HERA-Bench executable dataset
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +5 -0
- README.md +102 -0
- THIRD_PARTY_NOTICES.md +83 -0
- VALIDATION.json +168 -0
- benchmark.py +69 -0
- checksums.sha256 +0 -0
- data/environments/aws_release_review_v1/__init__.py +1 -0
- data/environments/aws_release_review_v1/domain_runtime.py +253 -0
- data/environments/aws_release_review_v1/endpoint_source.json +756 -0
- data/environments/aws_release_review_v1/environment.py +116 -0
- data/environments/aws_release_review_v1/schema.py +6 -0
- data/environments/eval60_ckan/__init__.py +1 -0
- data/environments/eval60_ckan/domain/domain_tools.py +126 -0
- data/environments/eval60_ckan/environment.py +108 -0
- data/environments/eval60_ckan/runtime.py +291 -0
- data/environments/eval60_ckan/vendor/rfc3339_validator.LICENSE +22 -0
- data/environments/eval60_ckan/vendor/rfc3339_validator.py +49 -0
- data/environments/eval60_datacite/__init__.py +1 -0
- data/environments/eval60_datacite/domain/domain_tools.py +56 -0
- data/environments/eval60_datacite/environment.py +108 -0
- data/environments/eval60_datacite/runtime.py +291 -0
- data/environments/eval60_datacite/vendor/rfc3339_validator.LICENSE +22 -0
- data/environments/eval60_datacite/vendor/rfc3339_validator.py +49 -0
- data/environments/eval60_erpnext/__init__.py +1 -0
- data/environments/eval60_erpnext/domain/domain_tools.py +146 -0
- data/environments/eval60_erpnext/environment.py +108 -0
- data/environments/eval60_erpnext/runtime.py +291 -0
- data/environments/eval60_erpnext/vendor/rfc3339_validator.LICENSE +22 -0
- data/environments/eval60_erpnext/vendor/rfc3339_validator.py +49 -0
- data/environments/eval60_europeana/__init__.py +1 -0
- data/environments/eval60_europeana/domain/domain_tools.py +159 -0
- data/environments/eval60_europeana/environment.py +108 -0
- data/environments/eval60_europeana/runtime.py +291 -0
- data/environments/eval60_europeana/vendor/rfc3339_validator.LICENSE +22 -0
- data/environments/eval60_europeana/vendor/rfc3339_validator.py +49 -0
- data/environments/eval60_gbif/__init__.py +1 -0
- data/environments/eval60_gbif/domain/domain_tools.py +131 -0
- data/environments/eval60_gbif/environment.py +108 -0
- data/environments/eval60_gbif/runtime.py +291 -0
- data/environments/eval60_gbif/vendor/rfc3339_validator.LICENSE +22 -0
- data/environments/eval60_gbif/vendor/rfc3339_validator.py +49 -0
- data/environments/eval60_gitlab/__init__.py +1 -0
- data/environments/eval60_gitlab/domain/domain_tools.py +168 -0
- data/environments/eval60_gitlab/environment.py +108 -0
- data/environments/eval60_gitlab/runtime.py +291 -0
- data/environments/eval60_gitlab/vendor/rfc3339_validator.LICENSE +22 -0
- data/environments/eval60_gitlab/vendor/rfc3339_validator.py +49 -0
- data/environments/eval60_inaturalist/__init__.py +1 -0
- data/environments/eval60_inaturalist/domain/domain_tools.py +239 -0
- data/environments/eval60_inaturalist/environment.py +108 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
*.json text eol=lf
|
| 62 |
+
*.jsonl text eol=lf
|
| 63 |
+
*.md text eol=lf
|
| 64 |
+
*.py text eol=lf
|
| 65 |
+
*.txt text eol=lf
|
README.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
pretty_name: HERA-Bench
|
| 3 |
+
license: cc-by-4.0
|
| 4 |
+
language:
|
| 5 |
+
- en
|
| 6 |
+
size_categories:
|
| 7 |
+
- n<1K
|
| 8 |
+
task_categories:
|
| 9 |
+
- other
|
| 10 |
+
tags:
|
| 11 |
+
- agentic-abstention
|
| 12 |
+
- tool-use
|
| 13 |
+
- evaluation
|
| 14 |
+
- benchmark
|
| 15 |
+
- executable-environments
|
| 16 |
+
- mcp
|
| 17 |
+
configs:
|
| 18 |
+
- config_name: default
|
| 19 |
+
default: true
|
| 20 |
+
data_files:
|
| 21 |
+
- split: test
|
| 22 |
+
path: index/test.jsonl
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
# HERA-Bench
|
| 26 |
+
|
| 27 |
+
HERA-Bench evaluates whether a tool-using agent can complete a feasible task and recognize when the same request cannot be fully satisfied. It accompanies *HERA: Harness–Environment Co-evolution for Reliable Agentic Abstention*.
|
| 28 |
+
|
| 29 |
+
[Code and harnesses](https://github.com/lhannnn/HERA-Bench) · [Project page](https://hera-bench.github.io/) · [Paper](https://arxiv.org/abs/2610.06563)
|
| 30 |
+
|
| 31 |
+
## Data
|
| 32 |
+
|
| 33 |
+
| Item | Count |
|
| 34 |
+
| --- | ---: |
|
| 35 |
+
| Matched task pairs | 60 |
|
| 36 |
+
| Feasible / should-abstain instances | 60 / 60 |
|
| 37 |
+
| Domain environment implementations | 58 |
|
| 38 |
+
| Shared document environment | 1 |
|
| 39 |
+
| Supporting briefs | 60 |
|
| 40 |
+
| Initial-state files | 240 |
|
| 41 |
+
|
| 42 |
+
Each pair shares a request, system prompt, and public tool interface. Its two environment states determine feasibility. A correct response to an infeasible task may be an evidence-grounded incomplete report, as specified by its brief. Environment counts identify implementation namespaces, not independent subject areas.
|
| 43 |
+
|
| 44 |
+
```text
|
| 45 |
+
index/test.jsonl 60 pair records
|
| 46 |
+
tasks.json Shared prompts
|
| 47 |
+
data/tasks/hera_NNN/ act/ and abstain/ initial states
|
| 48 |
+
data/environments/ Executable tools
|
| 49 |
+
public/briefs/ Supporting documents and report schemas
|
| 50 |
+
private/{pairs,bundles,controller}/
|
| 51 |
+
Routing, references, and grading
|
| 52 |
+
benchmark.py, runtime/ Environment execution
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
The index fields are `pair_id`, `number`, `action_type`, `environment`, `instruction`, `system_prompt`, `brief_path`, `pair_metadata_path`, `act_initial_state_paths`, and `abstain_initial_state_paths`. IDs run from `hera_001` to `hera_060`. All paths are relative to the repository root. See [schema](docs/SCHEMA.md) and [task inventory](docs/TASKS.md).
|
| 56 |
+
|
| 57 |
+
## Load and run
|
| 58 |
+
|
| 59 |
+
Load the pair index or download the complete executable dataset:
|
| 60 |
+
|
| 61 |
+
```python
|
| 62 |
+
from datasets import load_dataset
|
| 63 |
+
from huggingface_hub import snapshot_download
|
| 64 |
+
|
| 65 |
+
pairs = load_dataset("sxcn/HERA-Bench", split="test")
|
| 66 |
+
root = snapshot_download("sxcn/HERA-Bench", repo_type="dataset",
|
| 67 |
+
local_dir="HERA-Bench")
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
`load_dataset` reads the 60-row index; the complete download includes executable environments and grading. With Python 3.12, from the downloaded directory:
|
| 71 |
+
|
| 72 |
+
```bash
|
| 73 |
+
pip install -r requirements.txt
|
| 74 |
+
python -B benchmark.py verify
|
| 75 |
+
python -B benchmark.py serve --number 1 --side act --record ../episode.json
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
`verify` replays all 120 references offline without a model. `serve` exposes an MCP server over standard input/output. Use the [GitHub runner](https://github.com/lhannnn/HERA-Bench) to evaluate the base or final harness.
|
| 79 |
+
|
| 80 |
+
## Evaluation
|
| 81 |
+
|
| 82 |
+
For 60 pairs, **Act** is the percentage of correctly completed feasible instances; **Abstain** is the percentage of correct infeasible-instance responses; **Pair** requires both outcomes for the same pair. Use the supplied grader and retain failed episodes. [Evaluation details](docs/EVALUATION.md)
|
| 83 |
+
|
| 84 |
+
The solver receives only task prompts, public tools, and their observations. Keep side labels, initial states, reference solutions, and graders outside its context and filesystem access. `private/` denotes controller-only information during evaluation; these files are included for reproducibility.
|
| 85 |
+
|
| 86 |
+
This is a small English-language benchmark of local simulations. Tasks underwent author review and revision; the release does not certify untouched blind-test provenance or strict training-domain disjointness. Training and validation pools are not included. [Provenance](docs/PROVENANCE.md)
|
| 87 |
+
|
| 88 |
+
## License and citation
|
| 89 |
+
|
| 90 |
+
Dataset: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). Third-party components retain their [original notices](THIRD_PARTY_NOTICES.md); licensing of original accompanying code remains to be finalized.
|
| 91 |
+
|
| 92 |
+
```bibtex
|
| 93 |
+
@misc{luo2026heraharnessenvironmentcoevolutionreliable,
|
| 94 |
+
title = {HERA: Harness-Environment Co-Evolution for Reliable Agentic Abstention},
|
| 95 |
+
author = {Han Luo and Bingbing Wen and Guang Yang and Zora Zhiruo Wang and Pan Lu and Lucy Lu Wang},
|
| 96 |
+
year = {2026},
|
| 97 |
+
eprint = {2610.06563},
|
| 98 |
+
archivePrefix = {arXiv},
|
| 99 |
+
primaryClass = {cs.AI},
|
| 100 |
+
url = {https://arxiv.org/abs/2610.06563}
|
| 101 |
+
}
|
| 102 |
+
```
|
THIRD_PARTY_NOTICES.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Third-party notices
|
| 2 |
+
|
| 3 |
+
The existing source notices below are preserved verbatim. They apply to the corresponding components; they do not establish a license for the full benchmark.
|
| 4 |
+
|
| 5 |
+
- Vendored `rfc3339_validator` includes its MIT license and upstream author attribution.
|
| 6 |
+
- The AWS endpoint source includes its Apache-2.0 license and Amazon copyright notice.
|
| 7 |
+
|
| 8 |
+
## Included notice files
|
| 9 |
+
|
| 10 |
+
- [data/environments/eval60_ckan/vendor/rfc3339_validator.LICENSE](data/environments/eval60_ckan/vendor/rfc3339_validator.LICENSE)
|
| 11 |
+
- [data/environments/eval60_datacite/vendor/rfc3339_validator.LICENSE](data/environments/eval60_datacite/vendor/rfc3339_validator.LICENSE)
|
| 12 |
+
- [data/environments/eval60_erpnext/vendor/rfc3339_validator.LICENSE](data/environments/eval60_erpnext/vendor/rfc3339_validator.LICENSE)
|
| 13 |
+
- [data/environments/eval60_europeana/vendor/rfc3339_validator.LICENSE](data/environments/eval60_europeana/vendor/rfc3339_validator.LICENSE)
|
| 14 |
+
- [data/environments/eval60_gbif/vendor/rfc3339_validator.LICENSE](data/environments/eval60_gbif/vendor/rfc3339_validator.LICENSE)
|
| 15 |
+
- [data/environments/eval60_gitlab/vendor/rfc3339_validator.LICENSE](data/environments/eval60_gitlab/vendor/rfc3339_validator.LICENSE)
|
| 16 |
+
- [data/environments/eval60_inaturalist/vendor/rfc3339_validator.LICENSE](data/environments/eval60_inaturalist/vendor/rfc3339_validator.LICENSE)
|
| 17 |
+
- [data/environments/eval60_jenkins/vendor/rfc3339_validator.LICENSE](data/environments/eval60_jenkins/vendor/rfc3339_validator.LICENSE)
|
| 18 |
+
- [data/environments/eval60_musicbrainz/vendor/rfc3339_validator.LICENSE](data/environments/eval60_musicbrainz/vendor/rfc3339_validator.LICENSE)
|
| 19 |
+
- [data/environments/eval60_odoo/vendor/rfc3339_validator.LICENSE](data/environments/eval60_odoo/vendor/rfc3339_validator.LICENSE)
|
| 20 |
+
- [data/environments/eval60_openalex/vendor/rfc3339_validator.LICENSE](data/environments/eval60_openalex/vendor/rfc3339_validator.LICENSE)
|
| 21 |
+
- [data/environments/eval60_openlibrary/vendor/rfc3339_validator.LICENSE](data/environments/eval60_openlibrary/vendor/rfc3339_validator.LICENSE)
|
| 22 |
+
- [data/environments/eval60_openproject/vendor/rfc3339_validator.LICENSE](data/environments/eval60_openproject/vendor/rfc3339_validator.LICENSE)
|
| 23 |
+
- [data/environments/eval60_pretix/vendor/rfc3339_validator.LICENSE](data/environments/eval60_pretix/vendor/rfc3339_validator.LICENSE)
|
| 24 |
+
- [data/environments/eval60_snipeit/vendor/rfc3339_validator.LICENSE](data/environments/eval60_snipeit/vendor/rfc3339_validator.LICENSE)
|
| 25 |
+
- [data/environments/eval60_socrata/vendor/rfc3339_validator.LICENSE](data/environments/eval60_socrata/vendor/rfc3339_validator.LICENSE)
|
| 26 |
+
- [data/environments/eval60_wikidata/vendor/rfc3339_validator.LICENSE](data/environments/eval60_wikidata/vendor/rfc3339_validator.LICENSE)
|
| 27 |
+
- [data/environments/eval60_zenodo/vendor/rfc3339_validator.LICENSE](data/environments/eval60_zenodo/vendor/rfc3339_validator.LICENSE)
|
| 28 |
+
- [data/environments/eval60_zotero/vendor/rfc3339_validator.LICENSE](data/environments/eval60_zotero/vendor/rfc3339_validator.LICENSE)
|
| 29 |
+
- [data/environments/sol20_slot_04/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_04/vendor/rfc3339_validator.LICENSE)
|
| 30 |
+
- [data/environments/sol20_slot_05/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_05/vendor/rfc3339_validator.LICENSE)
|
| 31 |
+
- [data/environments/sol20_slot_06/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_06/vendor/rfc3339_validator.LICENSE)
|
| 32 |
+
- [data/environments/sol20_slot_07/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_07/vendor/rfc3339_validator.LICENSE)
|
| 33 |
+
- [data/environments/sol20_slot_08/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_08/vendor/rfc3339_validator.LICENSE)
|
| 34 |
+
- [data/environments/sol20_slot_09/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_09/vendor/rfc3339_validator.LICENSE)
|
| 35 |
+
- [data/environments/sol20_slot_10/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_10/vendor/rfc3339_validator.LICENSE)
|
| 36 |
+
- [data/environments/sol20_slot_11/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_11/vendor/rfc3339_validator.LICENSE)
|
| 37 |
+
- [data/environments/sol20_slot_12/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_12/vendor/rfc3339_validator.LICENSE)
|
| 38 |
+
- [data/environments/sol20_slot_13/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_13/vendor/rfc3339_validator.LICENSE)
|
| 39 |
+
- [data/environments/sol20_slot_14/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_14/vendor/rfc3339_validator.LICENSE)
|
| 40 |
+
- [data/environments/sol20_slot_15/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_15/vendor/rfc3339_validator.LICENSE)
|
| 41 |
+
- [data/environments/sol20_slot_16/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_16/vendor/rfc3339_validator.LICENSE)
|
| 42 |
+
- [data/environments/sol20_slot_17/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_17/vendor/rfc3339_validator.LICENSE)
|
| 43 |
+
- [data/environments/sol20_slot_18/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_18/vendor/rfc3339_validator.LICENSE)
|
| 44 |
+
- [data/environments/sol20_slot_19/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_19/vendor/rfc3339_validator.LICENSE)
|
| 45 |
+
- [data/environments/sol20_slot_20/vendor/rfc3339_validator.LICENSE](data/environments/sol20_slot_20/vendor/rfc3339_validator.LICENSE)
|
| 46 |
+
- [private/bundles/aws_release_v1/private/source/LICENSE](private/bundles/aws_release_v1/private/source/LICENSE)
|
| 47 |
+
- [private/bundles/aws_release_v1/private/source/NOTICE](private/bundles/aws_release_v1/private/source/NOTICE)
|
| 48 |
+
- [private/bundles/ckan/vendor/rfc3339_validator.LICENSE](private/bundles/ckan/vendor/rfc3339_validator.LICENSE)
|
| 49 |
+
- [private/bundles/datacite/vendor/rfc3339_validator.LICENSE](private/bundles/datacite/vendor/rfc3339_validator.LICENSE)
|
| 50 |
+
- [private/bundles/erpnext/vendor/rfc3339_validator.LICENSE](private/bundles/erpnext/vendor/rfc3339_validator.LICENSE)
|
| 51 |
+
- [private/bundles/europeana/vendor/rfc3339_validator.LICENSE](private/bundles/europeana/vendor/rfc3339_validator.LICENSE)
|
| 52 |
+
- [private/bundles/gbif/vendor/rfc3339_validator.LICENSE](private/bundles/gbif/vendor/rfc3339_validator.LICENSE)
|
| 53 |
+
- [private/bundles/gitlab/vendor/rfc3339_validator.LICENSE](private/bundles/gitlab/vendor/rfc3339_validator.LICENSE)
|
| 54 |
+
- [private/bundles/inaturalist/vendor/rfc3339_validator.LICENSE](private/bundles/inaturalist/vendor/rfc3339_validator.LICENSE)
|
| 55 |
+
- [private/bundles/jenkins/vendor/rfc3339_validator.LICENSE](private/bundles/jenkins/vendor/rfc3339_validator.LICENSE)
|
| 56 |
+
- [private/bundles/musicbrainz/vendor/rfc3339_validator.LICENSE](private/bundles/musicbrainz/vendor/rfc3339_validator.LICENSE)
|
| 57 |
+
- [private/bundles/odoo/vendor/rfc3339_validator.LICENSE](private/bundles/odoo/vendor/rfc3339_validator.LICENSE)
|
| 58 |
+
- [private/bundles/openalex/vendor/rfc3339_validator.LICENSE](private/bundles/openalex/vendor/rfc3339_validator.LICENSE)
|
| 59 |
+
- [private/bundles/openlibrary/vendor/rfc3339_validator.LICENSE](private/bundles/openlibrary/vendor/rfc3339_validator.LICENSE)
|
| 60 |
+
- [private/bundles/openproject/vendor/rfc3339_validator.LICENSE](private/bundles/openproject/vendor/rfc3339_validator.LICENSE)
|
| 61 |
+
- [private/bundles/pretix/vendor/rfc3339_validator.LICENSE](private/bundles/pretix/vendor/rfc3339_validator.LICENSE)
|
| 62 |
+
- [private/bundles/slot_04/vendor/rfc3339_validator.LICENSE](private/bundles/slot_04/vendor/rfc3339_validator.LICENSE)
|
| 63 |
+
- [private/bundles/slot_05/vendor/rfc3339_validator.LICENSE](private/bundles/slot_05/vendor/rfc3339_validator.LICENSE)
|
| 64 |
+
- [private/bundles/slot_06/vendor/rfc3339_validator.LICENSE](private/bundles/slot_06/vendor/rfc3339_validator.LICENSE)
|
| 65 |
+
- [private/bundles/slot_07/vendor/rfc3339_validator.LICENSE](private/bundles/slot_07/vendor/rfc3339_validator.LICENSE)
|
| 66 |
+
- [private/bundles/slot_08/vendor/rfc3339_validator.LICENSE](private/bundles/slot_08/vendor/rfc3339_validator.LICENSE)
|
| 67 |
+
- [private/bundles/slot_09/vendor/rfc3339_validator.LICENSE](private/bundles/slot_09/vendor/rfc3339_validator.LICENSE)
|
| 68 |
+
- [private/bundles/slot_10/vendor/rfc3339_validator.LICENSE](private/bundles/slot_10/vendor/rfc3339_validator.LICENSE)
|
| 69 |
+
- [private/bundles/slot_11/vendor/rfc3339_validator.LICENSE](private/bundles/slot_11/vendor/rfc3339_validator.LICENSE)
|
| 70 |
+
- [private/bundles/slot_12/vendor/rfc3339_validator.LICENSE](private/bundles/slot_12/vendor/rfc3339_validator.LICENSE)
|
| 71 |
+
- [private/bundles/slot_13/vendor/rfc3339_validator.LICENSE](private/bundles/slot_13/vendor/rfc3339_validator.LICENSE)
|
| 72 |
+
- [private/bundles/slot_14/vendor/rfc3339_validator.LICENSE](private/bundles/slot_14/vendor/rfc3339_validator.LICENSE)
|
| 73 |
+
- [private/bundles/slot_15/vendor/rfc3339_validator.LICENSE](private/bundles/slot_15/vendor/rfc3339_validator.LICENSE)
|
| 74 |
+
- [private/bundles/slot_16/vendor/rfc3339_validator.LICENSE](private/bundles/slot_16/vendor/rfc3339_validator.LICENSE)
|
| 75 |
+
- [private/bundles/slot_17/vendor/rfc3339_validator.LICENSE](private/bundles/slot_17/vendor/rfc3339_validator.LICENSE)
|
| 76 |
+
- [private/bundles/slot_18/vendor/rfc3339_validator.LICENSE](private/bundles/slot_18/vendor/rfc3339_validator.LICENSE)
|
| 77 |
+
- [private/bundles/slot_19/vendor/rfc3339_validator.LICENSE](private/bundles/slot_19/vendor/rfc3339_validator.LICENSE)
|
| 78 |
+
- [private/bundles/slot_20/vendor/rfc3339_validator.LICENSE](private/bundles/slot_20/vendor/rfc3339_validator.LICENSE)
|
| 79 |
+
- [private/bundles/snipeit/vendor/rfc3339_validator.LICENSE](private/bundles/snipeit/vendor/rfc3339_validator.LICENSE)
|
| 80 |
+
- [private/bundles/socrata/vendor/rfc3339_validator.LICENSE](private/bundles/socrata/vendor/rfc3339_validator.LICENSE)
|
| 81 |
+
- [private/bundles/wikidata/vendor/rfc3339_validator.LICENSE](private/bundles/wikidata/vendor/rfc3339_validator.LICENSE)
|
| 82 |
+
- [private/bundles/zenodo/vendor/rfc3339_validator.LICENSE](private/bundles/zenodo/vendor/rfc3339_validator.LICENSE)
|
| 83 |
+
- [private/bundles/zotero/vendor/rfc3339_validator.LICENSE](private/bundles/zotero/vendor/rfc3339_validator.LICENSE)
|
VALIDATION.json
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"release": "HERA-Bench with HERA environment runtime",
|
| 3 |
+
"date": "2026-10-16",
|
| 4 |
+
"passed": true,
|
| 5 |
+
"counts": {
|
| 6 |
+
"pairs": 60,
|
| 7 |
+
"instances": 120,
|
| 8 |
+
"feasible": 60,
|
| 9 |
+
"should_abstain": 60,
|
| 10 |
+
"domain_environments": 58,
|
| 11 |
+
"shared_document_environments": 1,
|
| 12 |
+
"initial_state_files": 240,
|
| 13 |
+
"public_briefs": 60,
|
| 14 |
+
"controller_pair_records": 60,
|
| 15 |
+
"bundle_runtimes": 40,
|
| 16 |
+
"native_pairs": 20
|
| 17 |
+
},
|
| 18 |
+
"preservation": {
|
| 19 |
+
"initial_states_byte_identical": 240,
|
| 20 |
+
"paired_prompts_unchanged": true,
|
| 21 |
+
"reference_programs_unchanged": true,
|
| 22 |
+
"domain_transitions_unchanged": true,
|
| 23 |
+
"grading_code_unchanged": true,
|
| 24 |
+
"environment_import_updates": 59
|
| 25 |
+
},
|
| 26 |
+
"executable_verification": {
|
| 27 |
+
"domain_calls": 613,
|
| 28 |
+
"failures": [],
|
| 29 |
+
"model_calls": 0,
|
| 30 |
+
"network_disabled": true,
|
| 31 |
+
"pairs": 60,
|
| 32 |
+
"passed": true,
|
| 33 |
+
"passed_sides": 120,
|
| 34 |
+
"sides": 120
|
| 35 |
+
},
|
| 36 |
+
"runtime_comparison": {
|
| 37 |
+
"instances": 120,
|
| 38 |
+
"public_tool_definitions_identical": true,
|
| 39 |
+
"reference_answers_events_and_states_identical": true,
|
| 40 |
+
"grading_results_identical": true,
|
| 41 |
+
"model_calls": 0
|
| 42 |
+
},
|
| 43 |
+
"previous_release_validation": {
|
| 44 |
+
"release": "HERA-Bench private release; neutral task directories",
|
| 45 |
+
"date": "2026-09-29",
|
| 46 |
+
"passed": true,
|
| 47 |
+
"source_archive_sha256": "16a646326df65e50b66dd716d817e1a169201faac1229256075b8d56b8277539",
|
| 48 |
+
"counts": {
|
| 49 |
+
"pairs": 60,
|
| 50 |
+
"instances": 120,
|
| 51 |
+
"feasible": 60,
|
| 52 |
+
"should_abstain": 60,
|
| 53 |
+
"domain_environments": 58,
|
| 54 |
+
"shared_document_environments": 1,
|
| 55 |
+
"initial_state_files": 240,
|
| 56 |
+
"public_briefs": 60,
|
| 57 |
+
"controller_pair_records": 60,
|
| 58 |
+
"bundle_runtimes": 40,
|
| 59 |
+
"native_pairs": 20
|
| 60 |
+
},
|
| 61 |
+
"action_types": {
|
| 62 |
+
"informational": 52,
|
| 63 |
+
"operational": 2,
|
| 64 |
+
"state_changing": 6
|
| 65 |
+
},
|
| 66 |
+
"preservation": {
|
| 67 |
+
"source_files_byte_identical_with_path_mapping": 923,
|
| 68 |
+
"routing_records_with_path_only_changes": 60,
|
| 69 |
+
"initial_states_byte_identical": 240,
|
| 70 |
+
"paired_prompts_unchanged": true,
|
| 71 |
+
"all_environment_and_scoring_code_byte_identical": true,
|
| 72 |
+
"legacy_failure_taxonomy_removed_from_current_tree": true,
|
| 73 |
+
"task_ids_and_feasibility_labels_unchanged": true
|
| 74 |
+
},
|
| 75 |
+
"formats": {
|
| 76 |
+
"utf8": true,
|
| 77 |
+
"duplicate_json_keys_rejected": true,
|
| 78 |
+
"python_files_parsed": 461,
|
| 79 |
+
"index_jsonl_rows": 60,
|
| 80 |
+
"index_fields": 10,
|
| 81 |
+
"all_json_and_report_schemas_valid": true,
|
| 82 |
+
"all_ids_unique_and_paired": true,
|
| 83 |
+
"all_index_paths_resolve": true,
|
| 84 |
+
"local_markdown_links_resolve": true
|
| 85 |
+
},
|
| 86 |
+
"executable_verification": {
|
| 87 |
+
"domain_calls": 613,
|
| 88 |
+
"failures": [],
|
| 89 |
+
"model_calls": 0,
|
| 90 |
+
"network_disabled": true,
|
| 91 |
+
"pairs": 60,
|
| 92 |
+
"passed": true,
|
| 93 |
+
"passed_sides": 120,
|
| 94 |
+
"sides": 120
|
| 95 |
+
},
|
| 96 |
+
"relocated_verification": {
|
| 97 |
+
"domain_calls": 613,
|
| 98 |
+
"failures": [],
|
| 99 |
+
"model_calls": 0,
|
| 100 |
+
"network_disabled": true,
|
| 101 |
+
"pairs": 60,
|
| 102 |
+
"passed": true,
|
| 103 |
+
"passed_sides": 120,
|
| 104 |
+
"sides": 120
|
| 105 |
+
},
|
| 106 |
+
"stdio_verification": {
|
| 107 |
+
"passed": true,
|
| 108 |
+
"relocated": true,
|
| 109 |
+
"isolated_python": true,
|
| 110 |
+
"unrelated_working_directory": true,
|
| 111 |
+
"cases": [
|
| 112 |
+
{
|
| 113 |
+
"number": 1,
|
| 114 |
+
"side": "abstain",
|
| 115 |
+
"passed": true,
|
| 116 |
+
"domain_calls": 4
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"number": 46,
|
| 120 |
+
"side": "act",
|
| 121 |
+
"passed": true,
|
| 122 |
+
"domain_calls": 4
|
| 123 |
+
}
|
| 124 |
+
]
|
| 125 |
+
},
|
| 126 |
+
"historical_grading_parity": {
|
| 127 |
+
"passed": true,
|
| 128 |
+
"recorded_episodes": 120,
|
| 129 |
+
"gradable_episodes_compared": 120,
|
| 130 |
+
"solver_runtime_failures_outside_dataset_scoring": 0,
|
| 131 |
+
"differences": [],
|
| 132 |
+
"api_calls": 0
|
| 133 |
+
},
|
| 134 |
+
"hugging_face": {
|
| 135 |
+
"local_load_dataset_passed": true,
|
| 136 |
+
"rows": 60,
|
| 137 |
+
"configs": [
|
| 138 |
+
"default"
|
| 139 |
+
],
|
| 140 |
+
"splits": [
|
| 141 |
+
"test"
|
| 142 |
+
],
|
| 143 |
+
"tested_datasets_versions": [
|
| 144 |
+
"4.8.5"
|
| 145 |
+
],
|
| 146 |
+
"huggingface_hub_version": "1.33.0",
|
| 147 |
+
"remote_load_dataset": true,
|
| 148 |
+
"remote_tested_revision": "a1c1dc7161cdbb019d3e380750b1605b9d15598e",
|
| 149 |
+
"remote_index_rows": 60,
|
| 150 |
+
"remote_index_exact_match": true,
|
| 151 |
+
"dataset_card_server_validation": true,
|
| 152 |
+
"downloaded_files_sha256_verified": 994,
|
| 153 |
+
"repository_private_verified": true,
|
| 154 |
+
"verification_note": "All 994 files were downloaded and verified at remote_tested_revision. This documentation-only follow-up records those results and refreshes checksums; benchmark data and executable code are unchanged."
|
| 155 |
+
},
|
| 156 |
+
"privacy_and_cleanup": {
|
| 157 |
+
"credential_findings": 0,
|
| 158 |
+
"machine_specific_path_findings": 0,
|
| 159 |
+
"unreviewed_contact_findings": 0,
|
| 160 |
+
"symlinks": 0,
|
| 161 |
+
"cache_temporary_and_internal_work_files": 0,
|
| 162 |
+
"reviewed_contacts": "Synthetic fixture identifiers and upstream attribution retained."
|
| 163 |
+
},
|
| 164 |
+
"scope": "Structural checks, offline reference verification, and parity with recorded verdicts; no new model evaluation or semantic reannotation.",
|
| 165 |
+
"checksums": "checksums.sha256 covers every release file except itself."
|
| 166 |
+
},
|
| 167 |
+
"checksums": "checksums.sha256 covers every release file except itself."
|
| 168 |
+
}
|
benchmark.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dataset controller: expose tools, replay references, and grade recorded episodes."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import argparse
|
| 4 |
+
import asyncio
|
| 5 |
+
import json
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
sys.dont_write_bytecode = True
|
| 9 |
+
ROOT = Path(__file__).resolve().parent
|
| 10 |
+
sys.path.insert(0, str(ROOT / 'private/controller'))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def main():
|
| 14 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 15 |
+
commands = parser.add_subparsers(dest='command', required=True)
|
| 16 |
+
listing = commands.add_parser('list', help='Print public task prompts')
|
| 17 |
+
listing.add_argument('--number', type=int, choices=range(1, 61))
|
| 18 |
+
for name in ('reference', 'serve', 'grade'):
|
| 19 |
+
p = commands.add_parser(name)
|
| 20 |
+
p.add_argument('--number', type=int, choices=range(1, 61), required=True)
|
| 21 |
+
p.add_argument('--side', choices=('act', 'abstain'), required=True)
|
| 22 |
+
if name == 'serve':
|
| 23 |
+
p.add_argument('--record', type=Path, help='New controller-only trace/state file')
|
| 24 |
+
else:
|
| 25 |
+
p.add_argument('--output', type=Path)
|
| 26 |
+
if name == 'grade':
|
| 27 |
+
p.add_argument('--submission', type=Path, required=True)
|
| 28 |
+
checking = commands.add_parser('verify', help='Check all references and public tool replays without a model')
|
| 29 |
+
checking.add_argument('--output', type=Path)
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
output = getattr(args, 'output', None)
|
| 32 |
+
if output is not None and output.exists():
|
| 33 |
+
parser.error('Output already exists; choose a new path')
|
| 34 |
+
|
| 35 |
+
from common import read, write
|
| 36 |
+
if args.command == 'list':
|
| 37 |
+
result = [t for t in read(ROOT / 'tasks.json')
|
| 38 |
+
if args.number is None or t['number'] == args.number]
|
| 39 |
+
elif args.command == 'serve':
|
| 40 |
+
from mcp_server import main as serve
|
| 41 |
+
asyncio.run(serve(ROOT, args.number, args.side, args.record))
|
| 42 |
+
return 0
|
| 43 |
+
elif args.command == 'verify':
|
| 44 |
+
from verify import verify
|
| 45 |
+
result = asyncio.run(verify(ROOT))
|
| 46 |
+
else:
|
| 47 |
+
from scoring import grade_submission, parse_answer
|
| 48 |
+
if args.command == 'grade':
|
| 49 |
+
submission = parse_answer(args.submission.read_text())
|
| 50 |
+
result = grade_submission(ROOT, args.number, args.side, submission)
|
| 51 |
+
else:
|
| 52 |
+
from evaluate import Episode
|
| 53 |
+
episode = Episode(ROOT, args.number, args.side)
|
| 54 |
+
answer = episode.solve()
|
| 55 |
+
result = {'answer': answer, 'events': episode.events, 'final_state': episode.state}
|
| 56 |
+
result['qualification'] = grade_submission(ROOT, args.number, args.side, result)
|
| 57 |
+
if output is not None:
|
| 58 |
+
write(output, result)
|
| 59 |
+
else:
|
| 60 |
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
| 61 |
+
if args.command in {'verify', 'grade'}:
|
| 62 |
+
return 0 if result['passed'] else 1
|
| 63 |
+
if args.command == 'reference':
|
| 64 |
+
return 0 if result['qualification']['passed'] else 1
|
| 65 |
+
return 0
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == '__main__':
|
| 69 |
+
raise SystemExit(main())
|
checksums.sha256
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/environments/aws_release_review_v1/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Manually authored evaluation overlay environment."""
|
data/environments/aws_release_review_v1/domain_runtime.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read-only mock release records plus a frozen, bounded AWS endpoint model.
|
| 2 |
+
|
| 3 |
+
Business records are simulated. Endpoint facts come only from the accompanying
|
| 4 |
+
digest-bound Smithy extraction, never from a release or an approved profile.
|
| 5 |
+
No network, external backend, dynamic import or argument-derived path is used.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from copy import deepcopy
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
ENDPOINT_SOURCE_SHA256 = '51e8ab670d780dc67f0908bef682731ee9f02fcb625420f61193b4209da19229'
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _canonical(value: Any) -> bytes:
|
| 20 |
+
return json.dumps(value, sort_keys=True, ensure_ascii=False,
|
| 21 |
+
separators=(',', ':'), allow_nan=False).encode('utf-8')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _digest(value: Any) -> str:
|
| 25 |
+
return hashlib.sha256(_canonical(value)).hexdigest()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _load_endpoint_source() -> dict:
|
| 29 |
+
# Only this controller-selected adjacent resource is opened. Tool arguments
|
| 30 |
+
# are never used as filenames, directory components or import targets.
|
| 31 |
+
path = Path(__file__).with_name('endpoint_source.json')
|
| 32 |
+
if path.is_symlink():
|
| 33 |
+
raise ValueError('Endpoint source must be a regular adjacent file')
|
| 34 |
+
raw = path.read_bytes()
|
| 35 |
+
if hashlib.sha256(raw).hexdigest() != ENDPOINT_SOURCE_SHA256:
|
| 36 |
+
raise ValueError('Frozen endpoint source SHA256 mismatch')
|
| 37 |
+
value = json.loads(raw)
|
| 38 |
+
if value.get('extraction_sha256') != _digest({k: v for k, v in value.items() if k != 'extraction_sha256'}):
|
| 39 |
+
raise ValueError('Endpoint extraction binding mismatch')
|
| 40 |
+
if value['source']['rule_set_sha256'] != _digest(value['rule_set']):
|
| 41 |
+
raise ValueError('Endpoint rule binding mismatch')
|
| 42 |
+
if value['source']['endpoint_tests_sha256'] != _digest(value['endpoint_tests']):
|
| 43 |
+
raise ValueError('Endpoint test binding mismatch')
|
| 44 |
+
return value
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
_SOURCE = _load_endpoint_source()
|
| 48 |
+
_RULES = _SOURCE['rule_set']['rules']
|
| 49 |
+
_DEFAULTS = {key: _SOURCE['rule_set']['parameters'][key]['default'] for key in ('UseFIPS', 'UseDualStack')}
|
| 50 |
+
_FIPS_CUSTOM_ERROR = _RULES[0]['rules'][0]['error']
|
| 51 |
+
_DUAL_CUSTOM_ERROR = _RULES[0]['rules'][1]['error']
|
| 52 |
+
_MISSING_REGION_ERROR = _RULES[-1]['error']
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _regional_urls() -> dict[tuple[str, bool, bool], str]:
|
| 56 |
+
"""Compile only source-verified regional combinations, not project answers.
|
| 57 |
+
|
| 58 |
+
The Smithy source delegates other cases to aws.partition, whose complete data
|
| 59 |
+
is not included in this frozen source. Absence of a tested combination does
|
| 60 |
+
not establish an unsupported AWS partition/variant.
|
| 61 |
+
"""
|
| 62 |
+
urls: dict[tuple[str, bool, bool], str] = {}
|
| 63 |
+
tests = _SOURCE['endpoint_tests']['testCases']
|
| 64 |
+
for scope in _SOURCE['authored_runtime_scope']['regional_parameter_combinations']:
|
| 65 |
+
case = tests[scope['test_index']]
|
| 66 |
+
params = case.get('params', {})
|
| 67 |
+
region = params.get('Region')
|
| 68 |
+
fips = params.get('UseFIPS', _DEFAULTS['UseFIPS'])
|
| 69 |
+
dual = params.get('UseDualStack', _DEFAULTS['UseDualStack'])
|
| 70 |
+
if (type(region) is not str or type(fips) is not bool or type(dual) is not bool
|
| 71 |
+
or params.get('Endpoint') is not None or 'endpoint' not in case['expect']):
|
| 72 |
+
raise ValueError('Regional scope does not bind a source endpoint case')
|
| 73 |
+
key = (region, fips, dual)
|
| 74 |
+
if scope != {'test_index': scope['test_index'], 'Region': region, 'UseFIPS': fips, 'UseDualStack': dual}:
|
| 75 |
+
raise ValueError('Regional parameter scope differs from its source test')
|
| 76 |
+
url = case['expect']['endpoint']['url']
|
| 77 |
+
if type(url) is not str or (key in urls and urls[key] != url):
|
| 78 |
+
raise ValueError('Ambiguous or invalid regional endpoint fact')
|
| 79 |
+
urls[key] = url
|
| 80 |
+
return urls
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
_REGIONAL_URLS = _regional_urls()
|
| 84 |
+
_COVERAGE_TEXT = (
|
| 85 |
+
'Regional coverage: us-east-1, cn-north-1 and us-gov-east-1 with all four '
|
| 86 |
+
'UseFIPS/UseDualStack combinations; ap-south-1 with both false; '
|
| 87 |
+
'us-iso-east-1 and us-isob-east-1 with UseDualStack false and either UseFIPS value. '
|
| 88 |
+
'Other regional combinations return outside_scope, not a claim that AWS rejects them.'
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _object_schema(properties: dict, required: list[str]) -> dict:
|
| 93 |
+
return {'type': 'object', 'properties': properties, 'required': required, 'additionalProperties': False}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
_IDENTIFIER = {'type': 'string', 'minLength': 1}
|
| 97 |
+
TOOL_SCHEMAS = [
|
| 98 |
+
{'name': 'get_release',
|
| 99 |
+
'description': 'Read a simulated release by application and release tag. Returns its release ID, production deployment ID, exact approved profile reference and binding policy. These references identify the subsequent public reads; an older profile version does not authorize this release.',
|
| 100 |
+
'input_schema': _object_schema({'application': deepcopy(_IDENTIFIER), 'release_tag': deepcopy(_IDENTIFIER)}, ['application', 'release_tag'])},
|
| 101 |
+
{'name': 'get_deployment',
|
| 102 |
+
'description': 'Read a simulated deployment by the deployment ID returned by get_release. Returns deployment_id, application, environment and the current Region, Endpoint, UseFIPS and UseDualStack connection values. Does not change or deploy anything.',
|
| 103 |
+
'input_schema': _object_schema({'deployment_id': deepcopy(_IDENTIFIER)}, ['deployment_id'])},
|
| 104 |
+
{'name': 'get_connection_profile',
|
| 105 |
+
'description': 'Read exactly the requested simulated connection profile version. Returns profile_id, version, approval_status and connection values only if that version is available. PROFILE_VERSION_UNAVAILABLE includes the requested reference and other available version numbers, never the unavailable settings or a substituted historical version.',
|
| 106 |
+
'input_schema': _object_schema({'profile_id': deepcopy(_IDENTIFIER), 'version': {'type': 'integer', 'minimum': 1}}, ['profile_id', 'version'])},
|
| 107 |
+
{'name': 'resolve_pricing_endpoint',
|
| 108 |
+
'description': 'Compute frozen, modeled AWS Price List endpoint behavior; no network availability is checked. Omitted UseFIPS/UseDualStack default to false; null flags are invalid. Omitted/null Region or Endpoint are unset. Any string Endpoint, including an empty string, is a literal override without URL validation: it takes priority over Region, conflicts with UseFIPS first and then UseDualStack. Missing Region without an override is a known configuration_error. Configuration errors are successful modeled results (ok=true); type/unknown-argument errors are tool failures. ' + _COVERAGE_TEXT,
|
| 109 |
+
'input_schema': _object_schema({
|
| 110 |
+
'Region': {'type': ['string', 'null'], 'default': None},
|
| 111 |
+
'Endpoint': {'type': ['string', 'null'], 'default': None},
|
| 112 |
+
'UseFIPS': {'type': 'boolean', 'default': False},
|
| 113 |
+
'UseDualStack': {'type': 'boolean', 'default': False}}, [])},
|
| 114 |
+
]
|
| 115 |
+
# A caller may copy/edit the advertised schema list without altering validation.
|
| 116 |
+
_SCHEMAS = {tool['name']: deepcopy(tool['input_schema']) for tool in TOOL_SCHEMAS}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _error(code: str, message: str, **details: Any) -> dict:
|
| 120 |
+
return {'ok': False, 'error': deepcopy({'code': code, 'message': message, **details})}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _ok(result: Any) -> dict:
|
| 124 |
+
return {'ok': True, 'result': deepcopy(result)}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _arguments_error(name: str, arguments: Any) -> str | None:
|
| 128 |
+
if type(arguments) is not dict:
|
| 129 |
+
return 'arguments must be an object'
|
| 130 |
+
schema = _SCHEMAS[name]
|
| 131 |
+
if any(type(key) is not str for key in arguments):
|
| 132 |
+
return 'argument names must be strings'
|
| 133 |
+
if set(arguments) - set(schema['properties']):
|
| 134 |
+
return 'unexpected argument fields'
|
| 135 |
+
if set(schema['required']) - set(arguments):
|
| 136 |
+
return 'required argument fields are missing'
|
| 137 |
+
for key, value in arguments.items():
|
| 138 |
+
prop = schema['properties'][key]
|
| 139 |
+
types = prop['type'] if type(prop['type']) is list else [prop['type']]
|
| 140 |
+
valid = (value is None and 'null' in types
|
| 141 |
+
or type(value) is str and 'string' in types
|
| 142 |
+
or type(value) is bool and 'boolean' in types
|
| 143 |
+
or type(value) is int and 'integer' in types)
|
| 144 |
+
if not valid:
|
| 145 |
+
return f'{key} has an invalid type'
|
| 146 |
+
if type(value) is str and len(value) < prop.get('minLength', 0):
|
| 147 |
+
return f'{key} must be nonempty'
|
| 148 |
+
if type(value) is int and value < prop.get('minimum', value):
|
| 149 |
+
return f'{key} is below its minimum'
|
| 150 |
+
return None
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _records(state: dict, table: str) -> dict:
|
| 154 |
+
value = state.get(table, {})
|
| 155 |
+
return value if type(value) is dict else {}
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _connection(record: dict) -> dict | None:
|
| 159 |
+
value = record.get('connection')
|
| 160 |
+
if type(value) is not dict or not all(key in value for key in ('Region', 'Endpoint', 'UseFIPS', 'UseDualStack')):
|
| 161 |
+
return None
|
| 162 |
+
if (any(value[key] is not None and type(value[key]) is not str for key in ('Region', 'Endpoint'))
|
| 163 |
+
or any(type(value[key]) is not bool for key in ('UseFIPS', 'UseDualStack'))):
|
| 164 |
+
return None
|
| 165 |
+
return {key: deepcopy(value[key]) for key in ('Region', 'Endpoint', 'UseFIPS', 'UseDualStack')}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _get_release(state: dict, args: dict) -> dict:
|
| 169 |
+
application, tag = args['application'], args['release_tag']
|
| 170 |
+
# Exact identity matching avoids composite-key delimiter collisions. Input
|
| 171 |
+
# strings containing '/', '..' or '@' are still ordinary IDs, never paths.
|
| 172 |
+
rows = [row for row in _records(state, 'releases').values() if type(row) is dict
|
| 173 |
+
and row.get('application') == application and row.get('release_tag') == tag]
|
| 174 |
+
if not rows:
|
| 175 |
+
return _error('RELEASE_NOT_FOUND', 'The requested release is not available.', application=application, release_tag=tag)
|
| 176 |
+
if len(rows) != 1:
|
| 177 |
+
return _error('STATE_RECORD_INVALID', 'Release identity is ambiguous.')
|
| 178 |
+
row = rows[0]
|
| 179 |
+
fields = ('release_id', 'application', 'release_tag', 'deployment_id', 'profile_binding_policy')
|
| 180 |
+
ref = row.get('approved_profile_ref')
|
| 181 |
+
if (any(type(row.get(key)) is not str or not row[key] for key in fields) or type(ref) is not dict
|
| 182 |
+
or type(ref.get('profile_id')) is not str or not ref['profile_id']
|
| 183 |
+
or type(ref.get('version')) is not int or ref['version'] < 1):
|
| 184 |
+
return _error('STATE_RECORD_INVALID', 'Release public record is incomplete.')
|
| 185 |
+
result = {key: row[key] for key in fields}
|
| 186 |
+
result['approved_profile_ref'] = {'profile_id': ref['profile_id'], 'version': ref['version']}
|
| 187 |
+
return _ok(result)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _get_deployment(state: dict, args: dict) -> dict:
|
| 191 |
+
identity = args['deployment_id']
|
| 192 |
+
row = _records(state, 'deployments').get(identity)
|
| 193 |
+
if type(row) is not dict:
|
| 194 |
+
return _error('DEPLOYMENT_NOT_FOUND', 'The requested deployment is not available.', deployment_id=identity)
|
| 195 |
+
connection = _connection(row)
|
| 196 |
+
if connection is None or any(type(row.get(key)) is not str for key in ('application', 'environment')):
|
| 197 |
+
return _error('STATE_RECORD_INVALID', 'Deployment public record is incomplete.')
|
| 198 |
+
return _ok({'deployment_id': identity, 'application': row['application'], 'environment': row['environment'], 'connection': connection})
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _get_profile(state: dict, args: dict) -> dict:
|
| 202 |
+
identity, version = args['profile_id'], args['version']
|
| 203 |
+
profiles = _records(state, 'profiles')
|
| 204 |
+
available = sorted({row['version'] for row in profiles.values() if type(row) is dict
|
| 205 |
+
and row.get('profile_id') == identity and type(row.get('version')) is int
|
| 206 |
+
and row['version'] >= 1 and row['version'] != version and row.get('availability') == 'available'})
|
| 207 |
+
row = profiles.get(f'{identity}@{version}')
|
| 208 |
+
if (type(row) is not dict or row.get('profile_id') != identity or type(row.get('version')) is not int
|
| 209 |
+
or row['version'] != version or row.get('availability') != 'available'):
|
| 210 |
+
return _error('PROFILE_VERSION_UNAVAILABLE', 'The exact requested profile version is unavailable; other versions cannot substitute for it.',
|
| 211 |
+
profile_id=identity, version=version, available_versions=available)
|
| 212 |
+
connection = _connection(row)
|
| 213 |
+
if connection is None or type(row.get('approval_status')) is not str:
|
| 214 |
+
return _error('STATE_RECORD_INVALID', 'Available profile public record is incomplete.')
|
| 215 |
+
return _ok({'profile_id': identity, 'version': version, 'approval_status': row['approval_status'], 'connection': connection})
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _endpoint(args: dict) -> dict:
|
| 219 |
+
region, override = args.get('Region'), args.get('Endpoint')
|
| 220 |
+
fips, dual = args.get('UseFIPS', _DEFAULTS['UseFIPS']), args.get('UseDualStack', _DEFAULTS['UseDualStack'])
|
| 221 |
+
if override is not None:
|
| 222 |
+
# These branches retain the exact source rule order. Region does not
|
| 223 |
+
# preempt a custom endpoint, even when it is missing/outside coverage.
|
| 224 |
+
if fips:
|
| 225 |
+
return _ok({'status': 'configuration_error', 'url': None, 'error': _FIPS_CUSTOM_ERROR})
|
| 226 |
+
if dual:
|
| 227 |
+
return _ok({'status': 'configuration_error', 'url': None, 'error': _DUAL_CUSTOM_ERROR})
|
| 228 |
+
return _ok({'status': 'resolved', 'url': override, 'error': None})
|
| 229 |
+
if region is None:
|
| 230 |
+
return _ok({'status': 'configuration_error', 'url': None, 'error': _MISSING_REGION_ERROR})
|
| 231 |
+
key = (region, fips, dual)
|
| 232 |
+
if key not in _REGIONAL_URLS:
|
| 233 |
+
return _ok({'status': 'outside_scope', 'url': None,
|
| 234 |
+
'error': 'The requested regional parameter combination is outside this frozen environment\'s verified coverage. This is not an AWS support or live availability claim.'})
|
| 235 |
+
return _ok({'status': 'resolved', 'url': _REGIONAL_URLS[key], 'error': None})
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def call_tool(state: dict, name: str, arguments: dict) -> dict:
|
| 239 |
+
"""Return a fresh JSON envelope; never mutate or return references to state."""
|
| 240 |
+
if type(name) is not str or name not in _SCHEMAS:
|
| 241 |
+
return _error('UNKNOWN_TOOL', 'The requested public tool does not exist.')
|
| 242 |
+
issue = _arguments_error(name, arguments)
|
| 243 |
+
if issue is not None:
|
| 244 |
+
return _error('INVALID_ARGUMENT', issue)
|
| 245 |
+
if type(state) is not dict:
|
| 246 |
+
return _error('INVALID_STATE', 'Environment state must be an object.')
|
| 247 |
+
if name == 'resolve_pricing_endpoint':
|
| 248 |
+
return _endpoint(arguments)
|
| 249 |
+
if name == 'get_release':
|
| 250 |
+
return _get_release(state, arguments)
|
| 251 |
+
if name == 'get_deployment':
|
| 252 |
+
return _get_deployment(state, arguments)
|
| 253 |
+
return _get_profile(state, arguments)
|
data/environments/aws_release_review_v1/endpoint_source.json
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"authored_runtime_scope": {
|
| 3 |
+
"generic_branches": [
|
| 4 |
+
"custom_endpoint_with_fips_precedence",
|
| 5 |
+
"custom_endpoint_with_dualstack_conflict",
|
| 6 |
+
"literal_custom_endpoint_passthrough",
|
| 7 |
+
"missing_region"
|
| 8 |
+
],
|
| 9 |
+
"live_network_validation": false,
|
| 10 |
+
"outside_scope_semantics": "Other regional flag combinations or regions are outside this frozen environment evidence coverage, not evidence that AWS does not support them.",
|
| 11 |
+
"provenance": "Manual environment scope; not an AWS service limitation claim.",
|
| 12 |
+
"regional_parameter_combinations": [
|
| 13 |
+
{
|
| 14 |
+
"Region": "ap-south-1",
|
| 15 |
+
"UseDualStack": false,
|
| 16 |
+
"UseFIPS": false,
|
| 17 |
+
"test_index": 0
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"Region": "us-east-1",
|
| 21 |
+
"UseDualStack": false,
|
| 22 |
+
"UseFIPS": false,
|
| 23 |
+
"test_index": 1
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"Region": "us-east-1",
|
| 27 |
+
"UseDualStack": true,
|
| 28 |
+
"UseFIPS": true,
|
| 29 |
+
"test_index": 2
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"Region": "us-east-1",
|
| 33 |
+
"UseDualStack": false,
|
| 34 |
+
"UseFIPS": true,
|
| 35 |
+
"test_index": 3
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"Region": "us-east-1",
|
| 39 |
+
"UseDualStack": true,
|
| 40 |
+
"UseFIPS": false,
|
| 41 |
+
"test_index": 4
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"Region": "cn-north-1",
|
| 45 |
+
"UseDualStack": true,
|
| 46 |
+
"UseFIPS": true,
|
| 47 |
+
"test_index": 5
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"Region": "cn-north-1",
|
| 51 |
+
"UseDualStack": false,
|
| 52 |
+
"UseFIPS": true,
|
| 53 |
+
"test_index": 6
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"Region": "cn-north-1",
|
| 57 |
+
"UseDualStack": true,
|
| 58 |
+
"UseFIPS": false,
|
| 59 |
+
"test_index": 7
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"Region": "cn-north-1",
|
| 63 |
+
"UseDualStack": false,
|
| 64 |
+
"UseFIPS": false,
|
| 65 |
+
"test_index": 8
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"Region": "us-gov-east-1",
|
| 69 |
+
"UseDualStack": true,
|
| 70 |
+
"UseFIPS": true,
|
| 71 |
+
"test_index": 9
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"Region": "us-gov-east-1",
|
| 75 |
+
"UseDualStack": false,
|
| 76 |
+
"UseFIPS": true,
|
| 77 |
+
"test_index": 10
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"Region": "us-gov-east-1",
|
| 81 |
+
"UseDualStack": true,
|
| 82 |
+
"UseFIPS": false,
|
| 83 |
+
"test_index": 11
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"Region": "us-gov-east-1",
|
| 87 |
+
"UseDualStack": false,
|
| 88 |
+
"UseFIPS": false,
|
| 89 |
+
"test_index": 12
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"Region": "us-iso-east-1",
|
| 93 |
+
"UseDualStack": false,
|
| 94 |
+
"UseFIPS": true,
|
| 95 |
+
"test_index": 13
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"Region": "us-iso-east-1",
|
| 99 |
+
"UseDualStack": false,
|
| 100 |
+
"UseFIPS": false,
|
| 101 |
+
"test_index": 14
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"Region": "us-isob-east-1",
|
| 105 |
+
"UseDualStack": false,
|
| 106 |
+
"UseFIPS": true,
|
| 107 |
+
"test_index": 15
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"Region": "us-isob-east-1",
|
| 111 |
+
"UseDualStack": false,
|
| 112 |
+
"UseFIPS": false,
|
| 113 |
+
"test_index": 16
|
| 114 |
+
}
|
| 115 |
+
]
|
| 116 |
+
},
|
| 117 |
+
"endpoint_tests": {
|
| 118 |
+
"testCases": [
|
| 119 |
+
{
|
| 120 |
+
"documentation": "For region ap-south-1 with FIPS disabled and DualStack disabled",
|
| 121 |
+
"expect": {
|
| 122 |
+
"endpoint": {
|
| 123 |
+
"url": "https://api.pricing.ap-south-1.amazonaws.com"
|
| 124 |
+
}
|
| 125 |
+
},
|
| 126 |
+
"params": {
|
| 127 |
+
"Region": "ap-south-1",
|
| 128 |
+
"UseDualStack": false,
|
| 129 |
+
"UseFIPS": false
|
| 130 |
+
}
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"documentation": "For region us-east-1 with FIPS disabled and DualStack disabled",
|
| 134 |
+
"expect": {
|
| 135 |
+
"endpoint": {
|
| 136 |
+
"url": "https://api.pricing.us-east-1.amazonaws.com"
|
| 137 |
+
}
|
| 138 |
+
},
|
| 139 |
+
"params": {
|
| 140 |
+
"Region": "us-east-1",
|
| 141 |
+
"UseDualStack": false,
|
| 142 |
+
"UseFIPS": false
|
| 143 |
+
}
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"documentation": "For region us-east-1 with FIPS enabled and DualStack enabled",
|
| 147 |
+
"expect": {
|
| 148 |
+
"endpoint": {
|
| 149 |
+
"url": "https://api.pricing-fips.us-east-1.api.aws"
|
| 150 |
+
}
|
| 151 |
+
},
|
| 152 |
+
"params": {
|
| 153 |
+
"Region": "us-east-1",
|
| 154 |
+
"UseDualStack": true,
|
| 155 |
+
"UseFIPS": true
|
| 156 |
+
}
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"documentation": "For region us-east-1 with FIPS enabled and DualStack disabled",
|
| 160 |
+
"expect": {
|
| 161 |
+
"endpoint": {
|
| 162 |
+
"url": "https://api.pricing-fips.us-east-1.amazonaws.com"
|
| 163 |
+
}
|
| 164 |
+
},
|
| 165 |
+
"params": {
|
| 166 |
+
"Region": "us-east-1",
|
| 167 |
+
"UseDualStack": false,
|
| 168 |
+
"UseFIPS": true
|
| 169 |
+
}
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"documentation": "For region us-east-1 with FIPS disabled and DualStack enabled",
|
| 173 |
+
"expect": {
|
| 174 |
+
"endpoint": {
|
| 175 |
+
"url": "https://api.pricing.us-east-1.api.aws"
|
| 176 |
+
}
|
| 177 |
+
},
|
| 178 |
+
"params": {
|
| 179 |
+
"Region": "us-east-1",
|
| 180 |
+
"UseDualStack": true,
|
| 181 |
+
"UseFIPS": false
|
| 182 |
+
}
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"documentation": "For region cn-north-1 with FIPS enabled and DualStack enabled",
|
| 186 |
+
"expect": {
|
| 187 |
+
"endpoint": {
|
| 188 |
+
"url": "https://api.pricing-fips.cn-north-1.api.amazonwebservices.com.cn"
|
| 189 |
+
}
|
| 190 |
+
},
|
| 191 |
+
"params": {
|
| 192 |
+
"Region": "cn-north-1",
|
| 193 |
+
"UseDualStack": true,
|
| 194 |
+
"UseFIPS": true
|
| 195 |
+
}
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"documentation": "For region cn-north-1 with FIPS enabled and DualStack disabled",
|
| 199 |
+
"expect": {
|
| 200 |
+
"endpoint": {
|
| 201 |
+
"url": "https://api.pricing-fips.cn-north-1.amazonaws.com.cn"
|
| 202 |
+
}
|
| 203 |
+
},
|
| 204 |
+
"params": {
|
| 205 |
+
"Region": "cn-north-1",
|
| 206 |
+
"UseDualStack": false,
|
| 207 |
+
"UseFIPS": true
|
| 208 |
+
}
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"documentation": "For region cn-north-1 with FIPS disabled and DualStack enabled",
|
| 212 |
+
"expect": {
|
| 213 |
+
"endpoint": {
|
| 214 |
+
"url": "https://api.pricing.cn-north-1.api.amazonwebservices.com.cn"
|
| 215 |
+
}
|
| 216 |
+
},
|
| 217 |
+
"params": {
|
| 218 |
+
"Region": "cn-north-1",
|
| 219 |
+
"UseDualStack": true,
|
| 220 |
+
"UseFIPS": false
|
| 221 |
+
}
|
| 222 |
+
},
|
| 223 |
+
{
|
| 224 |
+
"documentation": "For region cn-north-1 with FIPS disabled and DualStack disabled",
|
| 225 |
+
"expect": {
|
| 226 |
+
"endpoint": {
|
| 227 |
+
"url": "https://api.pricing.cn-north-1.amazonaws.com.cn"
|
| 228 |
+
}
|
| 229 |
+
},
|
| 230 |
+
"params": {
|
| 231 |
+
"Region": "cn-north-1",
|
| 232 |
+
"UseDualStack": false,
|
| 233 |
+
"UseFIPS": false
|
| 234 |
+
}
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"documentation": "For region us-gov-east-1 with FIPS enabled and DualStack enabled",
|
| 238 |
+
"expect": {
|
| 239 |
+
"endpoint": {
|
| 240 |
+
"url": "https://api.pricing-fips.us-gov-east-1.api.aws"
|
| 241 |
+
}
|
| 242 |
+
},
|
| 243 |
+
"params": {
|
| 244 |
+
"Region": "us-gov-east-1",
|
| 245 |
+
"UseDualStack": true,
|
| 246 |
+
"UseFIPS": true
|
| 247 |
+
}
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"documentation": "For region us-gov-east-1 with FIPS enabled and DualStack disabled",
|
| 251 |
+
"expect": {
|
| 252 |
+
"endpoint": {
|
| 253 |
+
"url": "https://api.pricing-fips.us-gov-east-1.amazonaws.com"
|
| 254 |
+
}
|
| 255 |
+
},
|
| 256 |
+
"params": {
|
| 257 |
+
"Region": "us-gov-east-1",
|
| 258 |
+
"UseDualStack": false,
|
| 259 |
+
"UseFIPS": true
|
| 260 |
+
}
|
| 261 |
+
},
|
| 262 |
+
{
|
| 263 |
+
"documentation": "For region us-gov-east-1 with FIPS disabled and DualStack enabled",
|
| 264 |
+
"expect": {
|
| 265 |
+
"endpoint": {
|
| 266 |
+
"url": "https://api.pricing.us-gov-east-1.api.aws"
|
| 267 |
+
}
|
| 268 |
+
},
|
| 269 |
+
"params": {
|
| 270 |
+
"Region": "us-gov-east-1",
|
| 271 |
+
"UseDualStack": true,
|
| 272 |
+
"UseFIPS": false
|
| 273 |
+
}
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"documentation": "For region us-gov-east-1 with FIPS disabled and DualStack disabled",
|
| 277 |
+
"expect": {
|
| 278 |
+
"endpoint": {
|
| 279 |
+
"url": "https://api.pricing.us-gov-east-1.amazonaws.com"
|
| 280 |
+
}
|
| 281 |
+
},
|
| 282 |
+
"params": {
|
| 283 |
+
"Region": "us-gov-east-1",
|
| 284 |
+
"UseDualStack": false,
|
| 285 |
+
"UseFIPS": false
|
| 286 |
+
}
|
| 287 |
+
},
|
| 288 |
+
{
|
| 289 |
+
"documentation": "For region us-iso-east-1 with FIPS enabled and DualStack disabled",
|
| 290 |
+
"expect": {
|
| 291 |
+
"endpoint": {
|
| 292 |
+
"url": "https://api.pricing-fips.us-iso-east-1.c2s.ic.gov"
|
| 293 |
+
}
|
| 294 |
+
},
|
| 295 |
+
"params": {
|
| 296 |
+
"Region": "us-iso-east-1",
|
| 297 |
+
"UseDualStack": false,
|
| 298 |
+
"UseFIPS": true
|
| 299 |
+
}
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"documentation": "For region us-iso-east-1 with FIPS disabled and DualStack disabled",
|
| 303 |
+
"expect": {
|
| 304 |
+
"endpoint": {
|
| 305 |
+
"url": "https://api.pricing.us-iso-east-1.c2s.ic.gov"
|
| 306 |
+
}
|
| 307 |
+
},
|
| 308 |
+
"params": {
|
| 309 |
+
"Region": "us-iso-east-1",
|
| 310 |
+
"UseDualStack": false,
|
| 311 |
+
"UseFIPS": false
|
| 312 |
+
}
|
| 313 |
+
},
|
| 314 |
+
{
|
| 315 |
+
"documentation": "For region us-isob-east-1 with FIPS enabled and DualStack disabled",
|
| 316 |
+
"expect": {
|
| 317 |
+
"endpoint": {
|
| 318 |
+
"url": "https://api.pricing-fips.us-isob-east-1.sc2s.sgov.gov"
|
| 319 |
+
}
|
| 320 |
+
},
|
| 321 |
+
"params": {
|
| 322 |
+
"Region": "us-isob-east-1",
|
| 323 |
+
"UseDualStack": false,
|
| 324 |
+
"UseFIPS": true
|
| 325 |
+
}
|
| 326 |
+
},
|
| 327 |
+
{
|
| 328 |
+
"documentation": "For region us-isob-east-1 with FIPS disabled and DualStack disabled",
|
| 329 |
+
"expect": {
|
| 330 |
+
"endpoint": {
|
| 331 |
+
"url": "https://api.pricing.us-isob-east-1.sc2s.sgov.gov"
|
| 332 |
+
}
|
| 333 |
+
},
|
| 334 |
+
"params": {
|
| 335 |
+
"Region": "us-isob-east-1",
|
| 336 |
+
"UseDualStack": false,
|
| 337 |
+
"UseFIPS": false
|
| 338 |
+
}
|
| 339 |
+
},
|
| 340 |
+
{
|
| 341 |
+
"documentation": "For custom endpoint with region set and fips disabled and dualstack disabled",
|
| 342 |
+
"expect": {
|
| 343 |
+
"endpoint": {
|
| 344 |
+
"url": "https://example.com"
|
| 345 |
+
}
|
| 346 |
+
},
|
| 347 |
+
"params": {
|
| 348 |
+
"Endpoint": "https://example.com",
|
| 349 |
+
"Region": "us-east-1",
|
| 350 |
+
"UseDualStack": false,
|
| 351 |
+
"UseFIPS": false
|
| 352 |
+
}
|
| 353 |
+
},
|
| 354 |
+
{
|
| 355 |
+
"documentation": "For custom endpoint with region not set and fips disabled and dualstack disabled",
|
| 356 |
+
"expect": {
|
| 357 |
+
"endpoint": {
|
| 358 |
+
"url": "https://example.com"
|
| 359 |
+
}
|
| 360 |
+
},
|
| 361 |
+
"params": {
|
| 362 |
+
"Endpoint": "https://example.com",
|
| 363 |
+
"UseDualStack": false,
|
| 364 |
+
"UseFIPS": false
|
| 365 |
+
}
|
| 366 |
+
},
|
| 367 |
+
{
|
| 368 |
+
"documentation": "For custom endpoint with fips enabled and dualstack disabled",
|
| 369 |
+
"expect": {
|
| 370 |
+
"error": "Invalid Configuration: FIPS and custom endpoint are not supported"
|
| 371 |
+
},
|
| 372 |
+
"params": {
|
| 373 |
+
"Endpoint": "https://example.com",
|
| 374 |
+
"Region": "us-east-1",
|
| 375 |
+
"UseDualStack": false,
|
| 376 |
+
"UseFIPS": true
|
| 377 |
+
}
|
| 378 |
+
},
|
| 379 |
+
{
|
| 380 |
+
"documentation": "For custom endpoint with fips disabled and dualstack enabled",
|
| 381 |
+
"expect": {
|
| 382 |
+
"error": "Invalid Configuration: Dualstack and custom endpoint are not supported"
|
| 383 |
+
},
|
| 384 |
+
"params": {
|
| 385 |
+
"Endpoint": "https://example.com",
|
| 386 |
+
"Region": "us-east-1",
|
| 387 |
+
"UseDualStack": true,
|
| 388 |
+
"UseFIPS": false
|
| 389 |
+
}
|
| 390 |
+
},
|
| 391 |
+
{
|
| 392 |
+
"documentation": "Missing region",
|
| 393 |
+
"expect": {
|
| 394 |
+
"error": "Invalid Configuration: Missing Region"
|
| 395 |
+
}
|
| 396 |
+
}
|
| 397 |
+
],
|
| 398 |
+
"version": "1.0"
|
| 399 |
+
},
|
| 400 |
+
"extraction_sha256": "b8c97076e99cb6cd0d0714ec12f9e845fe714146272b370216ccf6ad683c0d19",
|
| 401 |
+
"rule_set": {
|
| 402 |
+
"parameters": {
|
| 403 |
+
"Endpoint": {
|
| 404 |
+
"builtIn": "SDK::Endpoint",
|
| 405 |
+
"documentation": "Override the endpoint used to send this request",
|
| 406 |
+
"required": false,
|
| 407 |
+
"type": "string"
|
| 408 |
+
},
|
| 409 |
+
"Region": {
|
| 410 |
+
"builtIn": "AWS::Region",
|
| 411 |
+
"documentation": "The AWS region used to dispatch the request.",
|
| 412 |
+
"required": false,
|
| 413 |
+
"type": "string"
|
| 414 |
+
},
|
| 415 |
+
"UseDualStack": {
|
| 416 |
+
"builtIn": "AWS::UseDualStack",
|
| 417 |
+
"default": false,
|
| 418 |
+
"documentation": "When true, use the dual-stack endpoint. If the configured endpoint does not support dual-stack, dispatching the request MAY return an error.",
|
| 419 |
+
"required": true,
|
| 420 |
+
"type": "boolean"
|
| 421 |
+
},
|
| 422 |
+
"UseFIPS": {
|
| 423 |
+
"builtIn": "AWS::UseFIPS",
|
| 424 |
+
"default": false,
|
| 425 |
+
"documentation": "When true, send this request to the FIPS-compliant regional endpoint. If the configured endpoint does not have a FIPS compliant endpoint, dispatching the request will return an error.",
|
| 426 |
+
"required": true,
|
| 427 |
+
"type": "boolean"
|
| 428 |
+
}
|
| 429 |
+
},
|
| 430 |
+
"rules": [
|
| 431 |
+
{
|
| 432 |
+
"conditions": [
|
| 433 |
+
{
|
| 434 |
+
"argv": [
|
| 435 |
+
{
|
| 436 |
+
"ref": "Endpoint"
|
| 437 |
+
}
|
| 438 |
+
],
|
| 439 |
+
"fn": "isSet"
|
| 440 |
+
}
|
| 441 |
+
],
|
| 442 |
+
"rules": [
|
| 443 |
+
{
|
| 444 |
+
"conditions": [
|
| 445 |
+
{
|
| 446 |
+
"argv": [
|
| 447 |
+
{
|
| 448 |
+
"ref": "UseFIPS"
|
| 449 |
+
},
|
| 450 |
+
true
|
| 451 |
+
],
|
| 452 |
+
"fn": "booleanEquals"
|
| 453 |
+
}
|
| 454 |
+
],
|
| 455 |
+
"error": "Invalid Configuration: FIPS and custom endpoint are not supported",
|
| 456 |
+
"type": "error"
|
| 457 |
+
},
|
| 458 |
+
{
|
| 459 |
+
"conditions": [
|
| 460 |
+
{
|
| 461 |
+
"argv": [
|
| 462 |
+
{
|
| 463 |
+
"ref": "UseDualStack"
|
| 464 |
+
},
|
| 465 |
+
true
|
| 466 |
+
],
|
| 467 |
+
"fn": "booleanEquals"
|
| 468 |
+
}
|
| 469 |
+
],
|
| 470 |
+
"error": "Invalid Configuration: Dualstack and custom endpoint are not supported",
|
| 471 |
+
"type": "error"
|
| 472 |
+
},
|
| 473 |
+
{
|
| 474 |
+
"conditions": [],
|
| 475 |
+
"endpoint": {
|
| 476 |
+
"headers": {},
|
| 477 |
+
"properties": {},
|
| 478 |
+
"url": {
|
| 479 |
+
"ref": "Endpoint"
|
| 480 |
+
}
|
| 481 |
+
},
|
| 482 |
+
"type": "endpoint"
|
| 483 |
+
}
|
| 484 |
+
],
|
| 485 |
+
"type": "tree"
|
| 486 |
+
},
|
| 487 |
+
{
|
| 488 |
+
"conditions": [
|
| 489 |
+
{
|
| 490 |
+
"argv": [
|
| 491 |
+
{
|
| 492 |
+
"ref": "Region"
|
| 493 |
+
}
|
| 494 |
+
],
|
| 495 |
+
"fn": "isSet"
|
| 496 |
+
}
|
| 497 |
+
],
|
| 498 |
+
"rules": [
|
| 499 |
+
{
|
| 500 |
+
"conditions": [
|
| 501 |
+
{
|
| 502 |
+
"argv": [
|
| 503 |
+
{
|
| 504 |
+
"ref": "Region"
|
| 505 |
+
}
|
| 506 |
+
],
|
| 507 |
+
"assign": "PartitionResult",
|
| 508 |
+
"fn": "aws.partition"
|
| 509 |
+
}
|
| 510 |
+
],
|
| 511 |
+
"rules": [
|
| 512 |
+
{
|
| 513 |
+
"conditions": [
|
| 514 |
+
{
|
| 515 |
+
"argv": [
|
| 516 |
+
{
|
| 517 |
+
"ref": "UseFIPS"
|
| 518 |
+
},
|
| 519 |
+
true
|
| 520 |
+
],
|
| 521 |
+
"fn": "booleanEquals"
|
| 522 |
+
},
|
| 523 |
+
{
|
| 524 |
+
"argv": [
|
| 525 |
+
{
|
| 526 |
+
"ref": "UseDualStack"
|
| 527 |
+
},
|
| 528 |
+
true
|
| 529 |
+
],
|
| 530 |
+
"fn": "booleanEquals"
|
| 531 |
+
}
|
| 532 |
+
],
|
| 533 |
+
"rules": [
|
| 534 |
+
{
|
| 535 |
+
"conditions": [
|
| 536 |
+
{
|
| 537 |
+
"argv": [
|
| 538 |
+
true,
|
| 539 |
+
{
|
| 540 |
+
"argv": [
|
| 541 |
+
{
|
| 542 |
+
"ref": "PartitionResult"
|
| 543 |
+
},
|
| 544 |
+
"supportsFIPS"
|
| 545 |
+
],
|
| 546 |
+
"fn": "getAttr"
|
| 547 |
+
}
|
| 548 |
+
],
|
| 549 |
+
"fn": "booleanEquals"
|
| 550 |
+
},
|
| 551 |
+
{
|
| 552 |
+
"argv": [
|
| 553 |
+
true,
|
| 554 |
+
{
|
| 555 |
+
"argv": [
|
| 556 |
+
{
|
| 557 |
+
"ref": "PartitionResult"
|
| 558 |
+
},
|
| 559 |
+
"supportsDualStack"
|
| 560 |
+
],
|
| 561 |
+
"fn": "getAttr"
|
| 562 |
+
}
|
| 563 |
+
],
|
| 564 |
+
"fn": "booleanEquals"
|
| 565 |
+
}
|
| 566 |
+
],
|
| 567 |
+
"rules": [
|
| 568 |
+
{
|
| 569 |
+
"conditions": [],
|
| 570 |
+
"endpoint": {
|
| 571 |
+
"headers": {},
|
| 572 |
+
"properties": {},
|
| 573 |
+
"url": "https://api.pricing-fips.{Region}.{PartitionResult#dualStackDnsSuffix}"
|
| 574 |
+
},
|
| 575 |
+
"type": "endpoint"
|
| 576 |
+
}
|
| 577 |
+
],
|
| 578 |
+
"type": "tree"
|
| 579 |
+
},
|
| 580 |
+
{
|
| 581 |
+
"conditions": [],
|
| 582 |
+
"error": "FIPS and DualStack are enabled, but this partition does not support one or both",
|
| 583 |
+
"type": "error"
|
| 584 |
+
}
|
| 585 |
+
],
|
| 586 |
+
"type": "tree"
|
| 587 |
+
},
|
| 588 |
+
{
|
| 589 |
+
"conditions": [
|
| 590 |
+
{
|
| 591 |
+
"argv": [
|
| 592 |
+
{
|
| 593 |
+
"ref": "UseFIPS"
|
| 594 |
+
},
|
| 595 |
+
true
|
| 596 |
+
],
|
| 597 |
+
"fn": "booleanEquals"
|
| 598 |
+
}
|
| 599 |
+
],
|
| 600 |
+
"rules": [
|
| 601 |
+
{
|
| 602 |
+
"conditions": [
|
| 603 |
+
{
|
| 604 |
+
"argv": [
|
| 605 |
+
{
|
| 606 |
+
"argv": [
|
| 607 |
+
{
|
| 608 |
+
"ref": "PartitionResult"
|
| 609 |
+
},
|
| 610 |
+
"supportsFIPS"
|
| 611 |
+
],
|
| 612 |
+
"fn": "getAttr"
|
| 613 |
+
},
|
| 614 |
+
true
|
| 615 |
+
],
|
| 616 |
+
"fn": "booleanEquals"
|
| 617 |
+
}
|
| 618 |
+
],
|
| 619 |
+
"rules": [
|
| 620 |
+
{
|
| 621 |
+
"conditions": [],
|
| 622 |
+
"endpoint": {
|
| 623 |
+
"headers": {},
|
| 624 |
+
"properties": {},
|
| 625 |
+
"url": "https://api.pricing-fips.{Region}.{PartitionResult#dnsSuffix}"
|
| 626 |
+
},
|
| 627 |
+
"type": "endpoint"
|
| 628 |
+
}
|
| 629 |
+
],
|
| 630 |
+
"type": "tree"
|
| 631 |
+
},
|
| 632 |
+
{
|
| 633 |
+
"conditions": [],
|
| 634 |
+
"error": "FIPS is enabled but this partition does not support FIPS",
|
| 635 |
+
"type": "error"
|
| 636 |
+
}
|
| 637 |
+
],
|
| 638 |
+
"type": "tree"
|
| 639 |
+
},
|
| 640 |
+
{
|
| 641 |
+
"conditions": [
|
| 642 |
+
{
|
| 643 |
+
"argv": [
|
| 644 |
+
{
|
| 645 |
+
"ref": "UseDualStack"
|
| 646 |
+
},
|
| 647 |
+
true
|
| 648 |
+
],
|
| 649 |
+
"fn": "booleanEquals"
|
| 650 |
+
}
|
| 651 |
+
],
|
| 652 |
+
"rules": [
|
| 653 |
+
{
|
| 654 |
+
"conditions": [
|
| 655 |
+
{
|
| 656 |
+
"argv": [
|
| 657 |
+
true,
|
| 658 |
+
{
|
| 659 |
+
"argv": [
|
| 660 |
+
{
|
| 661 |
+
"ref": "PartitionResult"
|
| 662 |
+
},
|
| 663 |
+
"supportsDualStack"
|
| 664 |
+
],
|
| 665 |
+
"fn": "getAttr"
|
| 666 |
+
}
|
| 667 |
+
],
|
| 668 |
+
"fn": "booleanEquals"
|
| 669 |
+
}
|
| 670 |
+
],
|
| 671 |
+
"rules": [
|
| 672 |
+
{
|
| 673 |
+
"conditions": [],
|
| 674 |
+
"endpoint": {
|
| 675 |
+
"headers": {},
|
| 676 |
+
"properties": {},
|
| 677 |
+
"url": "https://api.pricing.{Region}.{PartitionResult#dualStackDnsSuffix}"
|
| 678 |
+
},
|
| 679 |
+
"type": "endpoint"
|
| 680 |
+
}
|
| 681 |
+
],
|
| 682 |
+
"type": "tree"
|
| 683 |
+
},
|
| 684 |
+
{
|
| 685 |
+
"conditions": [],
|
| 686 |
+
"error": "DualStack is enabled but this partition does not support DualStack",
|
| 687 |
+
"type": "error"
|
| 688 |
+
}
|
| 689 |
+
],
|
| 690 |
+
"type": "tree"
|
| 691 |
+
},
|
| 692 |
+
{
|
| 693 |
+
"conditions": [
|
| 694 |
+
{
|
| 695 |
+
"argv": [
|
| 696 |
+
"aws",
|
| 697 |
+
{
|
| 698 |
+
"argv": [
|
| 699 |
+
{
|
| 700 |
+
"ref": "PartitionResult"
|
| 701 |
+
},
|
| 702 |
+
"name"
|
| 703 |
+
],
|
| 704 |
+
"fn": "getAttr"
|
| 705 |
+
}
|
| 706 |
+
],
|
| 707 |
+
"fn": "stringEquals"
|
| 708 |
+
}
|
| 709 |
+
],
|
| 710 |
+
"endpoint": {
|
| 711 |
+
"headers": {},
|
| 712 |
+
"properties": {},
|
| 713 |
+
"url": "https://api.pricing.{Region}.amazonaws.com"
|
| 714 |
+
},
|
| 715 |
+
"type": "endpoint"
|
| 716 |
+
},
|
| 717 |
+
{
|
| 718 |
+
"conditions": [],
|
| 719 |
+
"endpoint": {
|
| 720 |
+
"headers": {},
|
| 721 |
+
"properties": {},
|
| 722 |
+
"url": "https://api.pricing.{Region}.{PartitionResult#dnsSuffix}"
|
| 723 |
+
},
|
| 724 |
+
"type": "endpoint"
|
| 725 |
+
}
|
| 726 |
+
],
|
| 727 |
+
"type": "tree"
|
| 728 |
+
}
|
| 729 |
+
],
|
| 730 |
+
"type": "tree"
|
| 731 |
+
},
|
| 732 |
+
{
|
| 733 |
+
"conditions": [],
|
| 734 |
+
"error": "Invalid Configuration: Missing Region",
|
| 735 |
+
"type": "error"
|
| 736 |
+
}
|
| 737 |
+
],
|
| 738 |
+
"version": "1.0"
|
| 739 |
+
},
|
| 740 |
+
"schema": "manual_eval.aws_pricing_endpoint_source.v1",
|
| 741 |
+
"source": {
|
| 742 |
+
"canonical_record_sha256": "ae5d5cefb4da0528f97d9660b2fcfba4f9db65ff68e64006c392c6cb8e88c75d",
|
| 743 |
+
"content_sha256": "10d539ecd3af293775d3d1bfef7216e2eb3f9a3721e47128167dac8dc3454d58",
|
| 744 |
+
"content_utf8_bytes": 67901,
|
| 745 |
+
"endpoint_tests_pointer": "/shapes/com.amazonaws.pricing#AWSPriceListService/traits/smithy.rules#endpointTests",
|
| 746 |
+
"endpoint_tests_sha256": "9efaad181ff7d21853c64098687723561fa27c0f198febe6eeaf04110230a587",
|
| 747 |
+
"frozen_context_sha256": "5034fe253fe7ed23d91bcf16595b348462e94d8e065009beff0ef1b2b6c348a7",
|
| 748 |
+
"raw_record_sha256": "0264a654212c41a6a32a231a44ea435e2de5947bf9a0642d6dbd9289e67cf8ab",
|
| 749 |
+
"rule_set_pointer": "/shapes/com.amazonaws.pricing#AWSPriceListService/traits/smithy.rules#endpointRuleSet",
|
| 750 |
+
"rule_set_sha256": "e623f6b5a5c99aa7f8d18462854d1e679924eeea443f40c9abb7659eb5a9ce66",
|
| 751 |
+
"service_shape": "com.amazonaws.pricing#AWSPriceListService",
|
| 752 |
+
"service_version": "2017-10-15",
|
| 753 |
+
"smithy_version": "2.0",
|
| 754 |
+
"uri": "https://github.com/aws/api-models-aws/blob/583dfa8959ed24569befb6c6c0e971e229802905/models/pricing/service/2017-10-15/pricing-2017-10-15.json"
|
| 755 |
+
}
|
| 756 |
+
}
|
data/environments/aws_release_review_v1/environment.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent read-only adapter; domain rules live in domain_runtime."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import copy
|
| 5 |
+
import json
|
| 6 |
+
from typing import Any, Callable
|
| 7 |
+
|
| 8 |
+
from fastmcp.tools import Tool
|
| 9 |
+
from fastmcp.tools.tool import ToolResult
|
| 10 |
+
from jsonschema import Draft202012Validator
|
| 11 |
+
from pydantic import Field
|
| 12 |
+
|
| 13 |
+
from hera_environment import BaseEnvironment, ToolError
|
| 14 |
+
from . import domain_runtime
|
| 15 |
+
from .schema import EMPTY_STATE, EXAMPLE_STATE, STATE_SCHEMA
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class _DomainTool(Tool):
|
| 19 |
+
# A callable field also preserves BaseEnvironment.get_tool_callable and
|
| 20 |
+
# its broken-tool replacement convention. Parameters retain the exact
|
| 21 |
+
# domain JSON Schema instead of being inferred from a generic **kwargs.
|
| 22 |
+
fn: Callable[..., Any] = Field(exclude=True)
|
| 23 |
+
|
| 24 |
+
async def run(self, arguments: dict[str, Any]) -> ToolResult:
|
| 25 |
+
envelope = self.fn(**arguments)
|
| 26 |
+
return ToolResult(
|
| 27 |
+
content=json.dumps(envelope, ensure_ascii=False, allow_nan=False),
|
| 28 |
+
structured_content=envelope,
|
| 29 |
+
is_error=envelope["ok"] is False,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Environment(BaseEnvironment):
|
| 34 |
+
env_name = 'aws_release_review_v1'
|
| 35 |
+
short_name = 'AWS Release Configuration Review'
|
| 36 |
+
always_skip_fields = set()
|
| 37 |
+
mutation_tools = set()
|
| 38 |
+
mutation_id_fields = set()
|
| 39 |
+
tool_kinds = json.loads('{"get_connection_profile": "lookup", "get_deployment": "lookup", "get_release": "lookup", "resolve_pricing_endpoint": "lookup"}')
|
| 40 |
+
_descriptors = json.loads('[{"description": "Read a simulated release by application and release tag. Returns its release ID, production deployment ID, exact approved profile reference and binding policy. These references identify the subsequent public reads; an older profile version does not authorize this release.", "name": "get_release", "parameters": {"additionalProperties": false, "properties": {"application": {"minLength": 1, "type": "string"}, "release_tag": {"minLength": 1, "type": "string"}}, "required": ["application", "release_tag"], "type": "object"}}, {"description": "Read a simulated deployment by the deployment ID returned by get_release. Returns deployment_id, application, environment and the current Region, Endpoint, UseFIPS and UseDualStack connection values. Does not change or deploy anything.", "name": "get_deployment", "parameters": {"additionalProperties": false, "properties": {"deployment_id": {"minLength": 1, "type": "string"}}, "required": ["deployment_id"], "type": "object"}}, {"description": "Read exactly the requested simulated connection profile version. Returns profile_id, version, approval_status and connection values only if that version is available. PROFILE_VERSION_UNAVAILABLE includes the requested reference and other available version numbers, never the unavailable settings or a substituted historical version.", "name": "get_connection_profile", "parameters": {"additionalProperties": false, "properties": {"profile_id": {"minLength": 1, "type": "string"}, "version": {"minimum": 1, "type": "integer"}}, "required": ["profile_id", "version"], "type": "object"}}, {"description": "Compute frozen, modeled AWS Price List endpoint behavior; no network availability is checked. Omitted UseFIPS/UseDualStack default to false; null flags are invalid. Omitted/null Region or Endpoint are unset. Any string Endpoint, including an empty string, is a literal override without URL validation: it takes priority over Region, conflicts with UseFIPS first and then UseDualStack. Missing Region without an override is a known configuration_error. Configuration errors are successful modeled results (ok=true); type/unknown-argument errors are tool failures. Regional coverage: us-east-1, cn-north-1 and us-gov-east-1 with all four UseFIPS/UseDualStack combinations; ap-south-1 with both false; us-iso-east-1 and us-isob-east-1 with UseDualStack false and either UseFIPS value. Other regional combinations return outside_scope, not a claim that AWS rejects them.", "name": "resolve_pricing_endpoint", "parameters": {"additionalProperties": false, "properties": {"Endpoint": {"default": null, "type": ["string", "null"]}, "Region": {"default": null, "type": ["string", "null"]}, "UseDualStack": {"default": false, "type": "boolean"}, "UseFIPS": {"default": false, "type": "boolean"}}, "required": [], "type": "object"}}]')
|
| 41 |
+
|
| 42 |
+
def _load_state(self, initial_state: dict) -> dict:
|
| 43 |
+
Draft202012Validator(STATE_SCHEMA).validate(initial_state)
|
| 44 |
+
return copy.deepcopy(initial_state)
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def get_empty_state(cls) -> dict:
|
| 48 |
+
return copy.deepcopy(EMPTY_STATE)
|
| 49 |
+
|
| 50 |
+
@classmethod
|
| 51 |
+
def get_example_state(cls) -> dict:
|
| 52 |
+
return copy.deepcopy(EXAMPLE_STATE)
|
| 53 |
+
|
| 54 |
+
@classmethod
|
| 55 |
+
def get_state_schema(cls) -> dict:
|
| 56 |
+
return copy.deepcopy(STATE_SCHEMA)
|
| 57 |
+
|
| 58 |
+
def _register_tools(self) -> None:
|
| 59 |
+
# Bind the supplied interface to the unchanged domain module. A stale
|
| 60 |
+
# assembler schema must fail before exposing a misleading public ABI.
|
| 61 |
+
actual = []
|
| 62 |
+
for item in domain_runtime.TOOL_SCHEMAS:
|
| 63 |
+
if ("parameters" in item and "input_schema" in item
|
| 64 |
+
and item["parameters"] != item["input_schema"]):
|
| 65 |
+
raise ValueError("Conflicting domain tool input schemas")
|
| 66 |
+
actual.append({
|
| 67 |
+
"name": item["name"],
|
| 68 |
+
"description": item.get("description", ""),
|
| 69 |
+
"parameters": item.get("parameters", item.get("input_schema")),
|
| 70 |
+
})
|
| 71 |
+
if actual != self._descriptors:
|
| 72 |
+
raise ValueError("Domain TOOL_SCHEMAS differ from the assembled interface")
|
| 73 |
+
for descriptor in self._descriptors:
|
| 74 |
+
name = descriptor["name"]
|
| 75 |
+
validator = Draft202012Validator(descriptor["parameters"])
|
| 76 |
+
|
| 77 |
+
# Tool input is validated against the schema in _invoke_domain.
|
| 78 |
+
# A closure factory avoids hidden Python parameters becoming
|
| 79 |
+
# caller-controllable when get_tool_callable is used directly.
|
| 80 |
+
def make_invoke(tool_name, tool_validator):
|
| 81 |
+
def bound(**arguments):
|
| 82 |
+
return self._invoke_domain(tool_name, tool_validator, arguments)
|
| 83 |
+
return bound
|
| 84 |
+
|
| 85 |
+
self.mcp.add_tool(_DomainTool(
|
| 86 |
+
name=name,
|
| 87 |
+
description=descriptor["description"],
|
| 88 |
+
parameters=copy.deepcopy(descriptor["parameters"]),
|
| 89 |
+
fn=make_invoke(name, validator),
|
| 90 |
+
))
|
| 91 |
+
|
| 92 |
+
def _invoke_domain(self, name, validator, arguments):
|
| 93 |
+
before = copy.deepcopy(self.state)
|
| 94 |
+
try:
|
| 95 |
+
validator.validate(arguments)
|
| 96 |
+
envelope = domain_runtime.call_tool(self.state, name, copy.deepcopy(arguments))
|
| 97 |
+
if self.state != before:
|
| 98 |
+
raise ValueError("Read-only domain tool changed state")
|
| 99 |
+
if not isinstance(envelope, dict) or type(envelope.get("ok")) is not bool:
|
| 100 |
+
raise ValueError("Domain result must contain a boolean ok")
|
| 101 |
+
if envelope["ok"] and "result" not in envelope:
|
| 102 |
+
raise ValueError("Successful domain result is missing result")
|
| 103 |
+
if not envelope["ok"] and "error" not in envelope:
|
| 104 |
+
raise ValueError("Failed domain result is missing error")
|
| 105 |
+
# Ensure the public payload is JSON without silently stringifying
|
| 106 |
+
# arbitrary Python objects or accepting non-finite numbers.
|
| 107 |
+
json.dumps(envelope, allow_nan=False)
|
| 108 |
+
except Exception as exc:
|
| 109 |
+
self.state = before
|
| 110 |
+
self._log_tool_call(name, copy.deepcopy(arguments), None, success=False, error=str(exc))
|
| 111 |
+
raise ToolError(str(exc)) from exc
|
| 112 |
+
envelope = copy.deepcopy(envelope)
|
| 113 |
+
error = None if envelope["ok"] else json.dumps(envelope["error"], ensure_ascii=False)
|
| 114 |
+
self._log_tool_call(name, copy.deepcopy(arguments), copy.deepcopy(envelope),
|
| 115 |
+
success=envelope["ok"], error=error)
|
| 116 |
+
return envelope
|
data/environments/aws_release_review_v1/schema.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controller-supplied public state shape; no task answers or judge code."""
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
STATE_SCHEMA = json.loads('{"additionalProperties": false, "properties": {"deployments": {"type": "object"}, "profiles": {"type": "object"}, "releases": {"type": "object"}}, "required": ["releases", "deployments", "profiles"], "type": "object"}')
|
| 5 |
+
EMPTY_STATE = json.loads('{"deployments": {}, "profiles": {}, "releases": {}}')
|
| 6 |
+
EXAMPLE_STATE = json.loads('{"deployments": {}, "profiles": {}, "releases": {}}')
|
data/environments/eval60_ckan/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Manually curated evaluation environment."""
|
data/environments/eval60_ckan/domain/domain_tools.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _obj_schema(properties, required):
|
| 5 |
+
return {"type": "object", "properties": properties, "required": required, "additionalProperties": False}
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
TOOL_SCHEMAS = [
|
| 9 |
+
{
|
| 10 |
+
"name": "organization_autocomplete",
|
| 11 |
+
"description": "Search the synthetic local organization directory for names or titles containing q (case-insensitive). Returns complete local organization records. This simulates the documented organization autocomplete resource concept, not CKAN API compatibility.",
|
| 12 |
+
"input_schema": _obj_schema({"q": {"type": "string", "minLength": 1}, "limit": {"type": "integer", "minimum": 1, "maximum": 50}}, ["q", "limit"]),
|
| 13 |
+
"read_only": True,
|
| 14 |
+
"output_schema": {"type": "array", "items": {"type": "object"}}
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"name": "package_search",
|
| 18 |
+
"description": "Search synthetic local dataset metadata. All supplied filters are applied with AND semantics. Returns complete matching dataset records, including resource metadata but never resource rows or internal availability flags. Empty results are a successful empty list.",
|
| 19 |
+
"input_schema": _obj_schema({"owner_org": {"type": "string", "minLength": 1}, "tag": {"type": "string", "minLength": 1}, "include_private": {"type": "boolean"}}, ["owner_org", "tag", "include_private"]),
|
| 20 |
+
"read_only": True,
|
| 21 |
+
"output_schema": {"type": "object", "required": ["count", "results"], "properties": {"count": {"type": "integer"}, "results": {"type": "array", "items": {"type": "object"}}}, "additionalProperties": False}
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"name": "package_show",
|
| 25 |
+
"description": "Return one complete synthetic dataset metadata record by id or name, with its resource metadata. Resource rows and internal availability flags are excluded.",
|
| 26 |
+
"input_schema": _obj_schema({"id": {"type": "string", "minLength": 1}}, ["id"]),
|
| 27 |
+
"read_only": True,
|
| 28 |
+
"output_schema": {"type": "object"}
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"name": "resource_show",
|
| 32 |
+
"description": "Return metadata for one synthetic resource by its discovered id. This does not read the resource's tabular rows.",
|
| 33 |
+
"input_schema": _obj_schema({"id": {"type": "string", "minLength": 1}}, ["id"]),
|
| 34 |
+
"read_only": True,
|
| 35 |
+
"output_schema": {"type": "object"}
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"name": "resource_rows_list",
|
| 39 |
+
"description": "Read all rows of one synthetic local tabular resource by its discovered id. This is a small offline content reader, not a documented CKAN action or an API-compatible DataStore clone. If that specific content resource is unavailable, returns UNAVAILABLE with its resource identifier.",
|
| 40 |
+
"input_schema": _obj_schema({"id": {"type": "string", "minLength": 1}}, ["id"]),
|
| 41 |
+
"read_only": True,
|
| 42 |
+
"output_schema": {"type": "object", "required": ["resource_id", "rows"], "properties": {"resource_id": {"type": "string"}, "rows": {"type": "array", "items": {"type": "object"}}}, "additionalProperties": False}
|
| 43 |
+
}
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _err(code, message, **extra):
|
| 48 |
+
e = {"code": code, "message": message}
|
| 49 |
+
e.update(extra)
|
| 50 |
+
return {"ok": False, "error": e}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _valid_args(name, a):
|
| 54 |
+
if not isinstance(a, dict):
|
| 55 |
+
return False
|
| 56 |
+
keys = {
|
| 57 |
+
"organization_autocomplete": {"q", "limit"},
|
| 58 |
+
"package_search": {"owner_org", "tag", "include_private"},
|
| 59 |
+
"package_show": {"id"},
|
| 60 |
+
"resource_show": {"id"},
|
| 61 |
+
"resource_rows_list": {"id"}
|
| 62 |
+
}[name]
|
| 63 |
+
if set(a) != keys:
|
| 64 |
+
return False
|
| 65 |
+
if name == "organization_autocomplete":
|
| 66 |
+
return isinstance(a["q"], str) and bool(a["q"]) and isinstance(a["limit"], int) and not isinstance(a["limit"], bool) and 1 <= a["limit"] <= 50
|
| 67 |
+
if name == "package_search":
|
| 68 |
+
return all(isinstance(a[x], str) and bool(a[x]) for x in ("owner_org", "tag")) and isinstance(a["include_private"], bool)
|
| 69 |
+
return isinstance(a["id"], str) and bool(a["id"])
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _resource_public(r):
|
| 73 |
+
return {k: deepcopy(v) for k, v in r.items() if k not in ("rows", "content_available")}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _dataset_public(state, d):
|
| 77 |
+
out = deepcopy(d)
|
| 78 |
+
out["resources"] = [_resource_public(r) for r in state.get("resources", []) if r.get("package_id") == d.get("id")]
|
| 79 |
+
return out
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def call_tool(state, name, arguments):
|
| 83 |
+
known = {x["name"] for x in TOOL_SCHEMAS}
|
| 84 |
+
if name not in known:
|
| 85 |
+
return _err("UNKNOWN_TOOL", "Unknown tool name", tool=name)
|
| 86 |
+
if not _valid_args(name, arguments):
|
| 87 |
+
return _err("INVALID_ARGUMENT", "Arguments do not match the tool schema")
|
| 88 |
+
if name == "organization_autocomplete":
|
| 89 |
+
q = arguments["q"].casefold()
|
| 90 |
+
found = [deepcopy(o) for o in state.get("organizations", []) if q in o.get("name", "").casefold() or q in o.get("title", "").casefold()]
|
| 91 |
+
found.sort(key=lambda o: (o.get("title", "").casefold(), o.get("id", "")))
|
| 92 |
+
return {"ok": True, "result": found[:arguments["limit"]]}
|
| 93 |
+
if name == "package_search":
|
| 94 |
+
org = arguments["owner_org"]
|
| 95 |
+
if not any(o.get("id") == org or o.get("name") == org for o in state.get("organizations", [])):
|
| 96 |
+
return _err("NOT_FOUND", "Organization was not found", resource="organization:" + org)
|
| 97 |
+
org_ids = {o["id"] for o in state["organizations"] if o.get("id") == org or o.get("name") == org}
|
| 98 |
+
tag = arguments["tag"].casefold()
|
| 99 |
+
ds = []
|
| 100 |
+
for d in state.get("datasets", []):
|
| 101 |
+
if d.get("owner_org") not in org_ids or tag not in [str(x).casefold() for x in d.get("tags", [])]:
|
| 102 |
+
continue
|
| 103 |
+
if d.get("private", False) and not arguments["include_private"]:
|
| 104 |
+
continue
|
| 105 |
+
ds.append(_dataset_public(state, d))
|
| 106 |
+
ds.sort(key=lambda d: (d.get("series_key", ""), d.get("name", ""), d.get("id", "")))
|
| 107 |
+
return {"ok": True, "result": {"count": len(ds), "results": ds}}
|
| 108 |
+
if name == "package_show":
|
| 109 |
+
ident = arguments["id"]
|
| 110 |
+
for d in state.get("datasets", []):
|
| 111 |
+
if d.get("id") == ident or d.get("name") == ident:
|
| 112 |
+
return {"ok": True, "result": _dataset_public(state, d)}
|
| 113 |
+
return _err("NOT_FOUND", "Dataset was not found", resource="dataset:" + ident)
|
| 114 |
+
ident = arguments["id"]
|
| 115 |
+
found = None
|
| 116 |
+
for r in state.get("resources", []):
|
| 117 |
+
if r.get("id") == ident:
|
| 118 |
+
found = r
|
| 119 |
+
break
|
| 120 |
+
if found is None:
|
| 121 |
+
return _err("NOT_FOUND", "Resource was not found", resource="resource:" + ident)
|
| 122 |
+
if name == "resource_show":
|
| 123 |
+
return {"ok": True, "result": _resource_public(found)}
|
| 124 |
+
if not found.get("content_available", False):
|
| 125 |
+
return _err("UNAVAILABLE", "The requested resource content is unavailable", resource="resource:" + ident)
|
| 126 |
+
return {"ok": True, "result": {"resource_id": ident, "rows": deepcopy(found.get("rows", []))}}
|
data/environments/eval60_ckan/environment.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Official tool adapter to the exact sealed transaction runtime."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import copy
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import threading
|
| 10 |
+
from typing import Any, Callable
|
| 11 |
+
|
| 12 |
+
from fastmcp.tools import Tool
|
| 13 |
+
from fastmcp.tools.tool import ToolResult
|
| 14 |
+
from pydantic import Field
|
| 15 |
+
from hera_environment import BaseEnvironment, ToolError
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parent
|
| 18 |
+
_spec = importlib.util.spec_from_file_location(__name__ + '_runtime', ROOT/'runtime.py')
|
| 19 |
+
support = importlib.util.module_from_spec(_spec)
|
| 20 |
+
_spec.loader.exec_module(support)
|
| 21 |
+
STATE_SCHEMA = json.loads('{"type": "object"}')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _DomainTool(Tool):
|
| 25 |
+
fn: Callable[..., Any] = Field(exclude=True)
|
| 26 |
+
|
| 27 |
+
async def run(self, arguments: dict[str, Any]) -> ToolResult:
|
| 28 |
+
envelope = self.fn(**arguments)
|
| 29 |
+
return ToolResult(content=json.dumps(envelope,ensure_ascii=False,allow_nan=False),
|
| 30 |
+
structured_content=envelope,is_error=envelope['ok'] is False)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Environment(BaseEnvironment):
|
| 34 |
+
env_name = 'eval60_ckan'
|
| 35 |
+
short_name = 'CKAN'
|
| 36 |
+
always_skip_fields = set()
|
| 37 |
+
mutation_tools = set()
|
| 38 |
+
mutation_id_fields = set()
|
| 39 |
+
tool_kinds = json.loads('{"organization_autocomplete": "lookup", "package_search": "lookup", "package_show": "lookup", "resource_rows_list": "lookup", "resource_show": "lookup"}')
|
| 40 |
+
_descriptors = json.loads('[{"description": "Search the synthetic local organization directory for names or titles containing q (case-insensitive). Returns complete local organization records. This simulates the documented organization autocomplete resource concept, not CKAN API compatibility.", "input_schema": {"additionalProperties": false, "properties": {"limit": {"maximum": 50, "minimum": 1, "type": "integer"}, "q": {"minLength": 1, "type": "string"}}, "required": ["q", "limit"], "type": "object"}, "name": "organization_autocomplete", "output_schema": {"items": {"type": "object"}, "type": "array"}, "read_only": true}, {"description": "Search synthetic local dataset metadata. All supplied filters are applied with AND semantics. Returns complete matching dataset records, including resource metadata but never resource rows or internal availability flags. Empty results are a successful empty list.", "input_schema": {"additionalProperties": false, "properties": {"include_private": {"type": "boolean"}, "owner_org": {"minLength": 1, "type": "string"}, "tag": {"minLength": 1, "type": "string"}}, "required": ["owner_org", "tag", "include_private"], "type": "object"}, "name": "package_search", "output_schema": {"additionalProperties": false, "properties": {"count": {"type": "integer"}, "results": {"items": {"type": "object"}, "type": "array"}}, "required": ["count", "results"], "type": "object"}, "read_only": true}, {"description": "Return one complete synthetic dataset metadata record by id or name, with its resource metadata. Resource rows and internal availability flags are excluded.", "input_schema": {"additionalProperties": false, "properties": {"id": {"minLength": 1, "type": "string"}}, "required": ["id"], "type": "object"}, "name": "package_show", "output_schema": {"type": "object"}, "read_only": true}, {"description": "Return metadata for one synthetic resource by its discovered id. This does not read the resource\'s tabular rows.", "input_schema": {"additionalProperties": false, "properties": {"id": {"minLength": 1, "type": "string"}}, "required": ["id"], "type": "object"}, "name": "resource_show", "output_schema": {"type": "object"}, "read_only": true}, {"description": "Read all rows of one synthetic local tabular resource by its discovered id. This is a small offline content reader, not a documented CKAN action or an API-compatible DataStore clone. If that specific content resource is unavailable, returns UNAVAILABLE with its resource identifier.", "input_schema": {"additionalProperties": false, "properties": {"id": {"minLength": 1, "type": "string"}}, "required": ["id"], "type": "object"}, "name": "resource_rows_list", "output_schema": {"additionalProperties": false, "properties": {"resource_id": {"type": "string"}, "rows": {"items": {"type": "object"}, "type": "array"}}, "required": ["resource_id", "rows"], "type": "object"}, "read_only": true}]')
|
| 41 |
+
|
| 42 |
+
def _load_state(self, initial_state):
|
| 43 |
+
support.validator(STATE_SCHEMA).validate(initial_state)
|
| 44 |
+
return copy.deepcopy(initial_state)
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def get_empty_state(cls):return {}
|
| 48 |
+
|
| 49 |
+
@classmethod
|
| 50 |
+
def get_example_state(cls):return {}
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def get_state_schema(cls):return copy.deepcopy(STATE_SCHEMA)
|
| 54 |
+
|
| 55 |
+
def _register_tools(self):
|
| 56 |
+
self._transaction_lock = threading.Lock()
|
| 57 |
+
self._transport_attempts = []
|
| 58 |
+
_, actual = support.load_domain(ROOT/'domain')
|
| 59 |
+
if support.canonical(actual) != support.canonical(self._descriptors):
|
| 60 |
+
raise ValueError('Public tool descriptors differ from the sealed domain')
|
| 61 |
+
for item in self._descriptors:
|
| 62 |
+
def bind(name):
|
| 63 |
+
def call(**arguments):return self._invoke_domain(name,arguments)
|
| 64 |
+
return call
|
| 65 |
+
output = None
|
| 66 |
+
if 'output_schema' in item:
|
| 67 |
+
output={'type':'object','oneOf':[
|
| 68 |
+
{'type':'object','required':['ok','result'],'additionalProperties':False,
|
| 69 |
+
'properties':{'ok':{'const':True},'result':copy.deepcopy(item['output_schema'])}},
|
| 70 |
+
{'type':'object','required':['ok','error'],'additionalProperties':False,
|
| 71 |
+
'properties':{'ok':{'const':False},'error':{'type':'object','required':['code','message'],
|
| 72 |
+
'properties':{'code':{'type':'string','minLength':1},'message':{'type':'string'}}}}}]}
|
| 73 |
+
self.mcp.add_tool(_DomainTool(name=item['name'],description=item['description'],
|
| 74 |
+
parameters=copy.deepcopy(item['input_schema']),output_schema=output,fn=bind(item['name'])))
|
| 75 |
+
|
| 76 |
+
def _invoke_domain(self, name, arguments):
|
| 77 |
+
with self._transaction_lock:
|
| 78 |
+
before = copy.deepcopy(self.state)
|
| 79 |
+
if len(support.canonical({'tool':name,'arguments':arguments})) > 32768:
|
| 80 |
+
raise ToolError('PUBLIC_REQUEST_LIMIT')
|
| 81 |
+
request = {'action':'transition','state':before,'tool':name,'arguments':arguments}
|
| 82 |
+
try:
|
| 83 |
+
process = subprocess.run([sys.executable,'-I','-B',str(ROOT/'runtime.py'),
|
| 84 |
+
'--environment',str(ROOT/'domain'),'--max-observation-bytes','32768'],
|
| 85 |
+
input=support.canonical(request),capture_output=True,timeout=120,
|
| 86 |
+
cwd=str(ROOT),env={'PATH':'/usr/bin:/bin','PYTHONDONTWRITEBYTECODE':'1'})
|
| 87 |
+
result = support.strict(process.stdout)
|
| 88 |
+
if process.returncode or set(result) != {'state','observation','dispatched'}:
|
| 89 |
+
raise ValueError('Transaction worker failed')
|
| 90 |
+
observation = result['observation']
|
| 91 |
+
support.canonical(observation)
|
| 92 |
+
self.state = copy.deepcopy(result['state'])
|
| 93 |
+
except Exception as exc:
|
| 94 |
+
self.state = before
|
| 95 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 96 |
+
'observation':None,'dispatched':None,'error':'TRANSACTION_INFRASTRUCTURE_ERROR'})
|
| 97 |
+
raise ToolError('TRANSACTION_INFRASTRUCTURE_ERROR') from exc
|
| 98 |
+
error = None if observation['ok'] else json.dumps(observation['error'],ensure_ascii=False)
|
| 99 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 100 |
+
'observation':copy.deepcopy(observation),'dispatched':result['dispatched']})
|
| 101 |
+
# Keep the semantic event stream identical to controller.public.
|
| 102 |
+
# Rejected pre-dispatch requests remain attempts but cannot count
|
| 103 |
+
# as observed domain evidence. MCP may itself reject extra keys
|
| 104 |
+
# before this adapter; that is a transport error, not a domain event.
|
| 105 |
+
if result['dispatched']:
|
| 106 |
+
self._log_tool_call(name,copy.deepcopy(arguments),copy.deepcopy(observation),
|
| 107 |
+
success=observation['ok'],error=error)
|
| 108 |
+
return observation
|
data/environments/eval60_ckan/runtime.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small offline transaction boundary for reviewed, candidate-specific tools.
|
| 2 |
+
|
| 3 |
+
This is not a sandbox for hostile Python. The trusted controller runs this
|
| 4 |
+
worker in a fresh interpreter for every call and keeps its state output private.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
from contextlib import redirect_stderr, redirect_stdout
|
| 10 |
+
from copy import deepcopy
|
| 11 |
+
import importlib.util
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import re
|
| 16 |
+
import sys
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
from jsonschema import Draft202012Validator, FormatChecker, validators
|
| 20 |
+
|
| 21 |
+
sys.dont_write_bytecode = True
|
| 22 |
+
MAX_REQUEST_BYTES = 32768
|
| 23 |
+
MAX_INTERNAL_BYTES = 16 * 1024 * 1024
|
| 24 |
+
DEFAULT_OBSERVATION_BYTES = 32768
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def require(condition, message):
|
| 28 |
+
if not condition:
|
| 29 |
+
raise ValueError(message)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def canonical(value):
|
| 33 |
+
# Reject Python-only coercions such as integer object keys or tuples.
|
| 34 |
+
def check(item):
|
| 35 |
+
if item is None or type(item) in (str, bool, int):
|
| 36 |
+
return
|
| 37 |
+
if type(item) is float:
|
| 38 |
+
require(math.isfinite(item), 'Nonfinite JSON number')
|
| 39 |
+
return
|
| 40 |
+
if type(item) is list:
|
| 41 |
+
for child in item:
|
| 42 |
+
check(child)
|
| 43 |
+
return
|
| 44 |
+
if type(item) is dict:
|
| 45 |
+
require(all(type(key) is str for key in item), 'JSON keys must be strings')
|
| 46 |
+
for child in item.values():
|
| 47 |
+
check(child)
|
| 48 |
+
return
|
| 49 |
+
raise ValueError('Value is not JSON')
|
| 50 |
+
check(value)
|
| 51 |
+
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
| 52 |
+
sort_keys=True, separators=(',', ':')).encode('utf-8')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def strict(raw):
|
| 56 |
+
if type(raw) is bytes:
|
| 57 |
+
raw = raw.decode('utf-8', errors='strict')
|
| 58 |
+
require(type(raw) is str, 'Expected JSON bytes or text')
|
| 59 |
+
def pairs(items):
|
| 60 |
+
result = {}
|
| 61 |
+
for key, value in items:
|
| 62 |
+
require(key not in result, 'Duplicate JSON key')
|
| 63 |
+
result[key] = value
|
| 64 |
+
return result
|
| 65 |
+
value = json.loads(raw, object_pairs_hook=pairs,
|
| 66 |
+
parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Nonfinite JSON')))
|
| 67 |
+
canonical(value)
|
| 68 |
+
return value
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read(path):
|
| 72 |
+
path = Path(path)
|
| 73 |
+
require(path.is_file() and not path.is_symlink(), 'Expected a regular file')
|
| 74 |
+
return strict(path.read_bytes())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
_TYPE_CHECKER = Draft202012Validator.TYPE_CHECKER.redefine_many({
|
| 78 |
+
'integer': lambda checker, value: type(value) is int,
|
| 79 |
+
'number': lambda checker, value: type(value) is int or (type(value) is float and math.isfinite(value)),
|
| 80 |
+
})
|
| 81 |
+
StrictValidator = validators.extend(Draft202012Validator, type_checker=_TYPE_CHECKER)
|
| 82 |
+
|
| 83 |
+
# Load the pinned optional format checker by bundle-relative path. It requires
|
| 84 |
+
# no network, installed extras, sys.path changes, or historical checkout.
|
| 85 |
+
_date_path = Path(__file__).resolve().parent / 'vendor/rfc3339_validator.py'
|
| 86 |
+
_date_spec = importlib.util.spec_from_file_location('_curated_rfc3339', _date_path)
|
| 87 |
+
_date_module = importlib.util.module_from_spec(_date_spec)
|
| 88 |
+
_date_spec.loader.exec_module(_date_module)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def validator(schema):
|
| 92 |
+
require(type(schema) in (dict, bool), 'Schema must be a JSON Schema')
|
| 93 |
+
canonical(schema)
|
| 94 |
+
formats = FormatChecker()
|
| 95 |
+
@formats.checks('date-time')
|
| 96 |
+
def date_time(value):
|
| 97 |
+
return not isinstance(value, str) or _date_module.validate_rfc3339(value.upper())
|
| 98 |
+
visited = set()
|
| 99 |
+
def inspect(value):
|
| 100 |
+
if type(value) is dict:
|
| 101 |
+
if id(value) in visited:
|
| 102 |
+
return
|
| 103 |
+
visited.add(id(value))
|
| 104 |
+
require(value != {'truncated': True}, 'Truncated schemas are unsupported')
|
| 105 |
+
require('$id' not in value and '$dynamicRef' not in value,
|
| 106 |
+
'Schema resource rebasing and dynamic references are unsupported')
|
| 107 |
+
if 'format' in value:
|
| 108 |
+
require(type(value['format']) is str and value['format'] in formats.checkers,
|
| 109 |
+
'Unsupported schema format')
|
| 110 |
+
if '$ref' in value:
|
| 111 |
+
ref = value['$ref']
|
| 112 |
+
require(type(ref) is str and (ref == '#' or ref.startswith('#/')),
|
| 113 |
+
'Only local JSON Pointer schema references are allowed')
|
| 114 |
+
current = schema
|
| 115 |
+
if ref != '#':
|
| 116 |
+
for part in ref[2:].split('/'):
|
| 117 |
+
part = part.replace('~1', '/').replace('~0', '~')
|
| 118 |
+
if type(current) is list:
|
| 119 |
+
require(part.isdigit(), 'Invalid local schema reference')
|
| 120 |
+
current = current[int(part)]
|
| 121 |
+
else:
|
| 122 |
+
require(type(current) is dict and part in current,
|
| 123 |
+
'Missing local schema reference')
|
| 124 |
+
current = current[part]
|
| 125 |
+
require(type(current) in (dict, bool), 'Schema reference is not a schema')
|
| 126 |
+
# A local reference may target a schema stored outside the
|
| 127 |
+
# standard schema keywords; inspect that target as well.
|
| 128 |
+
inspect(current)
|
| 129 |
+
# Walk schema locations, not property names or literal const/enum
|
| 130 |
+
# data (a business field named "format" is not a schema keyword).
|
| 131 |
+
for keyword in ('properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'):
|
| 132 |
+
if keyword in value:
|
| 133 |
+
require(type(value[keyword]) is dict, 'Invalid schema map')
|
| 134 |
+
for child in value[keyword].values():
|
| 135 |
+
inspect(child)
|
| 136 |
+
for keyword in ('allOf', 'anyOf', 'oneOf', 'prefixItems'):
|
| 137 |
+
if keyword in value:
|
| 138 |
+
require(type(value[keyword]) is list, 'Invalid schema sequence')
|
| 139 |
+
for child in value[keyword]:
|
| 140 |
+
inspect(child)
|
| 141 |
+
for keyword in ('items', 'contains', 'additionalProperties', 'propertyNames',
|
| 142 |
+
'unevaluatedProperties', 'unevaluatedItems', 'not', 'if', 'then', 'else'):
|
| 143 |
+
if keyword in value:
|
| 144 |
+
inspect(value[keyword])
|
| 145 |
+
inspect(schema)
|
| 146 |
+
Draft202012Validator.check_schema(schema)
|
| 147 |
+
return StrictValidator(schema, format_checker=formats)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class _BoundedSink:
|
| 151 |
+
def __init__(self):
|
| 152 |
+
self.size = 0
|
| 153 |
+
|
| 154 |
+
def write(self, value):
|
| 155 |
+
self.size += len(value.encode('utf-8'))
|
| 156 |
+
require(self.size <= 16384, 'Domain diagnostic output exceeded limit')
|
| 157 |
+
return len(value)
|
| 158 |
+
|
| 159 |
+
def flush(self):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def load_domain(environment):
|
| 164 |
+
environment = Path(environment)
|
| 165 |
+
require(environment.is_dir() and not environment.is_symlink(), 'Invalid environment directory')
|
| 166 |
+
path = environment / 'domain_tools.py'
|
| 167 |
+
require(path.is_file() and not path.is_symlink(), 'Invalid domain module')
|
| 168 |
+
spec = importlib.util.spec_from_file_location('_curated_domain_tools', path)
|
| 169 |
+
domain = importlib.util.module_from_spec(spec)
|
| 170 |
+
# No sys.path injection and no reuse of an earlier module's global state.
|
| 171 |
+
sys.modules[spec.name] = domain
|
| 172 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 173 |
+
spec.loader.exec_module(domain)
|
| 174 |
+
require(callable(getattr(domain, 'call_tool', None)), 'Domain call_tool is missing')
|
| 175 |
+
descriptors = deepcopy(getattr(domain, 'TOOL_SCHEMAS', None))
|
| 176 |
+
require(type(descriptors) is list and bool(descriptors), 'Tool schemas must be a nonempty list')
|
| 177 |
+
names = set()
|
| 178 |
+
for item in descriptors:
|
| 179 |
+
require(type(item) is dict and set(item) <= {
|
| 180 |
+
'name', 'description', 'input_schema', 'output_schema', 'read_only'
|
| 181 |
+
} and {'name', 'description', 'input_schema', 'read_only'} <= set(item),
|
| 182 |
+
'Invalid tool descriptor fields')
|
| 183 |
+
name = item['name']
|
| 184 |
+
require(type(name) is str and re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,127}', name)
|
| 185 |
+
and name not in names, 'Invalid or duplicate tool name')
|
| 186 |
+
names.add(name)
|
| 187 |
+
require(type(item['description']) is str and bool(item['description'].strip()),
|
| 188 |
+
'Tool description is required')
|
| 189 |
+
require(type(item['read_only']) is bool, 'read_only must be boolean')
|
| 190 |
+
schema = item['input_schema']
|
| 191 |
+
require(type(schema) is dict and schema.get('type') == 'object'
|
| 192 |
+
and schema.get('additionalProperties') is False,
|
| 193 |
+
'Tool input must explicitly prohibit extra arguments')
|
| 194 |
+
validator(schema)
|
| 195 |
+
if 'output_schema' in item:
|
| 196 |
+
validator(item['output_schema'])
|
| 197 |
+
return domain, descriptors
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def state_validator(environment):
|
| 201 |
+
path = Path(environment) / 'state_schema.json'
|
| 202 |
+
return validator(read(path)) if path.exists() else validator({'type': 'object'})
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def error(code, message):
|
| 206 |
+
return {'ok': False, 'error': {'code': code, 'message': message}}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def transition(environment, state, name, arguments, *, max_observation_bytes=DEFAULT_OBSERVATION_BYTES):
|
| 210 |
+
"""Return private {state, observation, dispatched}; never mutate inputs."""
|
| 211 |
+
canonical(state)
|
| 212 |
+
canonical(arguments)
|
| 213 |
+
require(type(state) is dict, 'State must be an object')
|
| 214 |
+
state_check = state_validator(environment)
|
| 215 |
+
state_check.validate(state)
|
| 216 |
+
domain, descriptors = load_domain(environment)
|
| 217 |
+
by_name = {item['name']: item for item in descriptors}
|
| 218 |
+
before, working = deepcopy(state), deepcopy(state)
|
| 219 |
+
def result(observation, dispatched, next_state=None):
|
| 220 |
+
return {'state': deepcopy(before if next_state is None else next_state),
|
| 221 |
+
'observation': deepcopy(observation), 'dispatched': dispatched}
|
| 222 |
+
if type(name) is not str or name not in by_name:
|
| 223 |
+
return result(error('UNKNOWN_TOOL', 'The requested tool is not public.'), False)
|
| 224 |
+
descriptor = by_name[name]
|
| 225 |
+
try:
|
| 226 |
+
require(type(arguments) is dict, 'Arguments must be an object')
|
| 227 |
+
validator(descriptor['input_schema']).validate(arguments)
|
| 228 |
+
except Exception:
|
| 229 |
+
return result(error('INVALID_ARGUMENTS', 'Arguments do not satisfy the public schema.'), False)
|
| 230 |
+
try:
|
| 231 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 232 |
+
observation = domain.call_tool(working, name, deepcopy(arguments))
|
| 233 |
+
except Exception:
|
| 234 |
+
return result(error('DOMAIN_EXECUTION_ERROR', 'The tool could not complete.'), True)
|
| 235 |
+
try:
|
| 236 |
+
require(type(observation) is dict and type(observation.get('ok')) is bool,
|
| 237 |
+
'Invalid domain envelope')
|
| 238 |
+
if observation['ok']:
|
| 239 |
+
require(set(observation) == {'ok', 'result'}, 'Invalid success envelope')
|
| 240 |
+
else:
|
| 241 |
+
require(set(observation) == {'ok', 'error'} and type(observation['error']) is dict,
|
| 242 |
+
'Invalid error envelope')
|
| 243 |
+
require(type(observation['error'].get('code')) is str and bool(observation['error']['code'])
|
| 244 |
+
and type(observation['error'].get('message')) is str, 'Invalid domain error')
|
| 245 |
+
encoded = canonical(observation)
|
| 246 |
+
require(type(max_observation_bytes) is int and 512 <= max_observation_bytes <= 1048576,
|
| 247 |
+
'Invalid observation limit')
|
| 248 |
+
if len(encoded) > max_observation_bytes:
|
| 249 |
+
return result(error('OBSERVATION_LIMIT', 'Tool result exceeds the public response limit.'), True)
|
| 250 |
+
if descriptor['read_only'] and canonical(working) != canonical(before):
|
| 251 |
+
return result(error('READ_ONLY_VIOLATION', 'A read-only tool attempted to change state.'), True)
|
| 252 |
+
if not observation['ok']:
|
| 253 |
+
return result(observation, True)
|
| 254 |
+
if 'output_schema' in descriptor:
|
| 255 |
+
validator(descriptor['output_schema']).validate(observation['result'])
|
| 256 |
+
state_check.validate(working)
|
| 257 |
+
canonical(working)
|
| 258 |
+
except Exception:
|
| 259 |
+
return result(error('INVALID_TOOL_RESULT', 'Tool output or state violates its contract.'), True)
|
| 260 |
+
return result(observation, True, working)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def main(argv=None):
|
| 264 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 265 |
+
parser.add_argument('--environment', type=Path, required=True)
|
| 266 |
+
parser.add_argument('--max-observation-bytes', type=int, default=DEFAULT_OBSERVATION_BYTES)
|
| 267 |
+
args = parser.parse_args(argv)
|
| 268 |
+
try:
|
| 269 |
+
raw = sys.stdin.buffer.read(MAX_INTERNAL_BYTES + 1)
|
| 270 |
+
require(len(raw) <= MAX_INTERNAL_BYTES, 'Internal request exceeds limit')
|
| 271 |
+
request = strict(raw)
|
| 272 |
+
with (patch('socket.socket', side_effect=RuntimeError('Offline worker forbids network')),
|
| 273 |
+
patch('socket.create_connection', side_effect=RuntimeError('Offline worker forbids network'))):
|
| 274 |
+
if request == {'action': 'describe'}:
|
| 275 |
+
_, descriptors = load_domain(args.environment)
|
| 276 |
+
state_validator(args.environment).validate(read(args.environment / 'state.json'))
|
| 277 |
+
value = {'tools': descriptors}
|
| 278 |
+
else:
|
| 279 |
+
require(type(request) is dict and set(request) == {'action', 'state', 'tool', 'arguments'}
|
| 280 |
+
and request['action'] == 'transition', 'Invalid internal request')
|
| 281 |
+
value = transition(args.environment, request['state'], request['tool'], request['arguments'],
|
| 282 |
+
max_observation_bytes=args.max_observation_bytes)
|
| 283 |
+
sys.stdout.buffer.write(canonical(value) + b'\n')
|
| 284 |
+
return 0
|
| 285 |
+
except Exception:
|
| 286 |
+
sys.stdout.buffer.write(canonical({'worker_error': 'RUNTIME_VALIDATION_FAILED'}) + b'\n')
|
| 287 |
+
return 1
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == '__main__':
|
| 291 |
+
raise SystemExit(main())
|
data/environments/eval60_ckan/vendor/rfc3339_validator.LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2019, Nicolas Aimetti
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
data/environments/eval60_ckan/vendor/rfc3339_validator.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Vendored 0.1.4; Python 3-only compatibility patch, see provenance.json.
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
__author__ = """Nicolas Aimetti"""
|
| 5 |
+
__email__ = 'naimetti@yahoo.com.ar'
|
| 6 |
+
__version__ = '0.1.4'
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
import calendar
|
| 10 |
+
|
| 11 |
+
RFC3339_REGEX_FLAGS = re.ASCII
|
| 12 |
+
|
| 13 |
+
RFC3339_REGEX = re.compile(r"""
|
| 14 |
+
^
|
| 15 |
+
(\d{4}) # Year
|
| 16 |
+
-
|
| 17 |
+
(0[1-9]|1[0-2]) # Month
|
| 18 |
+
-
|
| 19 |
+
(\d{2}) # Day
|
| 20 |
+
T
|
| 21 |
+
(?:[01]\d|2[0123]) # Hours
|
| 22 |
+
:
|
| 23 |
+
(?:[0-5]\d) # Minutes
|
| 24 |
+
:
|
| 25 |
+
(?:[0-5]\d) # Seconds
|
| 26 |
+
(?:\.\d+)? # Secfrac
|
| 27 |
+
(?: Z # UTC
|
| 28 |
+
| [+-](?:[01]\d|2[0123]):[0-5]\d # Offset
|
| 29 |
+
)
|
| 30 |
+
$
|
| 31 |
+
""", re.VERBOSE | RFC3339_REGEX_FLAGS)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def validate_rfc3339(date_string):
|
| 35 |
+
"""
|
| 36 |
+
Validates dates against RFC3339 datetime format
|
| 37 |
+
Leap seconds are no supported.
|
| 38 |
+
"""
|
| 39 |
+
m = RFC3339_REGEX.match(date_string)
|
| 40 |
+
if m is None:
|
| 41 |
+
return False
|
| 42 |
+
year, month, day = map(int, m.groups())
|
| 43 |
+
if not year:
|
| 44 |
+
# Year 0 is not valid a valid date
|
| 45 |
+
return False
|
| 46 |
+
(_, max_day) = calendar.monthrange(year, month)
|
| 47 |
+
if not 1 <= day <= max_day:
|
| 48 |
+
return False
|
| 49 |
+
return True
|
data/environments/eval60_datacite/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Manually curated evaluation environment."""
|
data/environments/eval60_datacite/domain/domain_tools.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
|
| 3 |
+
TOOL_SCHEMAS = [
|
| 4 |
+
{
|
| 5 |
+
"name": "list_curation_batches",
|
| 6 |
+
"description": "List complete synthetic local curation batches, optionally filtered by batch_id. This local operation is not a DataCite API endpoint.",
|
| 7 |
+
"input_schema": {
|
| 8 |
+
"type": "object",
|
| 9 |
+
"properties": {"batch_id": {"type": "string", "minLength": 1}},
|
| 10 |
+
"additionalProperties": False
|
| 11 |
+
},
|
| 12 |
+
"read_only": True,
|
| 13 |
+
"output_schema": {"type": "object", "properties": {"batches": {"type": "array"}, "count": {"type": "integer"}}, "required": ["batches", "count"], "additionalProperties": False}
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"name": "get_doi_metadata",
|
| 17 |
+
"description": "Retrieve one complete synthetic DOI metadata record by DOI. The modeled fields are a small local simulation of DataCite resource concepts, not an API-compatible response.",
|
| 18 |
+
"input_schema": {
|
| 19 |
+
"type": "object",
|
| 20 |
+
"properties": {"doi": {"type": "string", "minLength": 1}},
|
| 21 |
+
"required": ["doi"],
|
| 22 |
+
"additionalProperties": False
|
| 23 |
+
},
|
| 24 |
+
"read_only": True,
|
| 25 |
+
"output_schema": {"type": "object", "properties": {"record": {"type": "object"}}, "required": ["record"], "additionalProperties": False}
|
| 26 |
+
}
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
def _err(code, message, **extra):
|
| 30 |
+
e = {"code": code, "message": message}
|
| 31 |
+
e.update(extra)
|
| 32 |
+
return {"ok": False, "error": e}
|
| 33 |
+
|
| 34 |
+
def call_tool(state, name, arguments):
|
| 35 |
+
if not isinstance(arguments, dict):
|
| 36 |
+
return _err("INVALID_ARGUMENT", "arguments must be an object")
|
| 37 |
+
if name == "list_curation_batches":
|
| 38 |
+
if set(arguments) - {"batch_id"} or ("batch_id" in arguments and (not isinstance(arguments["batch_id"], str) or not arguments["batch_id"])):
|
| 39 |
+
return _err("INVALID_ARGUMENT", "batch_id must be a nonempty string when supplied")
|
| 40 |
+
rows = state.get("curation_batches", [])
|
| 41 |
+
if "batch_id" in arguments:
|
| 42 |
+
rows = [x for x in rows if x.get("batch_id") == arguments["batch_id"]]
|
| 43 |
+
return {"ok": True, "result": {"batches": deepcopy(rows), "count": len(rows)}}
|
| 44 |
+
if name == "get_doi_metadata":
|
| 45 |
+
if set(arguments) != {"doi"} or not isinstance(arguments.get("doi"), str) or not arguments["doi"]:
|
| 46 |
+
return _err("INVALID_ARGUMENT", "doi is required and must be a nonempty string")
|
| 47 |
+
doi = arguments["doi"].lower()
|
| 48 |
+
records = state.get("doi_records", {})
|
| 49 |
+
if doi not in records:
|
| 50 |
+
return _err("NOT_FOUND", "No DOI metadata record exists for the supplied identifier", resource="doi:" + doi)
|
| 51 |
+
availability = state.get("availability", {})
|
| 52 |
+
key = "doi:" + doi
|
| 53 |
+
if availability.get(key, True) is not True:
|
| 54 |
+
return _err("UNAVAILABLE", "The requested DOI metadata resource is unavailable", resource=key)
|
| 55 |
+
return {"ok": True, "result": {"record": deepcopy(records[doi])}}
|
| 56 |
+
return _err("UNKNOWN_TOOL", "Unknown tool name")
|
data/environments/eval60_datacite/environment.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Official tool adapter to the exact sealed transaction runtime."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import copy
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import threading
|
| 10 |
+
from typing import Any, Callable
|
| 11 |
+
|
| 12 |
+
from fastmcp.tools import Tool
|
| 13 |
+
from fastmcp.tools.tool import ToolResult
|
| 14 |
+
from pydantic import Field
|
| 15 |
+
from hera_environment import BaseEnvironment, ToolError
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parent
|
| 18 |
+
_spec = importlib.util.spec_from_file_location(__name__ + '_runtime', ROOT/'runtime.py')
|
| 19 |
+
support = importlib.util.module_from_spec(_spec)
|
| 20 |
+
_spec.loader.exec_module(support)
|
| 21 |
+
STATE_SCHEMA = json.loads('{"type": "object"}')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _DomainTool(Tool):
|
| 25 |
+
fn: Callable[..., Any] = Field(exclude=True)
|
| 26 |
+
|
| 27 |
+
async def run(self, arguments: dict[str, Any]) -> ToolResult:
|
| 28 |
+
envelope = self.fn(**arguments)
|
| 29 |
+
return ToolResult(content=json.dumps(envelope,ensure_ascii=False,allow_nan=False),
|
| 30 |
+
structured_content=envelope,is_error=envelope['ok'] is False)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Environment(BaseEnvironment):
|
| 34 |
+
env_name = 'eval60_datacite'
|
| 35 |
+
short_name = 'DataCite'
|
| 36 |
+
always_skip_fields = set()
|
| 37 |
+
mutation_tools = set()
|
| 38 |
+
mutation_id_fields = set()
|
| 39 |
+
tool_kinds = json.loads('{"get_doi_metadata": "lookup", "list_curation_batches": "lookup"}')
|
| 40 |
+
_descriptors = json.loads('[{"description": "List complete synthetic local curation batches, optionally filtered by batch_id. This local operation is not a DataCite API endpoint.", "input_schema": {"additionalProperties": false, "properties": {"batch_id": {"minLength": 1, "type": "string"}}, "type": "object"}, "name": "list_curation_batches", "output_schema": {"additionalProperties": false, "properties": {"batches": {"type": "array"}, "count": {"type": "integer"}}, "required": ["batches", "count"], "type": "object"}, "read_only": true}, {"description": "Retrieve one complete synthetic DOI metadata record by DOI. The modeled fields are a small local simulation of DataCite resource concepts, not an API-compatible response.", "input_schema": {"additionalProperties": false, "properties": {"doi": {"minLength": 1, "type": "string"}}, "required": ["doi"], "type": "object"}, "name": "get_doi_metadata", "output_schema": {"additionalProperties": false, "properties": {"record": {"type": "object"}}, "required": ["record"], "type": "object"}, "read_only": true}]')
|
| 41 |
+
|
| 42 |
+
def _load_state(self, initial_state):
|
| 43 |
+
support.validator(STATE_SCHEMA).validate(initial_state)
|
| 44 |
+
return copy.deepcopy(initial_state)
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def get_empty_state(cls):return {}
|
| 48 |
+
|
| 49 |
+
@classmethod
|
| 50 |
+
def get_example_state(cls):return {}
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def get_state_schema(cls):return copy.deepcopy(STATE_SCHEMA)
|
| 54 |
+
|
| 55 |
+
def _register_tools(self):
|
| 56 |
+
self._transaction_lock = threading.Lock()
|
| 57 |
+
self._transport_attempts = []
|
| 58 |
+
_, actual = support.load_domain(ROOT/'domain')
|
| 59 |
+
if support.canonical(actual) != support.canonical(self._descriptors):
|
| 60 |
+
raise ValueError('Public tool descriptors differ from the sealed domain')
|
| 61 |
+
for item in self._descriptors:
|
| 62 |
+
def bind(name):
|
| 63 |
+
def call(**arguments):return self._invoke_domain(name,arguments)
|
| 64 |
+
return call
|
| 65 |
+
output = None
|
| 66 |
+
if 'output_schema' in item:
|
| 67 |
+
output={'type':'object','oneOf':[
|
| 68 |
+
{'type':'object','required':['ok','result'],'additionalProperties':False,
|
| 69 |
+
'properties':{'ok':{'const':True},'result':copy.deepcopy(item['output_schema'])}},
|
| 70 |
+
{'type':'object','required':['ok','error'],'additionalProperties':False,
|
| 71 |
+
'properties':{'ok':{'const':False},'error':{'type':'object','required':['code','message'],
|
| 72 |
+
'properties':{'code':{'type':'string','minLength':1},'message':{'type':'string'}}}}}]}
|
| 73 |
+
self.mcp.add_tool(_DomainTool(name=item['name'],description=item['description'],
|
| 74 |
+
parameters=copy.deepcopy(item['input_schema']),output_schema=output,fn=bind(item['name'])))
|
| 75 |
+
|
| 76 |
+
def _invoke_domain(self, name, arguments):
|
| 77 |
+
with self._transaction_lock:
|
| 78 |
+
before = copy.deepcopy(self.state)
|
| 79 |
+
if len(support.canonical({'tool':name,'arguments':arguments})) > 32768:
|
| 80 |
+
raise ToolError('PUBLIC_REQUEST_LIMIT')
|
| 81 |
+
request = {'action':'transition','state':before,'tool':name,'arguments':arguments}
|
| 82 |
+
try:
|
| 83 |
+
process = subprocess.run([sys.executable,'-I','-B',str(ROOT/'runtime.py'),
|
| 84 |
+
'--environment',str(ROOT/'domain'),'--max-observation-bytes','32768'],
|
| 85 |
+
input=support.canonical(request),capture_output=True,timeout=120,
|
| 86 |
+
cwd=str(ROOT),env={'PATH':'/usr/bin:/bin','PYTHONDONTWRITEBYTECODE':'1'})
|
| 87 |
+
result = support.strict(process.stdout)
|
| 88 |
+
if process.returncode or set(result) != {'state','observation','dispatched'}:
|
| 89 |
+
raise ValueError('Transaction worker failed')
|
| 90 |
+
observation = result['observation']
|
| 91 |
+
support.canonical(observation)
|
| 92 |
+
self.state = copy.deepcopy(result['state'])
|
| 93 |
+
except Exception as exc:
|
| 94 |
+
self.state = before
|
| 95 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 96 |
+
'observation':None,'dispatched':None,'error':'TRANSACTION_INFRASTRUCTURE_ERROR'})
|
| 97 |
+
raise ToolError('TRANSACTION_INFRASTRUCTURE_ERROR') from exc
|
| 98 |
+
error = None if observation['ok'] else json.dumps(observation['error'],ensure_ascii=False)
|
| 99 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 100 |
+
'observation':copy.deepcopy(observation),'dispatched':result['dispatched']})
|
| 101 |
+
# Keep the semantic event stream identical to controller.public.
|
| 102 |
+
# Rejected pre-dispatch requests remain attempts but cannot count
|
| 103 |
+
# as observed domain evidence. MCP may itself reject extra keys
|
| 104 |
+
# before this adapter; that is a transport error, not a domain event.
|
| 105 |
+
if result['dispatched']:
|
| 106 |
+
self._log_tool_call(name,copy.deepcopy(arguments),copy.deepcopy(observation),
|
| 107 |
+
success=observation['ok'],error=error)
|
| 108 |
+
return observation
|
data/environments/eval60_datacite/runtime.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small offline transaction boundary for reviewed, candidate-specific tools.
|
| 2 |
+
|
| 3 |
+
This is not a sandbox for hostile Python. The trusted controller runs this
|
| 4 |
+
worker in a fresh interpreter for every call and keeps its state output private.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
from contextlib import redirect_stderr, redirect_stdout
|
| 10 |
+
from copy import deepcopy
|
| 11 |
+
import importlib.util
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import re
|
| 16 |
+
import sys
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
from jsonschema import Draft202012Validator, FormatChecker, validators
|
| 20 |
+
|
| 21 |
+
sys.dont_write_bytecode = True
|
| 22 |
+
MAX_REQUEST_BYTES = 32768
|
| 23 |
+
MAX_INTERNAL_BYTES = 16 * 1024 * 1024
|
| 24 |
+
DEFAULT_OBSERVATION_BYTES = 32768
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def require(condition, message):
|
| 28 |
+
if not condition:
|
| 29 |
+
raise ValueError(message)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def canonical(value):
|
| 33 |
+
# Reject Python-only coercions such as integer object keys or tuples.
|
| 34 |
+
def check(item):
|
| 35 |
+
if item is None or type(item) in (str, bool, int):
|
| 36 |
+
return
|
| 37 |
+
if type(item) is float:
|
| 38 |
+
require(math.isfinite(item), 'Nonfinite JSON number')
|
| 39 |
+
return
|
| 40 |
+
if type(item) is list:
|
| 41 |
+
for child in item:
|
| 42 |
+
check(child)
|
| 43 |
+
return
|
| 44 |
+
if type(item) is dict:
|
| 45 |
+
require(all(type(key) is str for key in item), 'JSON keys must be strings')
|
| 46 |
+
for child in item.values():
|
| 47 |
+
check(child)
|
| 48 |
+
return
|
| 49 |
+
raise ValueError('Value is not JSON')
|
| 50 |
+
check(value)
|
| 51 |
+
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
| 52 |
+
sort_keys=True, separators=(',', ':')).encode('utf-8')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def strict(raw):
|
| 56 |
+
if type(raw) is bytes:
|
| 57 |
+
raw = raw.decode('utf-8', errors='strict')
|
| 58 |
+
require(type(raw) is str, 'Expected JSON bytes or text')
|
| 59 |
+
def pairs(items):
|
| 60 |
+
result = {}
|
| 61 |
+
for key, value in items:
|
| 62 |
+
require(key not in result, 'Duplicate JSON key')
|
| 63 |
+
result[key] = value
|
| 64 |
+
return result
|
| 65 |
+
value = json.loads(raw, object_pairs_hook=pairs,
|
| 66 |
+
parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Nonfinite JSON')))
|
| 67 |
+
canonical(value)
|
| 68 |
+
return value
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read(path):
|
| 72 |
+
path = Path(path)
|
| 73 |
+
require(path.is_file() and not path.is_symlink(), 'Expected a regular file')
|
| 74 |
+
return strict(path.read_bytes())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
_TYPE_CHECKER = Draft202012Validator.TYPE_CHECKER.redefine_many({
|
| 78 |
+
'integer': lambda checker, value: type(value) is int,
|
| 79 |
+
'number': lambda checker, value: type(value) is int or (type(value) is float and math.isfinite(value)),
|
| 80 |
+
})
|
| 81 |
+
StrictValidator = validators.extend(Draft202012Validator, type_checker=_TYPE_CHECKER)
|
| 82 |
+
|
| 83 |
+
# Load the pinned optional format checker by bundle-relative path. It requires
|
| 84 |
+
# no network, installed extras, sys.path changes, or historical checkout.
|
| 85 |
+
_date_path = Path(__file__).resolve().parent / 'vendor/rfc3339_validator.py'
|
| 86 |
+
_date_spec = importlib.util.spec_from_file_location('_curated_rfc3339', _date_path)
|
| 87 |
+
_date_module = importlib.util.module_from_spec(_date_spec)
|
| 88 |
+
_date_spec.loader.exec_module(_date_module)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def validator(schema):
|
| 92 |
+
require(type(schema) in (dict, bool), 'Schema must be a JSON Schema')
|
| 93 |
+
canonical(schema)
|
| 94 |
+
formats = FormatChecker()
|
| 95 |
+
@formats.checks('date-time')
|
| 96 |
+
def date_time(value):
|
| 97 |
+
return not isinstance(value, str) or _date_module.validate_rfc3339(value.upper())
|
| 98 |
+
visited = set()
|
| 99 |
+
def inspect(value):
|
| 100 |
+
if type(value) is dict:
|
| 101 |
+
if id(value) in visited:
|
| 102 |
+
return
|
| 103 |
+
visited.add(id(value))
|
| 104 |
+
require(value != {'truncated': True}, 'Truncated schemas are unsupported')
|
| 105 |
+
require('$id' not in value and '$dynamicRef' not in value,
|
| 106 |
+
'Schema resource rebasing and dynamic references are unsupported')
|
| 107 |
+
if 'format' in value:
|
| 108 |
+
require(type(value['format']) is str and value['format'] in formats.checkers,
|
| 109 |
+
'Unsupported schema format')
|
| 110 |
+
if '$ref' in value:
|
| 111 |
+
ref = value['$ref']
|
| 112 |
+
require(type(ref) is str and (ref == '#' or ref.startswith('#/')),
|
| 113 |
+
'Only local JSON Pointer schema references are allowed')
|
| 114 |
+
current = schema
|
| 115 |
+
if ref != '#':
|
| 116 |
+
for part in ref[2:].split('/'):
|
| 117 |
+
part = part.replace('~1', '/').replace('~0', '~')
|
| 118 |
+
if type(current) is list:
|
| 119 |
+
require(part.isdigit(), 'Invalid local schema reference')
|
| 120 |
+
current = current[int(part)]
|
| 121 |
+
else:
|
| 122 |
+
require(type(current) is dict and part in current,
|
| 123 |
+
'Missing local schema reference')
|
| 124 |
+
current = current[part]
|
| 125 |
+
require(type(current) in (dict, bool), 'Schema reference is not a schema')
|
| 126 |
+
# A local reference may target a schema stored outside the
|
| 127 |
+
# standard schema keywords; inspect that target as well.
|
| 128 |
+
inspect(current)
|
| 129 |
+
# Walk schema locations, not property names or literal const/enum
|
| 130 |
+
# data (a business field named "format" is not a schema keyword).
|
| 131 |
+
for keyword in ('properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'):
|
| 132 |
+
if keyword in value:
|
| 133 |
+
require(type(value[keyword]) is dict, 'Invalid schema map')
|
| 134 |
+
for child in value[keyword].values():
|
| 135 |
+
inspect(child)
|
| 136 |
+
for keyword in ('allOf', 'anyOf', 'oneOf', 'prefixItems'):
|
| 137 |
+
if keyword in value:
|
| 138 |
+
require(type(value[keyword]) is list, 'Invalid schema sequence')
|
| 139 |
+
for child in value[keyword]:
|
| 140 |
+
inspect(child)
|
| 141 |
+
for keyword in ('items', 'contains', 'additionalProperties', 'propertyNames',
|
| 142 |
+
'unevaluatedProperties', 'unevaluatedItems', 'not', 'if', 'then', 'else'):
|
| 143 |
+
if keyword in value:
|
| 144 |
+
inspect(value[keyword])
|
| 145 |
+
inspect(schema)
|
| 146 |
+
Draft202012Validator.check_schema(schema)
|
| 147 |
+
return StrictValidator(schema, format_checker=formats)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class _BoundedSink:
|
| 151 |
+
def __init__(self):
|
| 152 |
+
self.size = 0
|
| 153 |
+
|
| 154 |
+
def write(self, value):
|
| 155 |
+
self.size += len(value.encode('utf-8'))
|
| 156 |
+
require(self.size <= 16384, 'Domain diagnostic output exceeded limit')
|
| 157 |
+
return len(value)
|
| 158 |
+
|
| 159 |
+
def flush(self):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def load_domain(environment):
|
| 164 |
+
environment = Path(environment)
|
| 165 |
+
require(environment.is_dir() and not environment.is_symlink(), 'Invalid environment directory')
|
| 166 |
+
path = environment / 'domain_tools.py'
|
| 167 |
+
require(path.is_file() and not path.is_symlink(), 'Invalid domain module')
|
| 168 |
+
spec = importlib.util.spec_from_file_location('_curated_domain_tools', path)
|
| 169 |
+
domain = importlib.util.module_from_spec(spec)
|
| 170 |
+
# No sys.path injection and no reuse of an earlier module's global state.
|
| 171 |
+
sys.modules[spec.name] = domain
|
| 172 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 173 |
+
spec.loader.exec_module(domain)
|
| 174 |
+
require(callable(getattr(domain, 'call_tool', None)), 'Domain call_tool is missing')
|
| 175 |
+
descriptors = deepcopy(getattr(domain, 'TOOL_SCHEMAS', None))
|
| 176 |
+
require(type(descriptors) is list and bool(descriptors), 'Tool schemas must be a nonempty list')
|
| 177 |
+
names = set()
|
| 178 |
+
for item in descriptors:
|
| 179 |
+
require(type(item) is dict and set(item) <= {
|
| 180 |
+
'name', 'description', 'input_schema', 'output_schema', 'read_only'
|
| 181 |
+
} and {'name', 'description', 'input_schema', 'read_only'} <= set(item),
|
| 182 |
+
'Invalid tool descriptor fields')
|
| 183 |
+
name = item['name']
|
| 184 |
+
require(type(name) is str and re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,127}', name)
|
| 185 |
+
and name not in names, 'Invalid or duplicate tool name')
|
| 186 |
+
names.add(name)
|
| 187 |
+
require(type(item['description']) is str and bool(item['description'].strip()),
|
| 188 |
+
'Tool description is required')
|
| 189 |
+
require(type(item['read_only']) is bool, 'read_only must be boolean')
|
| 190 |
+
schema = item['input_schema']
|
| 191 |
+
require(type(schema) is dict and schema.get('type') == 'object'
|
| 192 |
+
and schema.get('additionalProperties') is False,
|
| 193 |
+
'Tool input must explicitly prohibit extra arguments')
|
| 194 |
+
validator(schema)
|
| 195 |
+
if 'output_schema' in item:
|
| 196 |
+
validator(item['output_schema'])
|
| 197 |
+
return domain, descriptors
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def state_validator(environment):
|
| 201 |
+
path = Path(environment) / 'state_schema.json'
|
| 202 |
+
return validator(read(path)) if path.exists() else validator({'type': 'object'})
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def error(code, message):
|
| 206 |
+
return {'ok': False, 'error': {'code': code, 'message': message}}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def transition(environment, state, name, arguments, *, max_observation_bytes=DEFAULT_OBSERVATION_BYTES):
|
| 210 |
+
"""Return private {state, observation, dispatched}; never mutate inputs."""
|
| 211 |
+
canonical(state)
|
| 212 |
+
canonical(arguments)
|
| 213 |
+
require(type(state) is dict, 'State must be an object')
|
| 214 |
+
state_check = state_validator(environment)
|
| 215 |
+
state_check.validate(state)
|
| 216 |
+
domain, descriptors = load_domain(environment)
|
| 217 |
+
by_name = {item['name']: item for item in descriptors}
|
| 218 |
+
before, working = deepcopy(state), deepcopy(state)
|
| 219 |
+
def result(observation, dispatched, next_state=None):
|
| 220 |
+
return {'state': deepcopy(before if next_state is None else next_state),
|
| 221 |
+
'observation': deepcopy(observation), 'dispatched': dispatched}
|
| 222 |
+
if type(name) is not str or name not in by_name:
|
| 223 |
+
return result(error('UNKNOWN_TOOL', 'The requested tool is not public.'), False)
|
| 224 |
+
descriptor = by_name[name]
|
| 225 |
+
try:
|
| 226 |
+
require(type(arguments) is dict, 'Arguments must be an object')
|
| 227 |
+
validator(descriptor['input_schema']).validate(arguments)
|
| 228 |
+
except Exception:
|
| 229 |
+
return result(error('INVALID_ARGUMENTS', 'Arguments do not satisfy the public schema.'), False)
|
| 230 |
+
try:
|
| 231 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 232 |
+
observation = domain.call_tool(working, name, deepcopy(arguments))
|
| 233 |
+
except Exception:
|
| 234 |
+
return result(error('DOMAIN_EXECUTION_ERROR', 'The tool could not complete.'), True)
|
| 235 |
+
try:
|
| 236 |
+
require(type(observation) is dict and type(observation.get('ok')) is bool,
|
| 237 |
+
'Invalid domain envelope')
|
| 238 |
+
if observation['ok']:
|
| 239 |
+
require(set(observation) == {'ok', 'result'}, 'Invalid success envelope')
|
| 240 |
+
else:
|
| 241 |
+
require(set(observation) == {'ok', 'error'} and type(observation['error']) is dict,
|
| 242 |
+
'Invalid error envelope')
|
| 243 |
+
require(type(observation['error'].get('code')) is str and bool(observation['error']['code'])
|
| 244 |
+
and type(observation['error'].get('message')) is str, 'Invalid domain error')
|
| 245 |
+
encoded = canonical(observation)
|
| 246 |
+
require(type(max_observation_bytes) is int and 512 <= max_observation_bytes <= 1048576,
|
| 247 |
+
'Invalid observation limit')
|
| 248 |
+
if len(encoded) > max_observation_bytes:
|
| 249 |
+
return result(error('OBSERVATION_LIMIT', 'Tool result exceeds the public response limit.'), True)
|
| 250 |
+
if descriptor['read_only'] and canonical(working) != canonical(before):
|
| 251 |
+
return result(error('READ_ONLY_VIOLATION', 'A read-only tool attempted to change state.'), True)
|
| 252 |
+
if not observation['ok']:
|
| 253 |
+
return result(observation, True)
|
| 254 |
+
if 'output_schema' in descriptor:
|
| 255 |
+
validator(descriptor['output_schema']).validate(observation['result'])
|
| 256 |
+
state_check.validate(working)
|
| 257 |
+
canonical(working)
|
| 258 |
+
except Exception:
|
| 259 |
+
return result(error('INVALID_TOOL_RESULT', 'Tool output or state violates its contract.'), True)
|
| 260 |
+
return result(observation, True, working)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def main(argv=None):
|
| 264 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 265 |
+
parser.add_argument('--environment', type=Path, required=True)
|
| 266 |
+
parser.add_argument('--max-observation-bytes', type=int, default=DEFAULT_OBSERVATION_BYTES)
|
| 267 |
+
args = parser.parse_args(argv)
|
| 268 |
+
try:
|
| 269 |
+
raw = sys.stdin.buffer.read(MAX_INTERNAL_BYTES + 1)
|
| 270 |
+
require(len(raw) <= MAX_INTERNAL_BYTES, 'Internal request exceeds limit')
|
| 271 |
+
request = strict(raw)
|
| 272 |
+
with (patch('socket.socket', side_effect=RuntimeError('Offline worker forbids network')),
|
| 273 |
+
patch('socket.create_connection', side_effect=RuntimeError('Offline worker forbids network'))):
|
| 274 |
+
if request == {'action': 'describe'}:
|
| 275 |
+
_, descriptors = load_domain(args.environment)
|
| 276 |
+
state_validator(args.environment).validate(read(args.environment / 'state.json'))
|
| 277 |
+
value = {'tools': descriptors}
|
| 278 |
+
else:
|
| 279 |
+
require(type(request) is dict and set(request) == {'action', 'state', 'tool', 'arguments'}
|
| 280 |
+
and request['action'] == 'transition', 'Invalid internal request')
|
| 281 |
+
value = transition(args.environment, request['state'], request['tool'], request['arguments'],
|
| 282 |
+
max_observation_bytes=args.max_observation_bytes)
|
| 283 |
+
sys.stdout.buffer.write(canonical(value) + b'\n')
|
| 284 |
+
return 0
|
| 285 |
+
except Exception:
|
| 286 |
+
sys.stdout.buffer.write(canonical({'worker_error': 'RUNTIME_VALIDATION_FAILED'}) + b'\n')
|
| 287 |
+
return 1
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == '__main__':
|
| 291 |
+
raise SystemExit(main())
|
data/environments/eval60_datacite/vendor/rfc3339_validator.LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2019, Nicolas Aimetti
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
data/environments/eval60_datacite/vendor/rfc3339_validator.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Vendored 0.1.4; Python 3-only compatibility patch, see provenance.json.
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
__author__ = """Nicolas Aimetti"""
|
| 5 |
+
__email__ = 'naimetti@yahoo.com.ar'
|
| 6 |
+
__version__ = '0.1.4'
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
import calendar
|
| 10 |
+
|
| 11 |
+
RFC3339_REGEX_FLAGS = re.ASCII
|
| 12 |
+
|
| 13 |
+
RFC3339_REGEX = re.compile(r"""
|
| 14 |
+
^
|
| 15 |
+
(\d{4}) # Year
|
| 16 |
+
-
|
| 17 |
+
(0[1-9]|1[0-2]) # Month
|
| 18 |
+
-
|
| 19 |
+
(\d{2}) # Day
|
| 20 |
+
T
|
| 21 |
+
(?:[01]\d|2[0123]) # Hours
|
| 22 |
+
:
|
| 23 |
+
(?:[0-5]\d) # Minutes
|
| 24 |
+
:
|
| 25 |
+
(?:[0-5]\d) # Seconds
|
| 26 |
+
(?:\.\d+)? # Secfrac
|
| 27 |
+
(?: Z # UTC
|
| 28 |
+
| [+-](?:[01]\d|2[0123]):[0-5]\d # Offset
|
| 29 |
+
)
|
| 30 |
+
$
|
| 31 |
+
""", re.VERBOSE | RFC3339_REGEX_FLAGS)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def validate_rfc3339(date_string):
|
| 35 |
+
"""
|
| 36 |
+
Validates dates against RFC3339 datetime format
|
| 37 |
+
Leap seconds are no supported.
|
| 38 |
+
"""
|
| 39 |
+
m = RFC3339_REGEX.match(date_string)
|
| 40 |
+
if m is None:
|
| 41 |
+
return False
|
| 42 |
+
year, month, day = map(int, m.groups())
|
| 43 |
+
if not year:
|
| 44 |
+
# Year 0 is not valid a valid date
|
| 45 |
+
return False
|
| 46 |
+
(_, max_day) = calendar.monthrange(year, month)
|
| 47 |
+
if not 1 <= day <= max_day:
|
| 48 |
+
return False
|
| 49 |
+
return True
|
data/environments/eval60_erpnext/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Manually curated evaluation environment."""
|
data/environments/eval60_erpnext/domain/domain_tools.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def _obj(props, required):
|
| 6 |
+
return {"type": "object", "properties": props, "required": required, "additionalProperties": False}
|
| 7 |
+
|
| 8 |
+
REQ = _obj({
|
| 9 |
+
"requirement_id": {"type": "string"}, "item_id": {"type": "string"},
|
| 10 |
+
"warehouse_id": {"type": "string"}, "required_stock_qty": {"type": "number", "exclusiveMinimum": 0},
|
| 11 |
+
"stock_uom": {"type": "string"}, "need_by": {"type": "string", "format": "date"},
|
| 12 |
+
"status": {"type": "string", "enum": ["approved", "draft", "cancelled"]},
|
| 13 |
+
"source": {"type": "string"}
|
| 14 |
+
}, ["requirement_id", "item_id", "warehouse_id", "required_stock_qty", "stock_uom", "need_by", "status", "source"])
|
| 15 |
+
STOCK = _obj({
|
| 16 |
+
"balance_id": {"type": "string"}, "item_id": {"type": "string"}, "warehouse_id": {"type": "string"},
|
| 17 |
+
"on_hand_stock_qty": {"type": "number"}, "reserved_stock_qty": {"type": ["number", "null"]},
|
| 18 |
+
"stock_uom": {"type": "string"}, "as_of": {"type": "string", "format": "date-time"}
|
| 19 |
+
}, ["balance_id", "item_id", "warehouse_id", "on_hand_stock_qty", "reserved_stock_qty", "stock_uom", "as_of"])
|
| 20 |
+
ITEM = _obj({
|
| 21 |
+
"item_id": {"type": "string"}, "name": {"type": "string"}, "active": {"type": "boolean"},
|
| 22 |
+
"stock_uom": {"type": "string"}, "purchase_uom": {"type": "string"},
|
| 23 |
+
"purchase_conversion_id": {"type": ["string", "null"]}
|
| 24 |
+
}, ["item_id", "name", "active", "stock_uom", "purchase_uom", "purchase_conversion_id"])
|
| 25 |
+
POLINE = _obj({
|
| 26 |
+
"line_id": {"type": "string"}, "item_id": {"type": "string"}, "ordered_qty": {"type": "number"},
|
| 27 |
+
"received_qty": {"type": "number"}, "order_uom": {"type": "string"},
|
| 28 |
+
"conversion_id": {"type": ["string", "null"]}, "expected_on": {"type": "string", "format": "date"}
|
| 29 |
+
}, ["line_id", "item_id", "ordered_qty", "received_qty", "order_uom", "conversion_id", "expected_on"])
|
| 30 |
+
PO = _obj({
|
| 31 |
+
"purchase_order_id": {"type": "string"}, "supplier_id": {"type": "string"},
|
| 32 |
+
"warehouse_id": {"type": "string"}, "status": {"type": "string", "enum": ["draft", "submitted", "completed", "cancelled"]},
|
| 33 |
+
"lines": {"type": "array", "items": POLINE}
|
| 34 |
+
}, ["purchase_order_id", "supplier_id", "warehouse_id", "status", "lines"])
|
| 35 |
+
CONV = _obj({
|
| 36 |
+
"conversion_id": {"type": "string"}, "item_id": {"type": "string"},
|
| 37 |
+
"from_uom": {"type": "string"}, "to_uom": {"type": "string"},
|
| 38 |
+
"to_qty_per_from_unit": {"type": "number", "exclusiveMinimum": 0}
|
| 39 |
+
}, ["conversion_id", "item_id", "from_uom", "to_uom", "to_qty_per_from_unit"])
|
| 40 |
+
DLINE = _obj({
|
| 41 |
+
"line_no": {"type": "integer", "minimum": 1}, "item_id": {"type": "string"},
|
| 42 |
+
"request_qty": {"type": "number", "exclusiveMinimum": 0}, "request_uom": {"type": "string"},
|
| 43 |
+
"needed_stock_qty": {"type": "number", "exclusiveMinimum": 0}
|
| 44 |
+
}, ["line_no", "item_id", "request_qty", "request_uom", "needed_stock_qty"])
|
| 45 |
+
DRAFT = _obj({
|
| 46 |
+
"draft_id": {"type": "string"}, "warehouse_id": {"type": "string"},
|
| 47 |
+
"purpose": {"type": "string", "enum": ["Purchase"]}, "transaction_date": {"type": "string", "format": "date"},
|
| 48 |
+
"schedule_date": {"type": "string", "format": "date"}, "status": {"type": "string", "enum": ["draft"]},
|
| 49 |
+
"lines": {"type": "array", "minItems": 1, "items": DLINE}
|
| 50 |
+
}, ["draft_id", "warehouse_id", "purpose", "transaction_date", "schedule_date", "status", "lines"])
|
| 51 |
+
|
| 52 |
+
TOOL_SCHEMAS = [
|
| 53 |
+
{"name": "list_material_requirements", "description": "List complete synthetic local material-requirement records for a warehouse through an inclusive need-by date and one status. These records simulate the documented Material Request concept.", "input_schema": _obj({"warehouse_id": {"type": "string"}, "need_by_on_or_before": {"type": "string", "format": "date"}, "status": {"type": "string", "enum": ["approved", "draft", "cancelled"]}}, ["warehouse_id", "need_by_on_or_before", "status"]), "read_only": True, "output_schema": _obj({"requirements": {"type": "array", "items": REQ}, "count": {"type": "integer", "minimum": 1}}, ["requirements", "count"])},
|
| 54 |
+
{"name": "list_stock_balances", "description": "List complete synthetic point-in-time stock balances for a warehouse. An optional item filter supports targeted retrieval; null reserved quantity is returned as recorded.", "input_schema": _obj({"warehouse_id": {"type": "string"}, "item_id": {"type": ["string", "null"]}}, ["warehouse_id", "item_id"]), "read_only": True, "output_schema": _obj({"balances": {"type": "array", "items": STOCK}, "count": {"type": "integer", "minimum": 1}}, ["balances", "count"])},
|
| 55 |
+
{"name": "get_item", "description": "Get one complete synthetic item master, including stock and purchasing units and the discoverable conversion resource ID when different units are used.", "input_schema": _obj({"item_id": {"type": "string"}}, ["item_id"]), "read_only": True, "output_schema": ITEM},
|
| 56 |
+
{"name": "list_purchase_orders", "description": "List complete synthetic purchase orders for a warehouse whose status is in the supplied nonempty set. Lines include receipts, units, expected dates, and discoverable conversion IDs.", "input_schema": _obj({"warehouse_id": {"type": "string"}, "statuses": {"type": "array", "minItems": 1, "uniqueItems": True, "items": {"type": "string", "enum": ["draft", "submitted", "completed", "cancelled"]}}}, ["warehouse_id", "statuses"]), "read_only": True, "output_schema": _obj({"purchase_orders": {"type": "array", "items": PO}, "count": {"type": "integer", "minimum": 1}}, ["purchase_orders", "count"])},
|
| 57 |
+
{"name": "get_uom_conversion", "description": "Get a targeted synthetic item-specific unit conversion. This local record states stock-unit quantity per one purchasing-unit quantity; it is not a claim about upstream API behavior.", "input_schema": _obj({"conversion_id": {"type": "string"}}, ["conversion_id"]), "read_only": True, "output_schema": CONV},
|
| 58 |
+
{"name": "create_material_request_draft", "description": "Create and persist a synthetic, unsubmitted Material Request draft from explicit caller-supplied lines. It does not calculate replenishment and never submits the document.", "input_schema": _obj({"warehouse_id": {"type": "string"}, "purpose": {"type": "string", "enum": ["Purchase"]}, "schedule_date": {"type": "string", "format": "date"}, "lines": {"type": "array", "minItems": 1, "items": _obj({"item_id": {"type": "string"}, "request_qty": {"type": "number", "exclusiveMinimum": 0}, "request_uom": {"type": "string"}, "needed_stock_qty": {"type": "number", "exclusiveMinimum": 0}}, ["item_id", "request_qty", "request_uom", "needed_stock_qty"])}}, ["warehouse_id", "purpose", "schedule_date", "lines"]), "read_only": False, "output_schema": DRAFT}
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _err(code, message, **extra):
|
| 63 |
+
e = {"code": code, "message": message}; e.update(extra)
|
| 64 |
+
return {"ok": False, "error": e}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _date(s):
|
| 68 |
+
if not isinstance(s, str): return False
|
| 69 |
+
try: datetime.strptime(s, "%Y-%m-%d"); return len(s) == 10
|
| 70 |
+
except ValueError: return False
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _valid(name, a):
|
| 74 |
+
if not isinstance(a, dict): return "arguments must be an object"
|
| 75 |
+
schemas = {x["name"]: x["input_schema"] for x in TOOL_SCHEMAS}
|
| 76 |
+
if name not in schemas: return None
|
| 77 |
+
s = schemas[name]; p = s["properties"]
|
| 78 |
+
if set(a) != set(s["required"]): return "arguments must contain exactly the documented required properties"
|
| 79 |
+
for k, v in a.items():
|
| 80 |
+
q = p[k]; typ = q.get("type")
|
| 81 |
+
allowed = typ if isinstance(typ, list) else [typ]
|
| 82 |
+
good = ("null" in allowed and v is None) or ("string" in allowed and isinstance(v, str)) or ("array" in allowed and isinstance(v, list)) or ("number" in allowed and isinstance(v, (int, float)) and not isinstance(v, bool))
|
| 83 |
+
if not good: return "invalid type for " + k
|
| 84 |
+
if isinstance(v, str) and not v: return k + " must not be empty"
|
| 85 |
+
if q.get("format") == "date" and not _date(v): return "invalid date for " + k
|
| 86 |
+
if "enum" in q and v not in q["enum"]: return "invalid value for " + k
|
| 87 |
+
if isinstance(v, list):
|
| 88 |
+
if not v: return k + " must not be empty"
|
| 89 |
+
if q.get("uniqueItems") and any(x == y for i, x in enumerate(v) for y in v[:i]): return k + " must contain unique values"
|
| 90 |
+
enum = q.get("items", {}).get("enum")
|
| 91 |
+
if enum and any(not isinstance(x, str) or x not in enum for x in v): return "invalid member of " + k
|
| 92 |
+
if k == "lines":
|
| 93 |
+
for line in v:
|
| 94 |
+
if not isinstance(line, dict) or set(line) != {"item_id", "request_qty", "request_uom", "needed_stock_qty"}: return "invalid draft line shape"
|
| 95 |
+
if not isinstance(line["item_id"], str) or not line["item_id"] or not isinstance(line["request_uom"], str) or not line["request_uom"]: return "invalid draft line identifier or unit"
|
| 96 |
+
for n in ("request_qty", "needed_stock_qty"):
|
| 97 |
+
if not isinstance(line[n], (int, float)) or isinstance(line[n], bool) or line[n] <= 0: return "draft line quantities must be positive numbers"
|
| 98 |
+
return None
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def call_tool(state, name, arguments):
|
| 102 |
+
if name not in {x["name"] for x in TOOL_SCHEMAS}: return _err("UNKNOWN_TOOL", "Unknown tool name", tool=name)
|
| 103 |
+
problem = _valid(name, arguments)
|
| 104 |
+
if problem: return _err("INVALID_ARGUMENT", problem)
|
| 105 |
+
a = arguments
|
| 106 |
+
if name == "list_material_requirements":
|
| 107 |
+
rows = [x for x in state["requirements"] if x["warehouse_id"] == a["warehouse_id"] and x["need_by"] <= a["need_by_on_or_before"] and x["status"] == a["status"]]
|
| 108 |
+
rows.sort(key=lambda x: (x["need_by"], x["requirement_id"]))
|
| 109 |
+
if not rows: return _err("NO_MATCH", "No material requirements match the supplied filters")
|
| 110 |
+
return {"ok": True, "result": {"requirements": deepcopy(rows), "count": len(rows)}}
|
| 111 |
+
if name == "list_stock_balances":
|
| 112 |
+
rows = [x for x in state["stock_balances"] if x["warehouse_id"] == a["warehouse_id"] and (a["item_id"] is None or x["item_id"] == a["item_id"])]
|
| 113 |
+
rows.sort(key=lambda x: x["item_id"])
|
| 114 |
+
if not rows: return _err("NO_MATCH", "No stock balances match the supplied filters")
|
| 115 |
+
return {"ok": True, "result": {"balances": deepcopy(rows), "count": len(rows)}}
|
| 116 |
+
if name == "get_item":
|
| 117 |
+
rows = [x for x in state["items"] if x["item_id"] == a["item_id"]]
|
| 118 |
+
if not rows: return _err("NOT_FOUND", "Item does not exist", resource="item:" + a["item_id"])
|
| 119 |
+
return {"ok": True, "result": deepcopy(rows[0])}
|
| 120 |
+
if name == "list_purchase_orders":
|
| 121 |
+
rows = [x for x in state["purchase_orders"] if x["warehouse_id"] == a["warehouse_id"] and x["status"] in a["statuses"]]
|
| 122 |
+
rows.sort(key=lambda x: x["purchase_order_id"])
|
| 123 |
+
if not rows: return _err("NO_MATCH", "No purchase orders match the supplied filters")
|
| 124 |
+
return {"ok": True, "result": {"purchase_orders": deepcopy(rows), "count": len(rows)}}
|
| 125 |
+
if name == "get_uom_conversion":
|
| 126 |
+
rows = [x for x in state["uom_conversions"] if x["conversion_id"] == a["conversion_id"]]
|
| 127 |
+
if not rows: return _err("NOT_FOUND", "Unit conversion does not exist", resource="uom_conversion:" + a["conversion_id"])
|
| 128 |
+
rid = a["conversion_id"]
|
| 129 |
+
if not state["availability"]["uom_conversions"].get(rid, False):
|
| 130 |
+
return _err("UNAVAILABLE", "Unit conversion resource is currently unavailable", resource="uom_conversion:" + rid)
|
| 131 |
+
return {"ok": True, "result": deepcopy(rows[0])}
|
| 132 |
+
# Validate all linked values before mutation; failures are atomic.
|
| 133 |
+
item_map = {x["item_id"]: x for x in state["items"]}
|
| 134 |
+
seen = set()
|
| 135 |
+
for line in a["lines"]:
|
| 136 |
+
iid = line["item_id"]
|
| 137 |
+
if iid not in item_map: return _err("NOT_FOUND", "Draft line item does not exist", resource="item:" + iid)
|
| 138 |
+
if iid in seen: return _err("CONFLICT", "A draft may contain only one line per item", resource="item:" + iid)
|
| 139 |
+
seen.add(iid)
|
| 140 |
+
if line["request_uom"] != item_map[iid]["purchase_uom"]: return _err("INVALID_ARGUMENT", "request_uom must equal the item's purchase_uom", resource="item:" + iid)
|
| 141 |
+
n = state["next_draft_number"]
|
| 142 |
+
draft = {"draft_id": "MR-DRAFT-%04d" % n, "warehouse_id": a["warehouse_id"], "purpose": "Purchase", "transaction_date": state["fixed_clock"][:10], "schedule_date": a["schedule_date"], "status": "draft", "lines": []}
|
| 143 |
+
for i, line in enumerate(a["lines"], 1):
|
| 144 |
+
row = {"line_no": i}; row.update(deepcopy(line)); draft["lines"].append(row)
|
| 145 |
+
state["material_request_drafts"].append(deepcopy(draft)); state["next_draft_number"] = n + 1
|
| 146 |
+
return {"ok": True, "result": deepcopy(draft)}
|
data/environments/eval60_erpnext/environment.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Official tool adapter to the exact sealed transaction runtime."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import copy
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import threading
|
| 10 |
+
from typing import Any, Callable
|
| 11 |
+
|
| 12 |
+
from fastmcp.tools import Tool
|
| 13 |
+
from fastmcp.tools.tool import ToolResult
|
| 14 |
+
from pydantic import Field
|
| 15 |
+
from hera_environment import BaseEnvironment, ToolError
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parent
|
| 18 |
+
_spec = importlib.util.spec_from_file_location(__name__ + '_runtime', ROOT/'runtime.py')
|
| 19 |
+
support = importlib.util.module_from_spec(_spec)
|
| 20 |
+
_spec.loader.exec_module(support)
|
| 21 |
+
STATE_SCHEMA = json.loads('{"type": "object"}')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _DomainTool(Tool):
|
| 25 |
+
fn: Callable[..., Any] = Field(exclude=True)
|
| 26 |
+
|
| 27 |
+
async def run(self, arguments: dict[str, Any]) -> ToolResult:
|
| 28 |
+
envelope = self.fn(**arguments)
|
| 29 |
+
return ToolResult(content=json.dumps(envelope,ensure_ascii=False,allow_nan=False),
|
| 30 |
+
structured_content=envelope,is_error=envelope['ok'] is False)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Environment(BaseEnvironment):
|
| 34 |
+
env_name = 'eval60_erpnext'
|
| 35 |
+
short_name = 'ERPNext'
|
| 36 |
+
always_skip_fields = set()
|
| 37 |
+
mutation_tools = set()
|
| 38 |
+
mutation_id_fields = set()
|
| 39 |
+
tool_kinds = json.loads('{"create_material_request_draft": "commit", "get_item": "lookup", "get_uom_conversion": "lookup", "list_material_requirements": "lookup", "list_purchase_orders": "lookup", "list_stock_balances": "lookup"}')
|
| 40 |
+
_descriptors = json.loads('[{"description": "List complete synthetic local material-requirement records for a warehouse through an inclusive need-by date and one status. These records simulate the documented Material Request concept.", "input_schema": {"additionalProperties": false, "properties": {"need_by_on_or_before": {"format": "date", "type": "string"}, "status": {"enum": ["approved", "draft", "cancelled"], "type": "string"}, "warehouse_id": {"type": "string"}}, "required": ["warehouse_id", "need_by_on_or_before", "status"], "type": "object"}, "name": "list_material_requirements", "output_schema": {"additionalProperties": false, "properties": {"count": {"minimum": 1, "type": "integer"}, "requirements": {"items": {"additionalProperties": false, "properties": {"item_id": {"type": "string"}, "need_by": {"format": "date", "type": "string"}, "required_stock_qty": {"exclusiveMinimum": 0, "type": "number"}, "requirement_id": {"type": "string"}, "source": {"type": "string"}, "status": {"enum": ["approved", "draft", "cancelled"], "type": "string"}, "stock_uom": {"type": "string"}, "warehouse_id": {"type": "string"}}, "required": ["requirement_id", "item_id", "warehouse_id", "required_stock_qty", "stock_uom", "need_by", "status", "source"], "type": "object"}, "type": "array"}}, "required": ["requirements", "count"], "type": "object"}, "read_only": true}, {"description": "List complete synthetic point-in-time stock balances for a warehouse. An optional item filter supports targeted retrieval; null reserved quantity is returned as recorded.", "input_schema": {"additionalProperties": false, "properties": {"item_id": {"type": ["string", "null"]}, "warehouse_id": {"type": "string"}}, "required": ["warehouse_id", "item_id"], "type": "object"}, "name": "list_stock_balances", "output_schema": {"additionalProperties": false, "properties": {"balances": {"items": {"additionalProperties": false, "properties": {"as_of": {"format": "date-time", "type": "string"}, "balance_id": {"type": "string"}, "item_id": {"type": "string"}, "on_hand_stock_qty": {"type": "number"}, "reserved_stock_qty": {"type": ["number", "null"]}, "stock_uom": {"type": "string"}, "warehouse_id": {"type": "string"}}, "required": ["balance_id", "item_id", "warehouse_id", "on_hand_stock_qty", "reserved_stock_qty", "stock_uom", "as_of"], "type": "object"}, "type": "array"}, "count": {"minimum": 1, "type": "integer"}}, "required": ["balances", "count"], "type": "object"}, "read_only": true}, {"description": "Get one complete synthetic item master, including stock and purchasing units and the discoverable conversion resource ID when different units are used.", "input_schema": {"additionalProperties": false, "properties": {"item_id": {"type": "string"}}, "required": ["item_id"], "type": "object"}, "name": "get_item", "output_schema": {"additionalProperties": false, "properties": {"active": {"type": "boolean"}, "item_id": {"type": "string"}, "name": {"type": "string"}, "purchase_conversion_id": {"type": ["string", "null"]}, "purchase_uom": {"type": "string"}, "stock_uom": {"type": "string"}}, "required": ["item_id", "name", "active", "stock_uom", "purchase_uom", "purchase_conversion_id"], "type": "object"}, "read_only": true}, {"description": "List complete synthetic purchase orders for a warehouse whose status is in the supplied nonempty set. Lines include receipts, units, expected dates, and discoverable conversion IDs.", "input_schema": {"additionalProperties": false, "properties": {"statuses": {"items": {"enum": ["draft", "submitted", "completed", "cancelled"], "type": "string"}, "minItems": 1, "type": "array", "uniqueItems": true}, "warehouse_id": {"type": "string"}}, "required": ["warehouse_id", "statuses"], "type": "object"}, "name": "list_purchase_orders", "output_schema": {"additionalProperties": false, "properties": {"count": {"minimum": 1, "type": "integer"}, "purchase_orders": {"items": {"additionalProperties": false, "properties": {"lines": {"items": {"additionalProperties": false, "properties": {"conversion_id": {"type": ["string", "null"]}, "expected_on": {"format": "date", "type": "string"}, "item_id": {"type": "string"}, "line_id": {"type": "string"}, "order_uom": {"type": "string"}, "ordered_qty": {"type": "number"}, "received_qty": {"type": "number"}}, "required": ["line_id", "item_id", "ordered_qty", "received_qty", "order_uom", "conversion_id", "expected_on"], "type": "object"}, "type": "array"}, "purchase_order_id": {"type": "string"}, "status": {"enum": ["draft", "submitted", "completed", "cancelled"], "type": "string"}, "supplier_id": {"type": "string"}, "warehouse_id": {"type": "string"}}, "required": ["purchase_order_id", "supplier_id", "warehouse_id", "status", "lines"], "type": "object"}, "type": "array"}}, "required": ["purchase_orders", "count"], "type": "object"}, "read_only": true}, {"description": "Get a targeted synthetic item-specific unit conversion. This local record states stock-unit quantity per one purchasing-unit quantity; it is not a claim about upstream API behavior.", "input_schema": {"additionalProperties": false, "properties": {"conversion_id": {"type": "string"}}, "required": ["conversion_id"], "type": "object"}, "name": "get_uom_conversion", "output_schema": {"additionalProperties": false, "properties": {"conversion_id": {"type": "string"}, "from_uom": {"type": "string"}, "item_id": {"type": "string"}, "to_qty_per_from_unit": {"exclusiveMinimum": 0, "type": "number"}, "to_uom": {"type": "string"}}, "required": ["conversion_id", "item_id", "from_uom", "to_uom", "to_qty_per_from_unit"], "type": "object"}, "read_only": true}, {"description": "Create and persist a synthetic, unsubmitted Material Request draft from explicit caller-supplied lines. It does not calculate replenishment and never submits the document.", "input_schema": {"additionalProperties": false, "properties": {"lines": {"items": {"additionalProperties": false, "properties": {"item_id": {"type": "string"}, "needed_stock_qty": {"exclusiveMinimum": 0, "type": "number"}, "request_qty": {"exclusiveMinimum": 0, "type": "number"}, "request_uom": {"type": "string"}}, "required": ["item_id", "request_qty", "request_uom", "needed_stock_qty"], "type": "object"}, "minItems": 1, "type": "array"}, "purpose": {"enum": ["Purchase"], "type": "string"}, "schedule_date": {"format": "date", "type": "string"}, "warehouse_id": {"type": "string"}}, "required": ["warehouse_id", "purpose", "schedule_date", "lines"], "type": "object"}, "name": "create_material_request_draft", "output_schema": {"additionalProperties": false, "properties": {"draft_id": {"type": "string"}, "lines": {"items": {"additionalProperties": false, "properties": {"item_id": {"type": "string"}, "line_no": {"minimum": 1, "type": "integer"}, "needed_stock_qty": {"exclusiveMinimum": 0, "type": "number"}, "request_qty": {"exclusiveMinimum": 0, "type": "number"}, "request_uom": {"type": "string"}}, "required": ["line_no", "item_id", "request_qty", "request_uom", "needed_stock_qty"], "type": "object"}, "minItems": 1, "type": "array"}, "purpose": {"enum": ["Purchase"], "type": "string"}, "schedule_date": {"format": "date", "type": "string"}, "status": {"enum": ["draft"], "type": "string"}, "transaction_date": {"format": "date", "type": "string"}, "warehouse_id": {"type": "string"}}, "required": ["draft_id", "warehouse_id", "purpose", "transaction_date", "schedule_date", "status", "lines"], "type": "object"}, "read_only": false}]')
|
| 41 |
+
|
| 42 |
+
def _load_state(self, initial_state):
|
| 43 |
+
support.validator(STATE_SCHEMA).validate(initial_state)
|
| 44 |
+
return copy.deepcopy(initial_state)
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def get_empty_state(cls):return {}
|
| 48 |
+
|
| 49 |
+
@classmethod
|
| 50 |
+
def get_example_state(cls):return {}
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def get_state_schema(cls):return copy.deepcopy(STATE_SCHEMA)
|
| 54 |
+
|
| 55 |
+
def _register_tools(self):
|
| 56 |
+
self._transaction_lock = threading.Lock()
|
| 57 |
+
self._transport_attempts = []
|
| 58 |
+
_, actual = support.load_domain(ROOT/'domain')
|
| 59 |
+
if support.canonical(actual) != support.canonical(self._descriptors):
|
| 60 |
+
raise ValueError('Public tool descriptors differ from the sealed domain')
|
| 61 |
+
for item in self._descriptors:
|
| 62 |
+
def bind(name):
|
| 63 |
+
def call(**arguments):return self._invoke_domain(name,arguments)
|
| 64 |
+
return call
|
| 65 |
+
output = None
|
| 66 |
+
if 'output_schema' in item:
|
| 67 |
+
output={'type':'object','oneOf':[
|
| 68 |
+
{'type':'object','required':['ok','result'],'additionalProperties':False,
|
| 69 |
+
'properties':{'ok':{'const':True},'result':copy.deepcopy(item['output_schema'])}},
|
| 70 |
+
{'type':'object','required':['ok','error'],'additionalProperties':False,
|
| 71 |
+
'properties':{'ok':{'const':False},'error':{'type':'object','required':['code','message'],
|
| 72 |
+
'properties':{'code':{'type':'string','minLength':1},'message':{'type':'string'}}}}}]}
|
| 73 |
+
self.mcp.add_tool(_DomainTool(name=item['name'],description=item['description'],
|
| 74 |
+
parameters=copy.deepcopy(item['input_schema']),output_schema=output,fn=bind(item['name'])))
|
| 75 |
+
|
| 76 |
+
def _invoke_domain(self, name, arguments):
|
| 77 |
+
with self._transaction_lock:
|
| 78 |
+
before = copy.deepcopy(self.state)
|
| 79 |
+
if len(support.canonical({'tool':name,'arguments':arguments})) > 32768:
|
| 80 |
+
raise ToolError('PUBLIC_REQUEST_LIMIT')
|
| 81 |
+
request = {'action':'transition','state':before,'tool':name,'arguments':arguments}
|
| 82 |
+
try:
|
| 83 |
+
process = subprocess.run([sys.executable,'-I','-B',str(ROOT/'runtime.py'),
|
| 84 |
+
'--environment',str(ROOT/'domain'),'--max-observation-bytes','32768'],
|
| 85 |
+
input=support.canonical(request),capture_output=True,timeout=120,
|
| 86 |
+
cwd=str(ROOT),env={'PATH':'/usr/bin:/bin','PYTHONDONTWRITEBYTECODE':'1'})
|
| 87 |
+
result = support.strict(process.stdout)
|
| 88 |
+
if process.returncode or set(result) != {'state','observation','dispatched'}:
|
| 89 |
+
raise ValueError('Transaction worker failed')
|
| 90 |
+
observation = result['observation']
|
| 91 |
+
support.canonical(observation)
|
| 92 |
+
self.state = copy.deepcopy(result['state'])
|
| 93 |
+
except Exception as exc:
|
| 94 |
+
self.state = before
|
| 95 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 96 |
+
'observation':None,'dispatched':None,'error':'TRANSACTION_INFRASTRUCTURE_ERROR'})
|
| 97 |
+
raise ToolError('TRANSACTION_INFRASTRUCTURE_ERROR') from exc
|
| 98 |
+
error = None if observation['ok'] else json.dumps(observation['error'],ensure_ascii=False)
|
| 99 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 100 |
+
'observation':copy.deepcopy(observation),'dispatched':result['dispatched']})
|
| 101 |
+
# Keep the semantic event stream identical to controller.public.
|
| 102 |
+
# Rejected pre-dispatch requests remain attempts but cannot count
|
| 103 |
+
# as observed domain evidence. MCP may itself reject extra keys
|
| 104 |
+
# before this adapter; that is a transport error, not a domain event.
|
| 105 |
+
if result['dispatched']:
|
| 106 |
+
self._log_tool_call(name,copy.deepcopy(arguments),copy.deepcopy(observation),
|
| 107 |
+
success=observation['ok'],error=error)
|
| 108 |
+
return observation
|
data/environments/eval60_erpnext/runtime.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small offline transaction boundary for reviewed, candidate-specific tools.
|
| 2 |
+
|
| 3 |
+
This is not a sandbox for hostile Python. The trusted controller runs this
|
| 4 |
+
worker in a fresh interpreter for every call and keeps its state output private.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
from contextlib import redirect_stderr, redirect_stdout
|
| 10 |
+
from copy import deepcopy
|
| 11 |
+
import importlib.util
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import re
|
| 16 |
+
import sys
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
from jsonschema import Draft202012Validator, FormatChecker, validators
|
| 20 |
+
|
| 21 |
+
sys.dont_write_bytecode = True
|
| 22 |
+
MAX_REQUEST_BYTES = 32768
|
| 23 |
+
MAX_INTERNAL_BYTES = 16 * 1024 * 1024
|
| 24 |
+
DEFAULT_OBSERVATION_BYTES = 32768
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def require(condition, message):
|
| 28 |
+
if not condition:
|
| 29 |
+
raise ValueError(message)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def canonical(value):
|
| 33 |
+
# Reject Python-only coercions such as integer object keys or tuples.
|
| 34 |
+
def check(item):
|
| 35 |
+
if item is None or type(item) in (str, bool, int):
|
| 36 |
+
return
|
| 37 |
+
if type(item) is float:
|
| 38 |
+
require(math.isfinite(item), 'Nonfinite JSON number')
|
| 39 |
+
return
|
| 40 |
+
if type(item) is list:
|
| 41 |
+
for child in item:
|
| 42 |
+
check(child)
|
| 43 |
+
return
|
| 44 |
+
if type(item) is dict:
|
| 45 |
+
require(all(type(key) is str for key in item), 'JSON keys must be strings')
|
| 46 |
+
for child in item.values():
|
| 47 |
+
check(child)
|
| 48 |
+
return
|
| 49 |
+
raise ValueError('Value is not JSON')
|
| 50 |
+
check(value)
|
| 51 |
+
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
| 52 |
+
sort_keys=True, separators=(',', ':')).encode('utf-8')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def strict(raw):
|
| 56 |
+
if type(raw) is bytes:
|
| 57 |
+
raw = raw.decode('utf-8', errors='strict')
|
| 58 |
+
require(type(raw) is str, 'Expected JSON bytes or text')
|
| 59 |
+
def pairs(items):
|
| 60 |
+
result = {}
|
| 61 |
+
for key, value in items:
|
| 62 |
+
require(key not in result, 'Duplicate JSON key')
|
| 63 |
+
result[key] = value
|
| 64 |
+
return result
|
| 65 |
+
value = json.loads(raw, object_pairs_hook=pairs,
|
| 66 |
+
parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Nonfinite JSON')))
|
| 67 |
+
canonical(value)
|
| 68 |
+
return value
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read(path):
|
| 72 |
+
path = Path(path)
|
| 73 |
+
require(path.is_file() and not path.is_symlink(), 'Expected a regular file')
|
| 74 |
+
return strict(path.read_bytes())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
_TYPE_CHECKER = Draft202012Validator.TYPE_CHECKER.redefine_many({
|
| 78 |
+
'integer': lambda checker, value: type(value) is int,
|
| 79 |
+
'number': lambda checker, value: type(value) is int or (type(value) is float and math.isfinite(value)),
|
| 80 |
+
})
|
| 81 |
+
StrictValidator = validators.extend(Draft202012Validator, type_checker=_TYPE_CHECKER)
|
| 82 |
+
|
| 83 |
+
# Load the pinned optional format checker by bundle-relative path. It requires
|
| 84 |
+
# no network, installed extras, sys.path changes, or historical checkout.
|
| 85 |
+
_date_path = Path(__file__).resolve().parent / 'vendor/rfc3339_validator.py'
|
| 86 |
+
_date_spec = importlib.util.spec_from_file_location('_curated_rfc3339', _date_path)
|
| 87 |
+
_date_module = importlib.util.module_from_spec(_date_spec)
|
| 88 |
+
_date_spec.loader.exec_module(_date_module)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def validator(schema):
|
| 92 |
+
require(type(schema) in (dict, bool), 'Schema must be a JSON Schema')
|
| 93 |
+
canonical(schema)
|
| 94 |
+
formats = FormatChecker()
|
| 95 |
+
@formats.checks('date-time')
|
| 96 |
+
def date_time(value):
|
| 97 |
+
return not isinstance(value, str) or _date_module.validate_rfc3339(value.upper())
|
| 98 |
+
visited = set()
|
| 99 |
+
def inspect(value):
|
| 100 |
+
if type(value) is dict:
|
| 101 |
+
if id(value) in visited:
|
| 102 |
+
return
|
| 103 |
+
visited.add(id(value))
|
| 104 |
+
require(value != {'truncated': True}, 'Truncated schemas are unsupported')
|
| 105 |
+
require('$id' not in value and '$dynamicRef' not in value,
|
| 106 |
+
'Schema resource rebasing and dynamic references are unsupported')
|
| 107 |
+
if 'format' in value:
|
| 108 |
+
require(type(value['format']) is str and value['format'] in formats.checkers,
|
| 109 |
+
'Unsupported schema format')
|
| 110 |
+
if '$ref' in value:
|
| 111 |
+
ref = value['$ref']
|
| 112 |
+
require(type(ref) is str and (ref == '#' or ref.startswith('#/')),
|
| 113 |
+
'Only local JSON Pointer schema references are allowed')
|
| 114 |
+
current = schema
|
| 115 |
+
if ref != '#':
|
| 116 |
+
for part in ref[2:].split('/'):
|
| 117 |
+
part = part.replace('~1', '/').replace('~0', '~')
|
| 118 |
+
if type(current) is list:
|
| 119 |
+
require(part.isdigit(), 'Invalid local schema reference')
|
| 120 |
+
current = current[int(part)]
|
| 121 |
+
else:
|
| 122 |
+
require(type(current) is dict and part in current,
|
| 123 |
+
'Missing local schema reference')
|
| 124 |
+
current = current[part]
|
| 125 |
+
require(type(current) in (dict, bool), 'Schema reference is not a schema')
|
| 126 |
+
# A local reference may target a schema stored outside the
|
| 127 |
+
# standard schema keywords; inspect that target as well.
|
| 128 |
+
inspect(current)
|
| 129 |
+
# Walk schema locations, not property names or literal const/enum
|
| 130 |
+
# data (a business field named "format" is not a schema keyword).
|
| 131 |
+
for keyword in ('properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'):
|
| 132 |
+
if keyword in value:
|
| 133 |
+
require(type(value[keyword]) is dict, 'Invalid schema map')
|
| 134 |
+
for child in value[keyword].values():
|
| 135 |
+
inspect(child)
|
| 136 |
+
for keyword in ('allOf', 'anyOf', 'oneOf', 'prefixItems'):
|
| 137 |
+
if keyword in value:
|
| 138 |
+
require(type(value[keyword]) is list, 'Invalid schema sequence')
|
| 139 |
+
for child in value[keyword]:
|
| 140 |
+
inspect(child)
|
| 141 |
+
for keyword in ('items', 'contains', 'additionalProperties', 'propertyNames',
|
| 142 |
+
'unevaluatedProperties', 'unevaluatedItems', 'not', 'if', 'then', 'else'):
|
| 143 |
+
if keyword in value:
|
| 144 |
+
inspect(value[keyword])
|
| 145 |
+
inspect(schema)
|
| 146 |
+
Draft202012Validator.check_schema(schema)
|
| 147 |
+
return StrictValidator(schema, format_checker=formats)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class _BoundedSink:
|
| 151 |
+
def __init__(self):
|
| 152 |
+
self.size = 0
|
| 153 |
+
|
| 154 |
+
def write(self, value):
|
| 155 |
+
self.size += len(value.encode('utf-8'))
|
| 156 |
+
require(self.size <= 16384, 'Domain diagnostic output exceeded limit')
|
| 157 |
+
return len(value)
|
| 158 |
+
|
| 159 |
+
def flush(self):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def load_domain(environment):
|
| 164 |
+
environment = Path(environment)
|
| 165 |
+
require(environment.is_dir() and not environment.is_symlink(), 'Invalid environment directory')
|
| 166 |
+
path = environment / 'domain_tools.py'
|
| 167 |
+
require(path.is_file() and not path.is_symlink(), 'Invalid domain module')
|
| 168 |
+
spec = importlib.util.spec_from_file_location('_curated_domain_tools', path)
|
| 169 |
+
domain = importlib.util.module_from_spec(spec)
|
| 170 |
+
# No sys.path injection and no reuse of an earlier module's global state.
|
| 171 |
+
sys.modules[spec.name] = domain
|
| 172 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 173 |
+
spec.loader.exec_module(domain)
|
| 174 |
+
require(callable(getattr(domain, 'call_tool', None)), 'Domain call_tool is missing')
|
| 175 |
+
descriptors = deepcopy(getattr(domain, 'TOOL_SCHEMAS', None))
|
| 176 |
+
require(type(descriptors) is list and bool(descriptors), 'Tool schemas must be a nonempty list')
|
| 177 |
+
names = set()
|
| 178 |
+
for item in descriptors:
|
| 179 |
+
require(type(item) is dict and set(item) <= {
|
| 180 |
+
'name', 'description', 'input_schema', 'output_schema', 'read_only'
|
| 181 |
+
} and {'name', 'description', 'input_schema', 'read_only'} <= set(item),
|
| 182 |
+
'Invalid tool descriptor fields')
|
| 183 |
+
name = item['name']
|
| 184 |
+
require(type(name) is str and re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,127}', name)
|
| 185 |
+
and name not in names, 'Invalid or duplicate tool name')
|
| 186 |
+
names.add(name)
|
| 187 |
+
require(type(item['description']) is str and bool(item['description'].strip()),
|
| 188 |
+
'Tool description is required')
|
| 189 |
+
require(type(item['read_only']) is bool, 'read_only must be boolean')
|
| 190 |
+
schema = item['input_schema']
|
| 191 |
+
require(type(schema) is dict and schema.get('type') == 'object'
|
| 192 |
+
and schema.get('additionalProperties') is False,
|
| 193 |
+
'Tool input must explicitly prohibit extra arguments')
|
| 194 |
+
validator(schema)
|
| 195 |
+
if 'output_schema' in item:
|
| 196 |
+
validator(item['output_schema'])
|
| 197 |
+
return domain, descriptors
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def state_validator(environment):
|
| 201 |
+
path = Path(environment) / 'state_schema.json'
|
| 202 |
+
return validator(read(path)) if path.exists() else validator({'type': 'object'})
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def error(code, message):
|
| 206 |
+
return {'ok': False, 'error': {'code': code, 'message': message}}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def transition(environment, state, name, arguments, *, max_observation_bytes=DEFAULT_OBSERVATION_BYTES):
|
| 210 |
+
"""Return private {state, observation, dispatched}; never mutate inputs."""
|
| 211 |
+
canonical(state)
|
| 212 |
+
canonical(arguments)
|
| 213 |
+
require(type(state) is dict, 'State must be an object')
|
| 214 |
+
state_check = state_validator(environment)
|
| 215 |
+
state_check.validate(state)
|
| 216 |
+
domain, descriptors = load_domain(environment)
|
| 217 |
+
by_name = {item['name']: item for item in descriptors}
|
| 218 |
+
before, working = deepcopy(state), deepcopy(state)
|
| 219 |
+
def result(observation, dispatched, next_state=None):
|
| 220 |
+
return {'state': deepcopy(before if next_state is None else next_state),
|
| 221 |
+
'observation': deepcopy(observation), 'dispatched': dispatched}
|
| 222 |
+
if type(name) is not str or name not in by_name:
|
| 223 |
+
return result(error('UNKNOWN_TOOL', 'The requested tool is not public.'), False)
|
| 224 |
+
descriptor = by_name[name]
|
| 225 |
+
try:
|
| 226 |
+
require(type(arguments) is dict, 'Arguments must be an object')
|
| 227 |
+
validator(descriptor['input_schema']).validate(arguments)
|
| 228 |
+
except Exception:
|
| 229 |
+
return result(error('INVALID_ARGUMENTS', 'Arguments do not satisfy the public schema.'), False)
|
| 230 |
+
try:
|
| 231 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 232 |
+
observation = domain.call_tool(working, name, deepcopy(arguments))
|
| 233 |
+
except Exception:
|
| 234 |
+
return result(error('DOMAIN_EXECUTION_ERROR', 'The tool could not complete.'), True)
|
| 235 |
+
try:
|
| 236 |
+
require(type(observation) is dict and type(observation.get('ok')) is bool,
|
| 237 |
+
'Invalid domain envelope')
|
| 238 |
+
if observation['ok']:
|
| 239 |
+
require(set(observation) == {'ok', 'result'}, 'Invalid success envelope')
|
| 240 |
+
else:
|
| 241 |
+
require(set(observation) == {'ok', 'error'} and type(observation['error']) is dict,
|
| 242 |
+
'Invalid error envelope')
|
| 243 |
+
require(type(observation['error'].get('code')) is str and bool(observation['error']['code'])
|
| 244 |
+
and type(observation['error'].get('message')) is str, 'Invalid domain error')
|
| 245 |
+
encoded = canonical(observation)
|
| 246 |
+
require(type(max_observation_bytes) is int and 512 <= max_observation_bytes <= 1048576,
|
| 247 |
+
'Invalid observation limit')
|
| 248 |
+
if len(encoded) > max_observation_bytes:
|
| 249 |
+
return result(error('OBSERVATION_LIMIT', 'Tool result exceeds the public response limit.'), True)
|
| 250 |
+
if descriptor['read_only'] and canonical(working) != canonical(before):
|
| 251 |
+
return result(error('READ_ONLY_VIOLATION', 'A read-only tool attempted to change state.'), True)
|
| 252 |
+
if not observation['ok']:
|
| 253 |
+
return result(observation, True)
|
| 254 |
+
if 'output_schema' in descriptor:
|
| 255 |
+
validator(descriptor['output_schema']).validate(observation['result'])
|
| 256 |
+
state_check.validate(working)
|
| 257 |
+
canonical(working)
|
| 258 |
+
except Exception:
|
| 259 |
+
return result(error('INVALID_TOOL_RESULT', 'Tool output or state violates its contract.'), True)
|
| 260 |
+
return result(observation, True, working)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def main(argv=None):
|
| 264 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 265 |
+
parser.add_argument('--environment', type=Path, required=True)
|
| 266 |
+
parser.add_argument('--max-observation-bytes', type=int, default=DEFAULT_OBSERVATION_BYTES)
|
| 267 |
+
args = parser.parse_args(argv)
|
| 268 |
+
try:
|
| 269 |
+
raw = sys.stdin.buffer.read(MAX_INTERNAL_BYTES + 1)
|
| 270 |
+
require(len(raw) <= MAX_INTERNAL_BYTES, 'Internal request exceeds limit')
|
| 271 |
+
request = strict(raw)
|
| 272 |
+
with (patch('socket.socket', side_effect=RuntimeError('Offline worker forbids network')),
|
| 273 |
+
patch('socket.create_connection', side_effect=RuntimeError('Offline worker forbids network'))):
|
| 274 |
+
if request == {'action': 'describe'}:
|
| 275 |
+
_, descriptors = load_domain(args.environment)
|
| 276 |
+
state_validator(args.environment).validate(read(args.environment / 'state.json'))
|
| 277 |
+
value = {'tools': descriptors}
|
| 278 |
+
else:
|
| 279 |
+
require(type(request) is dict and set(request) == {'action', 'state', 'tool', 'arguments'}
|
| 280 |
+
and request['action'] == 'transition', 'Invalid internal request')
|
| 281 |
+
value = transition(args.environment, request['state'], request['tool'], request['arguments'],
|
| 282 |
+
max_observation_bytes=args.max_observation_bytes)
|
| 283 |
+
sys.stdout.buffer.write(canonical(value) + b'\n')
|
| 284 |
+
return 0
|
| 285 |
+
except Exception:
|
| 286 |
+
sys.stdout.buffer.write(canonical({'worker_error': 'RUNTIME_VALIDATION_FAILED'}) + b'\n')
|
| 287 |
+
return 1
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == '__main__':
|
| 291 |
+
raise SystemExit(main())
|
data/environments/eval60_erpnext/vendor/rfc3339_validator.LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2019, Nicolas Aimetti
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
data/environments/eval60_erpnext/vendor/rfc3339_validator.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Vendored 0.1.4; Python 3-only compatibility patch, see provenance.json.
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
__author__ = """Nicolas Aimetti"""
|
| 5 |
+
__email__ = 'naimetti@yahoo.com.ar'
|
| 6 |
+
__version__ = '0.1.4'
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
import calendar
|
| 10 |
+
|
| 11 |
+
RFC3339_REGEX_FLAGS = re.ASCII
|
| 12 |
+
|
| 13 |
+
RFC3339_REGEX = re.compile(r"""
|
| 14 |
+
^
|
| 15 |
+
(\d{4}) # Year
|
| 16 |
+
-
|
| 17 |
+
(0[1-9]|1[0-2]) # Month
|
| 18 |
+
-
|
| 19 |
+
(\d{2}) # Day
|
| 20 |
+
T
|
| 21 |
+
(?:[01]\d|2[0123]) # Hours
|
| 22 |
+
:
|
| 23 |
+
(?:[0-5]\d) # Minutes
|
| 24 |
+
:
|
| 25 |
+
(?:[0-5]\d) # Seconds
|
| 26 |
+
(?:\.\d+)? # Secfrac
|
| 27 |
+
(?: Z # UTC
|
| 28 |
+
| [+-](?:[01]\d|2[0123]):[0-5]\d # Offset
|
| 29 |
+
)
|
| 30 |
+
$
|
| 31 |
+
""", re.VERBOSE | RFC3339_REGEX_FLAGS)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def validate_rfc3339(date_string):
|
| 35 |
+
"""
|
| 36 |
+
Validates dates against RFC3339 datetime format
|
| 37 |
+
Leap seconds are no supported.
|
| 38 |
+
"""
|
| 39 |
+
m = RFC3339_REGEX.match(date_string)
|
| 40 |
+
if m is None:
|
| 41 |
+
return False
|
| 42 |
+
year, month, day = map(int, m.groups())
|
| 43 |
+
if not year:
|
| 44 |
+
# Year 0 is not valid a valid date
|
| 45 |
+
return False
|
| 46 |
+
(_, max_day) = calendar.monthrange(year, month)
|
| 47 |
+
if not 1 <= day <= max_day:
|
| 48 |
+
return False
|
| 49 |
+
return True
|
data/environments/eval60_europeana/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Manually curated evaluation environment."""
|
data/environments/eval60_europeana/domain/domain_tools.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
|
| 3 |
+
SUMMARY_SCHEMA = {
|
| 4 |
+
"type": "object", "additionalProperties": False,
|
| 5 |
+
"required": ["record_id", "title", "theme", "reusability", "has_media", "has_thumbnail", "has_landing_page", "timestamp_created", "timestamp_update", "completeness"],
|
| 6 |
+
"properties": {
|
| 7 |
+
"record_id": {"type": "string"},
|
| 8 |
+
"title": {"type": "string"},
|
| 9 |
+
"theme": {"type": "string"},
|
| 10 |
+
"reusability": {"type": "string", "enum": ["open", "restricted", "permission"]},
|
| 11 |
+
"has_media": {"type": "boolean"},
|
| 12 |
+
"has_thumbnail": {"type": "boolean"},
|
| 13 |
+
"has_landing_page": {"type": "boolean"},
|
| 14 |
+
"timestamp_created": {"type": "string"},
|
| 15 |
+
"timestamp_update": {"type": "string"},
|
| 16 |
+
"completeness": {"type": "integer", "minimum": 1, "maximum": 10}
|
| 17 |
+
}
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
DETAIL_SCHEMA = {
|
| 21 |
+
"type": "object", "additionalProperties": False,
|
| 22 |
+
"required": ["record_id", "title", "theme", "reusability", "has_media", "has_thumbnail", "has_landing_page", "timestamp_created", "timestamp_update", "completeness", "keywords", "provider", "object_year", "rights_statement", "media_url", "landing_page_url"],
|
| 23 |
+
"properties": {
|
| 24 |
+
"record_id": {"type": "string"},
|
| 25 |
+
"title": {"type": "string"},
|
| 26 |
+
"theme": {"type": "string"},
|
| 27 |
+
"reusability": {"type": "string", "enum": ["open", "restricted", "permission"]},
|
| 28 |
+
"has_media": {"type": "boolean"},
|
| 29 |
+
"has_thumbnail": {"type": "boolean"},
|
| 30 |
+
"has_landing_page": {"type": "boolean"},
|
| 31 |
+
"timestamp_created": {"type": "string"},
|
| 32 |
+
"timestamp_update": {"type": "string"},
|
| 33 |
+
"completeness": {"type": "integer", "minimum": 1, "maximum": 10},
|
| 34 |
+
"keywords": {"type": "array", "items": {"type": "string"}},
|
| 35 |
+
"provider": {"type": ["string", "null"]},
|
| 36 |
+
"object_year": {"type": ["integer", "null"]},
|
| 37 |
+
"rights_statement": {"type": ["string", "null"]},
|
| 38 |
+
"media_url": {"type": ["string", "null"]},
|
| 39 |
+
"landing_page_url": {"type": ["string", "null"]}
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
TOOL_SCHEMAS = [
|
| 44 |
+
{
|
| 45 |
+
"name": "search_catalog_records",
|
| 46 |
+
"description": "Search the complete local simulated cultural-heritage catalog. Query matching is case-insensitive AND matching over title and keywords; '*' matches all records. Optional theme and reusability filters use exact values, and media filters whether a resolvable full-media URL is recorded. Results are complete local search-summary resources, not full record details. An empty match is a successful result with zero items.",
|
| 47 |
+
"input_schema": {
|
| 48 |
+
"type": "object", "additionalProperties": False,
|
| 49 |
+
"required": ["query"],
|
| 50 |
+
"properties": {
|
| 51 |
+
"query": {"type": "string", "minLength": 1},
|
| 52 |
+
"theme": {"type": "string", "enum": ["archaeology", "art", "fashion", "industrial", "manuscript", "map", "migration", "music", "nature", "newspaper", "photography", "sport", "ww1"]},
|
| 53 |
+
"reusability": {"type": "string", "enum": ["open", "restricted", "permission"]},
|
| 54 |
+
"media": {"type": "boolean"},
|
| 55 |
+
"sort": {"type": "string", "enum": ["europeana_id_asc", "timestamp_update_desc", "completeness_desc"]}
|
| 56 |
+
}
|
| 57 |
+
},
|
| 58 |
+
"read_only": True,
|
| 59 |
+
"output_schema": {
|
| 60 |
+
"type": "object", "additionalProperties": False,
|
| 61 |
+
"required": ["total_results", "items"],
|
| 62 |
+
"properties": {
|
| 63 |
+
"total_results": {"type": "integer", "minimum": 0},
|
| 64 |
+
"items": {"type": "array", "items": SUMMARY_SCHEMA}
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"name": "get_catalog_record",
|
| 70 |
+
"description": "Retrieve one complete local simulated metadata record by a record ID discovered in catalog search. Detail availability is independent of the searchable summary. Provider, object year, rights statement, and URLs are synthetic record metadata.",
|
| 71 |
+
"input_schema": {
|
| 72 |
+
"type": "object", "additionalProperties": False,
|
| 73 |
+
"required": ["record_id"],
|
| 74 |
+
"properties": {"record_id": {"type": "string", "minLength": 1}}
|
| 75 |
+
},
|
| 76 |
+
"read_only": True,
|
| 77 |
+
"output_schema": DETAIL_SCHEMA
|
| 78 |
+
}
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
_SUMMARY_FIELDS = ["record_id", "title", "theme", "reusability", "has_media", "has_thumbnail", "has_landing_page", "timestamp_created", "timestamp_update", "completeness"]
|
| 82 |
+
_DETAIL_FIELDS = _SUMMARY_FIELDS + ["keywords", "provider", "object_year", "rights_statement", "media_url", "landing_page_url"]
|
| 83 |
+
|
| 84 |
+
def _error(code, message, **extra):
|
| 85 |
+
err = {"code": code, "message": message}
|
| 86 |
+
err.update(extra)
|
| 87 |
+
return {"ok": False, "error": err}
|
| 88 |
+
|
| 89 |
+
def _valid_keys(arguments, allowed, required):
|
| 90 |
+
if not isinstance(arguments, dict):
|
| 91 |
+
return False
|
| 92 |
+
if any(k not in allowed for k in arguments):
|
| 93 |
+
return False
|
| 94 |
+
return all(k in arguments for k in required)
|
| 95 |
+
|
| 96 |
+
def _summary(record):
|
| 97 |
+
return {k: deepcopy(record[k]) for k in _SUMMARY_FIELDS}
|
| 98 |
+
|
| 99 |
+
def _detail(record):
|
| 100 |
+
return {k: deepcopy(record[k]) for k in _DETAIL_FIELDS}
|
| 101 |
+
|
| 102 |
+
def call_tool(state, name, arguments):
|
| 103 |
+
if name == "search_catalog_records":
|
| 104 |
+
allowed = {"query", "theme", "reusability", "media", "sort"}
|
| 105 |
+
if not _valid_keys(arguments, allowed, {"query"}):
|
| 106 |
+
return _error("INVALID_ARGUMENT", "Arguments must be an object with query and only documented fields.")
|
| 107 |
+
query = arguments["query"]
|
| 108 |
+
if not isinstance(query, str) or not query.strip():
|
| 109 |
+
return _error("INVALID_ARGUMENT", "query must be a non-empty string.")
|
| 110 |
+
themes = {"archaeology", "art", "fashion", "industrial", "manuscript", "map", "migration", "music", "nature", "newspaper", "photography", "sport", "ww1"}
|
| 111 |
+
reuse = {"open", "restricted", "permission"}
|
| 112 |
+
sorts = {"europeana_id_asc", "timestamp_update_desc", "completeness_desc"}
|
| 113 |
+
if "theme" in arguments and (not isinstance(arguments["theme"], str) or arguments["theme"] not in themes):
|
| 114 |
+
return _error("INVALID_ARGUMENT", "theme is not a supported thematic collection.")
|
| 115 |
+
if "reusability" in arguments and (not isinstance(arguments["reusability"], str) or arguments["reusability"] not in reuse):
|
| 116 |
+
return _error("INVALID_ARGUMENT", "reusability must be open, restricted, or permission.")
|
| 117 |
+
if "media" in arguments and type(arguments["media"]) is not bool:
|
| 118 |
+
return _error("INVALID_ARGUMENT", "media must be boolean.")
|
| 119 |
+
if "sort" in arguments and (not isinstance(arguments["sort"], str) or arguments["sort"] not in sorts):
|
| 120 |
+
return _error("INVALID_ARGUMENT", "sort is not supported.")
|
| 121 |
+
terms = [] if query.strip() == "*" else query.lower().split()
|
| 122 |
+
matches = []
|
| 123 |
+
for record in state.get("records", []):
|
| 124 |
+
haystack = (record["title"] + " " + " ".join(record["keywords"])).lower()
|
| 125 |
+
if terms and not all(term in haystack for term in terms):
|
| 126 |
+
continue
|
| 127 |
+
if "theme" in arguments and record["theme"] != arguments["theme"]:
|
| 128 |
+
continue
|
| 129 |
+
if "reusability" in arguments and record["reusability"] != arguments["reusability"]:
|
| 130 |
+
continue
|
| 131 |
+
if "media" in arguments and record["has_media"] != arguments["media"]:
|
| 132 |
+
continue
|
| 133 |
+
matches.append(record)
|
| 134 |
+
sort = arguments.get("sort", "europeana_id_asc")
|
| 135 |
+
if sort == "europeana_id_asc":
|
| 136 |
+
matches.sort(key=lambda r: r["record_id"])
|
| 137 |
+
elif sort == "timestamp_update_desc":
|
| 138 |
+
matches.sort(key=lambda r: (r["timestamp_update"], r["record_id"]), reverse=True)
|
| 139 |
+
else:
|
| 140 |
+
matches.sort(key=lambda r: (-r["completeness"], r["record_id"]))
|
| 141 |
+
result = {"total_results": len(matches), "items": [_summary(r) for r in matches]}
|
| 142 |
+
return {"ok": True, "result": deepcopy(result)}
|
| 143 |
+
if name == "get_catalog_record":
|
| 144 |
+
if not _valid_keys(arguments, {"record_id"}, {"record_id"}):
|
| 145 |
+
return _error("INVALID_ARGUMENT", "Arguments must contain only record_id.")
|
| 146 |
+
record_id = arguments["record_id"]
|
| 147 |
+
if not isinstance(record_id, str) or not record_id:
|
| 148 |
+
return _error("INVALID_ARGUMENT", "record_id must be a non-empty string.")
|
| 149 |
+
record = None
|
| 150 |
+
for candidate in state.get("records", []):
|
| 151 |
+
if candidate["record_id"] == record_id:
|
| 152 |
+
record = candidate
|
| 153 |
+
break
|
| 154 |
+
if record is None:
|
| 155 |
+
return _error("NOT_FOUND", "No catalog record has that record_id.", resource="catalog_record:" + record_id)
|
| 156 |
+
if not record.get("detail_available", False):
|
| 157 |
+
return _error("UNAVAILABLE", "The catalog record detail is currently unavailable.", resource="catalog_record:" + record_id)
|
| 158 |
+
return {"ok": True, "result": deepcopy(_detail(record))}
|
| 159 |
+
return _error("UNKNOWN_TOOL", "Unknown tool name.")
|
data/environments/eval60_europeana/environment.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Official tool adapter to the exact sealed transaction runtime."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import copy
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import threading
|
| 10 |
+
from typing import Any, Callable
|
| 11 |
+
|
| 12 |
+
from fastmcp.tools import Tool
|
| 13 |
+
from fastmcp.tools.tool import ToolResult
|
| 14 |
+
from pydantic import Field
|
| 15 |
+
from hera_environment import BaseEnvironment, ToolError
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parent
|
| 18 |
+
_spec = importlib.util.spec_from_file_location(__name__ + '_runtime', ROOT/'runtime.py')
|
| 19 |
+
support = importlib.util.module_from_spec(_spec)
|
| 20 |
+
_spec.loader.exec_module(support)
|
| 21 |
+
STATE_SCHEMA = json.loads('{"type": "object"}')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _DomainTool(Tool):
|
| 25 |
+
fn: Callable[..., Any] = Field(exclude=True)
|
| 26 |
+
|
| 27 |
+
async def run(self, arguments: dict[str, Any]) -> ToolResult:
|
| 28 |
+
envelope = self.fn(**arguments)
|
| 29 |
+
return ToolResult(content=json.dumps(envelope,ensure_ascii=False,allow_nan=False),
|
| 30 |
+
structured_content=envelope,is_error=envelope['ok'] is False)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Environment(BaseEnvironment):
|
| 34 |
+
env_name = 'eval60_europeana'
|
| 35 |
+
short_name = 'Europeana'
|
| 36 |
+
always_skip_fields = set()
|
| 37 |
+
mutation_tools = set()
|
| 38 |
+
mutation_id_fields = set()
|
| 39 |
+
tool_kinds = json.loads('{"get_catalog_record": "lookup", "search_catalog_records": "lookup"}')
|
| 40 |
+
_descriptors = json.loads('[{"description": "Search the complete local simulated cultural-heritage catalog. Query matching is case-insensitive AND matching over title and keywords; \'*\' matches all records. Optional theme and reusability filters use exact values, and media filters whether a resolvable full-media URL is recorded. Results are complete local search-summary resources, not full record details. An empty match is a successful result with zero items.", "input_schema": {"additionalProperties": false, "properties": {"media": {"type": "boolean"}, "query": {"minLength": 1, "type": "string"}, "reusability": {"enum": ["open", "restricted", "permission"], "type": "string"}, "sort": {"enum": ["europeana_id_asc", "timestamp_update_desc", "completeness_desc"], "type": "string"}, "theme": {"enum": ["archaeology", "art", "fashion", "industrial", "manuscript", "map", "migration", "music", "nature", "newspaper", "photography", "sport", "ww1"], "type": "string"}}, "required": ["query"], "type": "object"}, "name": "search_catalog_records", "output_schema": {"additionalProperties": false, "properties": {"items": {"items": {"additionalProperties": false, "properties": {"completeness": {"maximum": 10, "minimum": 1, "type": "integer"}, "has_landing_page": {"type": "boolean"}, "has_media": {"type": "boolean"}, "has_thumbnail": {"type": "boolean"}, "record_id": {"type": "string"}, "reusability": {"enum": ["open", "restricted", "permission"], "type": "string"}, "theme": {"type": "string"}, "timestamp_created": {"type": "string"}, "timestamp_update": {"type": "string"}, "title": {"type": "string"}}, "required": ["record_id", "title", "theme", "reusability", "has_media", "has_thumbnail", "has_landing_page", "timestamp_created", "timestamp_update", "completeness"], "type": "object"}, "type": "array"}, "total_results": {"minimum": 0, "type": "integer"}}, "required": ["total_results", "items"], "type": "object"}, "read_only": true}, {"description": "Retrieve one complete local simulated metadata record by a record ID discovered in catalog search. Detail availability is independent of the searchable summary. Provider, object year, rights statement, and URLs are synthetic record metadata.", "input_schema": {"additionalProperties": false, "properties": {"record_id": {"minLength": 1, "type": "string"}}, "required": ["record_id"], "type": "object"}, "name": "get_catalog_record", "output_schema": {"additionalProperties": false, "properties": {"completeness": {"maximum": 10, "minimum": 1, "type": "integer"}, "has_landing_page": {"type": "boolean"}, "has_media": {"type": "boolean"}, "has_thumbnail": {"type": "boolean"}, "keywords": {"items": {"type": "string"}, "type": "array"}, "landing_page_url": {"type": ["string", "null"]}, "media_url": {"type": ["string", "null"]}, "object_year": {"type": ["integer", "null"]}, "provider": {"type": ["string", "null"]}, "record_id": {"type": "string"}, "reusability": {"enum": ["open", "restricted", "permission"], "type": "string"}, "rights_statement": {"type": ["string", "null"]}, "theme": {"type": "string"}, "timestamp_created": {"type": "string"}, "timestamp_update": {"type": "string"}, "title": {"type": "string"}}, "required": ["record_id", "title", "theme", "reusability", "has_media", "has_thumbnail", "has_landing_page", "timestamp_created", "timestamp_update", "completeness", "keywords", "provider", "object_year", "rights_statement", "media_url", "landing_page_url"], "type": "object"}, "read_only": true}]')
|
| 41 |
+
|
| 42 |
+
def _load_state(self, initial_state):
|
| 43 |
+
support.validator(STATE_SCHEMA).validate(initial_state)
|
| 44 |
+
return copy.deepcopy(initial_state)
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def get_empty_state(cls):return {}
|
| 48 |
+
|
| 49 |
+
@classmethod
|
| 50 |
+
def get_example_state(cls):return {}
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def get_state_schema(cls):return copy.deepcopy(STATE_SCHEMA)
|
| 54 |
+
|
| 55 |
+
def _register_tools(self):
|
| 56 |
+
self._transaction_lock = threading.Lock()
|
| 57 |
+
self._transport_attempts = []
|
| 58 |
+
_, actual = support.load_domain(ROOT/'domain')
|
| 59 |
+
if support.canonical(actual) != support.canonical(self._descriptors):
|
| 60 |
+
raise ValueError('Public tool descriptors differ from the sealed domain')
|
| 61 |
+
for item in self._descriptors:
|
| 62 |
+
def bind(name):
|
| 63 |
+
def call(**arguments):return self._invoke_domain(name,arguments)
|
| 64 |
+
return call
|
| 65 |
+
output = None
|
| 66 |
+
if 'output_schema' in item:
|
| 67 |
+
output={'type':'object','oneOf':[
|
| 68 |
+
{'type':'object','required':['ok','result'],'additionalProperties':False,
|
| 69 |
+
'properties':{'ok':{'const':True},'result':copy.deepcopy(item['output_schema'])}},
|
| 70 |
+
{'type':'object','required':['ok','error'],'additionalProperties':False,
|
| 71 |
+
'properties':{'ok':{'const':False},'error':{'type':'object','required':['code','message'],
|
| 72 |
+
'properties':{'code':{'type':'string','minLength':1},'message':{'type':'string'}}}}}]}
|
| 73 |
+
self.mcp.add_tool(_DomainTool(name=item['name'],description=item['description'],
|
| 74 |
+
parameters=copy.deepcopy(item['input_schema']),output_schema=output,fn=bind(item['name'])))
|
| 75 |
+
|
| 76 |
+
def _invoke_domain(self, name, arguments):
|
| 77 |
+
with self._transaction_lock:
|
| 78 |
+
before = copy.deepcopy(self.state)
|
| 79 |
+
if len(support.canonical({'tool':name,'arguments':arguments})) > 32768:
|
| 80 |
+
raise ToolError('PUBLIC_REQUEST_LIMIT')
|
| 81 |
+
request = {'action':'transition','state':before,'tool':name,'arguments':arguments}
|
| 82 |
+
try:
|
| 83 |
+
process = subprocess.run([sys.executable,'-I','-B',str(ROOT/'runtime.py'),
|
| 84 |
+
'--environment',str(ROOT/'domain'),'--max-observation-bytes','32768'],
|
| 85 |
+
input=support.canonical(request),capture_output=True,timeout=120,
|
| 86 |
+
cwd=str(ROOT),env={'PATH':'/usr/bin:/bin','PYTHONDONTWRITEBYTECODE':'1'})
|
| 87 |
+
result = support.strict(process.stdout)
|
| 88 |
+
if process.returncode or set(result) != {'state','observation','dispatched'}:
|
| 89 |
+
raise ValueError('Transaction worker failed')
|
| 90 |
+
observation = result['observation']
|
| 91 |
+
support.canonical(observation)
|
| 92 |
+
self.state = copy.deepcopy(result['state'])
|
| 93 |
+
except Exception as exc:
|
| 94 |
+
self.state = before
|
| 95 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 96 |
+
'observation':None,'dispatched':None,'error':'TRANSACTION_INFRASTRUCTURE_ERROR'})
|
| 97 |
+
raise ToolError('TRANSACTION_INFRASTRUCTURE_ERROR') from exc
|
| 98 |
+
error = None if observation['ok'] else json.dumps(observation['error'],ensure_ascii=False)
|
| 99 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 100 |
+
'observation':copy.deepcopy(observation),'dispatched':result['dispatched']})
|
| 101 |
+
# Keep the semantic event stream identical to controller.public.
|
| 102 |
+
# Rejected pre-dispatch requests remain attempts but cannot count
|
| 103 |
+
# as observed domain evidence. MCP may itself reject extra keys
|
| 104 |
+
# before this adapter; that is a transport error, not a domain event.
|
| 105 |
+
if result['dispatched']:
|
| 106 |
+
self._log_tool_call(name,copy.deepcopy(arguments),copy.deepcopy(observation),
|
| 107 |
+
success=observation['ok'],error=error)
|
| 108 |
+
return observation
|
data/environments/eval60_europeana/runtime.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small offline transaction boundary for reviewed, candidate-specific tools.
|
| 2 |
+
|
| 3 |
+
This is not a sandbox for hostile Python. The trusted controller runs this
|
| 4 |
+
worker in a fresh interpreter for every call and keeps its state output private.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
from contextlib import redirect_stderr, redirect_stdout
|
| 10 |
+
from copy import deepcopy
|
| 11 |
+
import importlib.util
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import re
|
| 16 |
+
import sys
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
from jsonschema import Draft202012Validator, FormatChecker, validators
|
| 20 |
+
|
| 21 |
+
sys.dont_write_bytecode = True
|
| 22 |
+
MAX_REQUEST_BYTES = 32768
|
| 23 |
+
MAX_INTERNAL_BYTES = 16 * 1024 * 1024
|
| 24 |
+
DEFAULT_OBSERVATION_BYTES = 32768
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def require(condition, message):
|
| 28 |
+
if not condition:
|
| 29 |
+
raise ValueError(message)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def canonical(value):
|
| 33 |
+
# Reject Python-only coercions such as integer object keys or tuples.
|
| 34 |
+
def check(item):
|
| 35 |
+
if item is None or type(item) in (str, bool, int):
|
| 36 |
+
return
|
| 37 |
+
if type(item) is float:
|
| 38 |
+
require(math.isfinite(item), 'Nonfinite JSON number')
|
| 39 |
+
return
|
| 40 |
+
if type(item) is list:
|
| 41 |
+
for child in item:
|
| 42 |
+
check(child)
|
| 43 |
+
return
|
| 44 |
+
if type(item) is dict:
|
| 45 |
+
require(all(type(key) is str for key in item), 'JSON keys must be strings')
|
| 46 |
+
for child in item.values():
|
| 47 |
+
check(child)
|
| 48 |
+
return
|
| 49 |
+
raise ValueError('Value is not JSON')
|
| 50 |
+
check(value)
|
| 51 |
+
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
| 52 |
+
sort_keys=True, separators=(',', ':')).encode('utf-8')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def strict(raw):
|
| 56 |
+
if type(raw) is bytes:
|
| 57 |
+
raw = raw.decode('utf-8', errors='strict')
|
| 58 |
+
require(type(raw) is str, 'Expected JSON bytes or text')
|
| 59 |
+
def pairs(items):
|
| 60 |
+
result = {}
|
| 61 |
+
for key, value in items:
|
| 62 |
+
require(key not in result, 'Duplicate JSON key')
|
| 63 |
+
result[key] = value
|
| 64 |
+
return result
|
| 65 |
+
value = json.loads(raw, object_pairs_hook=pairs,
|
| 66 |
+
parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Nonfinite JSON')))
|
| 67 |
+
canonical(value)
|
| 68 |
+
return value
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read(path):
|
| 72 |
+
path = Path(path)
|
| 73 |
+
require(path.is_file() and not path.is_symlink(), 'Expected a regular file')
|
| 74 |
+
return strict(path.read_bytes())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
_TYPE_CHECKER = Draft202012Validator.TYPE_CHECKER.redefine_many({
|
| 78 |
+
'integer': lambda checker, value: type(value) is int,
|
| 79 |
+
'number': lambda checker, value: type(value) is int or (type(value) is float and math.isfinite(value)),
|
| 80 |
+
})
|
| 81 |
+
StrictValidator = validators.extend(Draft202012Validator, type_checker=_TYPE_CHECKER)
|
| 82 |
+
|
| 83 |
+
# Load the pinned optional format checker by bundle-relative path. It requires
|
| 84 |
+
# no network, installed extras, sys.path changes, or historical checkout.
|
| 85 |
+
_date_path = Path(__file__).resolve().parent / 'vendor/rfc3339_validator.py'
|
| 86 |
+
_date_spec = importlib.util.spec_from_file_location('_curated_rfc3339', _date_path)
|
| 87 |
+
_date_module = importlib.util.module_from_spec(_date_spec)
|
| 88 |
+
_date_spec.loader.exec_module(_date_module)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def validator(schema):
|
| 92 |
+
require(type(schema) in (dict, bool), 'Schema must be a JSON Schema')
|
| 93 |
+
canonical(schema)
|
| 94 |
+
formats = FormatChecker()
|
| 95 |
+
@formats.checks('date-time')
|
| 96 |
+
def date_time(value):
|
| 97 |
+
return not isinstance(value, str) or _date_module.validate_rfc3339(value.upper())
|
| 98 |
+
visited = set()
|
| 99 |
+
def inspect(value):
|
| 100 |
+
if type(value) is dict:
|
| 101 |
+
if id(value) in visited:
|
| 102 |
+
return
|
| 103 |
+
visited.add(id(value))
|
| 104 |
+
require(value != {'truncated': True}, 'Truncated schemas are unsupported')
|
| 105 |
+
require('$id' not in value and '$dynamicRef' not in value,
|
| 106 |
+
'Schema resource rebasing and dynamic references are unsupported')
|
| 107 |
+
if 'format' in value:
|
| 108 |
+
require(type(value['format']) is str and value['format'] in formats.checkers,
|
| 109 |
+
'Unsupported schema format')
|
| 110 |
+
if '$ref' in value:
|
| 111 |
+
ref = value['$ref']
|
| 112 |
+
require(type(ref) is str and (ref == '#' or ref.startswith('#/')),
|
| 113 |
+
'Only local JSON Pointer schema references are allowed')
|
| 114 |
+
current = schema
|
| 115 |
+
if ref != '#':
|
| 116 |
+
for part in ref[2:].split('/'):
|
| 117 |
+
part = part.replace('~1', '/').replace('~0', '~')
|
| 118 |
+
if type(current) is list:
|
| 119 |
+
require(part.isdigit(), 'Invalid local schema reference')
|
| 120 |
+
current = current[int(part)]
|
| 121 |
+
else:
|
| 122 |
+
require(type(current) is dict and part in current,
|
| 123 |
+
'Missing local schema reference')
|
| 124 |
+
current = current[part]
|
| 125 |
+
require(type(current) in (dict, bool), 'Schema reference is not a schema')
|
| 126 |
+
# A local reference may target a schema stored outside the
|
| 127 |
+
# standard schema keywords; inspect that target as well.
|
| 128 |
+
inspect(current)
|
| 129 |
+
# Walk schema locations, not property names or literal const/enum
|
| 130 |
+
# data (a business field named "format" is not a schema keyword).
|
| 131 |
+
for keyword in ('properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'):
|
| 132 |
+
if keyword in value:
|
| 133 |
+
require(type(value[keyword]) is dict, 'Invalid schema map')
|
| 134 |
+
for child in value[keyword].values():
|
| 135 |
+
inspect(child)
|
| 136 |
+
for keyword in ('allOf', 'anyOf', 'oneOf', 'prefixItems'):
|
| 137 |
+
if keyword in value:
|
| 138 |
+
require(type(value[keyword]) is list, 'Invalid schema sequence')
|
| 139 |
+
for child in value[keyword]:
|
| 140 |
+
inspect(child)
|
| 141 |
+
for keyword in ('items', 'contains', 'additionalProperties', 'propertyNames',
|
| 142 |
+
'unevaluatedProperties', 'unevaluatedItems', 'not', 'if', 'then', 'else'):
|
| 143 |
+
if keyword in value:
|
| 144 |
+
inspect(value[keyword])
|
| 145 |
+
inspect(schema)
|
| 146 |
+
Draft202012Validator.check_schema(schema)
|
| 147 |
+
return StrictValidator(schema, format_checker=formats)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class _BoundedSink:
|
| 151 |
+
def __init__(self):
|
| 152 |
+
self.size = 0
|
| 153 |
+
|
| 154 |
+
def write(self, value):
|
| 155 |
+
self.size += len(value.encode('utf-8'))
|
| 156 |
+
require(self.size <= 16384, 'Domain diagnostic output exceeded limit')
|
| 157 |
+
return len(value)
|
| 158 |
+
|
| 159 |
+
def flush(self):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def load_domain(environment):
|
| 164 |
+
environment = Path(environment)
|
| 165 |
+
require(environment.is_dir() and not environment.is_symlink(), 'Invalid environment directory')
|
| 166 |
+
path = environment / 'domain_tools.py'
|
| 167 |
+
require(path.is_file() and not path.is_symlink(), 'Invalid domain module')
|
| 168 |
+
spec = importlib.util.spec_from_file_location('_curated_domain_tools', path)
|
| 169 |
+
domain = importlib.util.module_from_spec(spec)
|
| 170 |
+
# No sys.path injection and no reuse of an earlier module's global state.
|
| 171 |
+
sys.modules[spec.name] = domain
|
| 172 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 173 |
+
spec.loader.exec_module(domain)
|
| 174 |
+
require(callable(getattr(domain, 'call_tool', None)), 'Domain call_tool is missing')
|
| 175 |
+
descriptors = deepcopy(getattr(domain, 'TOOL_SCHEMAS', None))
|
| 176 |
+
require(type(descriptors) is list and bool(descriptors), 'Tool schemas must be a nonempty list')
|
| 177 |
+
names = set()
|
| 178 |
+
for item in descriptors:
|
| 179 |
+
require(type(item) is dict and set(item) <= {
|
| 180 |
+
'name', 'description', 'input_schema', 'output_schema', 'read_only'
|
| 181 |
+
} and {'name', 'description', 'input_schema', 'read_only'} <= set(item),
|
| 182 |
+
'Invalid tool descriptor fields')
|
| 183 |
+
name = item['name']
|
| 184 |
+
require(type(name) is str and re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,127}', name)
|
| 185 |
+
and name not in names, 'Invalid or duplicate tool name')
|
| 186 |
+
names.add(name)
|
| 187 |
+
require(type(item['description']) is str and bool(item['description'].strip()),
|
| 188 |
+
'Tool description is required')
|
| 189 |
+
require(type(item['read_only']) is bool, 'read_only must be boolean')
|
| 190 |
+
schema = item['input_schema']
|
| 191 |
+
require(type(schema) is dict and schema.get('type') == 'object'
|
| 192 |
+
and schema.get('additionalProperties') is False,
|
| 193 |
+
'Tool input must explicitly prohibit extra arguments')
|
| 194 |
+
validator(schema)
|
| 195 |
+
if 'output_schema' in item:
|
| 196 |
+
validator(item['output_schema'])
|
| 197 |
+
return domain, descriptors
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def state_validator(environment):
|
| 201 |
+
path = Path(environment) / 'state_schema.json'
|
| 202 |
+
return validator(read(path)) if path.exists() else validator({'type': 'object'})
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def error(code, message):
|
| 206 |
+
return {'ok': False, 'error': {'code': code, 'message': message}}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def transition(environment, state, name, arguments, *, max_observation_bytes=DEFAULT_OBSERVATION_BYTES):
|
| 210 |
+
"""Return private {state, observation, dispatched}; never mutate inputs."""
|
| 211 |
+
canonical(state)
|
| 212 |
+
canonical(arguments)
|
| 213 |
+
require(type(state) is dict, 'State must be an object')
|
| 214 |
+
state_check = state_validator(environment)
|
| 215 |
+
state_check.validate(state)
|
| 216 |
+
domain, descriptors = load_domain(environment)
|
| 217 |
+
by_name = {item['name']: item for item in descriptors}
|
| 218 |
+
before, working = deepcopy(state), deepcopy(state)
|
| 219 |
+
def result(observation, dispatched, next_state=None):
|
| 220 |
+
return {'state': deepcopy(before if next_state is None else next_state),
|
| 221 |
+
'observation': deepcopy(observation), 'dispatched': dispatched}
|
| 222 |
+
if type(name) is not str or name not in by_name:
|
| 223 |
+
return result(error('UNKNOWN_TOOL', 'The requested tool is not public.'), False)
|
| 224 |
+
descriptor = by_name[name]
|
| 225 |
+
try:
|
| 226 |
+
require(type(arguments) is dict, 'Arguments must be an object')
|
| 227 |
+
validator(descriptor['input_schema']).validate(arguments)
|
| 228 |
+
except Exception:
|
| 229 |
+
return result(error('INVALID_ARGUMENTS', 'Arguments do not satisfy the public schema.'), False)
|
| 230 |
+
try:
|
| 231 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 232 |
+
observation = domain.call_tool(working, name, deepcopy(arguments))
|
| 233 |
+
except Exception:
|
| 234 |
+
return result(error('DOMAIN_EXECUTION_ERROR', 'The tool could not complete.'), True)
|
| 235 |
+
try:
|
| 236 |
+
require(type(observation) is dict and type(observation.get('ok')) is bool,
|
| 237 |
+
'Invalid domain envelope')
|
| 238 |
+
if observation['ok']:
|
| 239 |
+
require(set(observation) == {'ok', 'result'}, 'Invalid success envelope')
|
| 240 |
+
else:
|
| 241 |
+
require(set(observation) == {'ok', 'error'} and type(observation['error']) is dict,
|
| 242 |
+
'Invalid error envelope')
|
| 243 |
+
require(type(observation['error'].get('code')) is str and bool(observation['error']['code'])
|
| 244 |
+
and type(observation['error'].get('message')) is str, 'Invalid domain error')
|
| 245 |
+
encoded = canonical(observation)
|
| 246 |
+
require(type(max_observation_bytes) is int and 512 <= max_observation_bytes <= 1048576,
|
| 247 |
+
'Invalid observation limit')
|
| 248 |
+
if len(encoded) > max_observation_bytes:
|
| 249 |
+
return result(error('OBSERVATION_LIMIT', 'Tool result exceeds the public response limit.'), True)
|
| 250 |
+
if descriptor['read_only'] and canonical(working) != canonical(before):
|
| 251 |
+
return result(error('READ_ONLY_VIOLATION', 'A read-only tool attempted to change state.'), True)
|
| 252 |
+
if not observation['ok']:
|
| 253 |
+
return result(observation, True)
|
| 254 |
+
if 'output_schema' in descriptor:
|
| 255 |
+
validator(descriptor['output_schema']).validate(observation['result'])
|
| 256 |
+
state_check.validate(working)
|
| 257 |
+
canonical(working)
|
| 258 |
+
except Exception:
|
| 259 |
+
return result(error('INVALID_TOOL_RESULT', 'Tool output or state violates its contract.'), True)
|
| 260 |
+
return result(observation, True, working)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def main(argv=None):
|
| 264 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 265 |
+
parser.add_argument('--environment', type=Path, required=True)
|
| 266 |
+
parser.add_argument('--max-observation-bytes', type=int, default=DEFAULT_OBSERVATION_BYTES)
|
| 267 |
+
args = parser.parse_args(argv)
|
| 268 |
+
try:
|
| 269 |
+
raw = sys.stdin.buffer.read(MAX_INTERNAL_BYTES + 1)
|
| 270 |
+
require(len(raw) <= MAX_INTERNAL_BYTES, 'Internal request exceeds limit')
|
| 271 |
+
request = strict(raw)
|
| 272 |
+
with (patch('socket.socket', side_effect=RuntimeError('Offline worker forbids network')),
|
| 273 |
+
patch('socket.create_connection', side_effect=RuntimeError('Offline worker forbids network'))):
|
| 274 |
+
if request == {'action': 'describe'}:
|
| 275 |
+
_, descriptors = load_domain(args.environment)
|
| 276 |
+
state_validator(args.environment).validate(read(args.environment / 'state.json'))
|
| 277 |
+
value = {'tools': descriptors}
|
| 278 |
+
else:
|
| 279 |
+
require(type(request) is dict and set(request) == {'action', 'state', 'tool', 'arguments'}
|
| 280 |
+
and request['action'] == 'transition', 'Invalid internal request')
|
| 281 |
+
value = transition(args.environment, request['state'], request['tool'], request['arguments'],
|
| 282 |
+
max_observation_bytes=args.max_observation_bytes)
|
| 283 |
+
sys.stdout.buffer.write(canonical(value) + b'\n')
|
| 284 |
+
return 0
|
| 285 |
+
except Exception:
|
| 286 |
+
sys.stdout.buffer.write(canonical({'worker_error': 'RUNTIME_VALIDATION_FAILED'}) + b'\n')
|
| 287 |
+
return 1
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == '__main__':
|
| 291 |
+
raise SystemExit(main())
|
data/environments/eval60_europeana/vendor/rfc3339_validator.LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2019, Nicolas Aimetti
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
data/environments/eval60_europeana/vendor/rfc3339_validator.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Vendored 0.1.4; Python 3-only compatibility patch, see provenance.json.
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
__author__ = """Nicolas Aimetti"""
|
| 5 |
+
__email__ = 'naimetti@yahoo.com.ar'
|
| 6 |
+
__version__ = '0.1.4'
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
import calendar
|
| 10 |
+
|
| 11 |
+
RFC3339_REGEX_FLAGS = re.ASCII
|
| 12 |
+
|
| 13 |
+
RFC3339_REGEX = re.compile(r"""
|
| 14 |
+
^
|
| 15 |
+
(\d{4}) # Year
|
| 16 |
+
-
|
| 17 |
+
(0[1-9]|1[0-2]) # Month
|
| 18 |
+
-
|
| 19 |
+
(\d{2}) # Day
|
| 20 |
+
T
|
| 21 |
+
(?:[01]\d|2[0123]) # Hours
|
| 22 |
+
:
|
| 23 |
+
(?:[0-5]\d) # Minutes
|
| 24 |
+
:
|
| 25 |
+
(?:[0-5]\d) # Seconds
|
| 26 |
+
(?:\.\d+)? # Secfrac
|
| 27 |
+
(?: Z # UTC
|
| 28 |
+
| [+-](?:[01]\d|2[0123]):[0-5]\d # Offset
|
| 29 |
+
)
|
| 30 |
+
$
|
| 31 |
+
""", re.VERBOSE | RFC3339_REGEX_FLAGS)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def validate_rfc3339(date_string):
|
| 35 |
+
"""
|
| 36 |
+
Validates dates against RFC3339 datetime format
|
| 37 |
+
Leap seconds are no supported.
|
| 38 |
+
"""
|
| 39 |
+
m = RFC3339_REGEX.match(date_string)
|
| 40 |
+
if m is None:
|
| 41 |
+
return False
|
| 42 |
+
year, month, day = map(int, m.groups())
|
| 43 |
+
if not year:
|
| 44 |
+
# Year 0 is not valid a valid date
|
| 45 |
+
return False
|
| 46 |
+
(_, max_day) = calendar.monthrange(year, month)
|
| 47 |
+
if not 1 <= day <= max_day:
|
| 48 |
+
return False
|
| 49 |
+
return True
|
data/environments/eval60_gbif/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Manually curated evaluation environment."""
|
data/environments/eval60_gbif/domain/domain_tools.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
from datetime import date
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def _obj_schema(properties, required):
|
| 7 |
+
return {"type": "object", "properties": properties, "required": required, "additionalProperties": False}
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
OCCURRENCE_SCHEMA = _obj_schema({
|
| 11 |
+
"gbifId": {"type": "integer"}, "acceptedTaxonKey": {"type": "integer"},
|
| 12 |
+
"scientificName": {"type": "string"}, "country": {"type": "string"},
|
| 13 |
+
"eventDate": {"type": "string", "format": "date"},
|
| 14 |
+
"occurrenceId": {"type": ["string", "null"]}, "datasetKey": {"type": "string"},
|
| 15 |
+
"lastInterpreted": {"type": "string"},
|
| 16 |
+
"decimalLatitude": {"type": ["number", "null"]},
|
| 17 |
+
"decimalLongitude": {"type": ["number", "null"]},
|
| 18 |
+
"coordinateUncertaintyInMeters": {"type": ["number", "null"]},
|
| 19 |
+
"occurrenceStatus": {"type": "string", "enum": ["PRESENT", "ABSENT"]},
|
| 20 |
+
"hasGeospatialIssue": {"type": "boolean"}
|
| 21 |
+
}, ["gbifId", "acceptedTaxonKey", "scientificName", "country", "eventDate", "occurrenceId", "datasetKey", "lastInterpreted", "decimalLatitude", "decimalLongitude", "coordinateUncertaintyInMeters", "occurrenceStatus", "hasGeospatialIssue"])
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
TOOL_SCHEMAS = [
|
| 25 |
+
{
|
| 26 |
+
"name": "search_occurrences",
|
| 27 |
+
"description": "Search the local synthetic occurrence index. Filters are exact except the inclusive event-date bounds. Results are complete local occurrence objects; an empty result is returned as count 0.",
|
| 28 |
+
"input_schema": _obj_schema({
|
| 29 |
+
"acceptedTaxonKey": {"type": "integer"},
|
| 30 |
+
"country": {"type": "string", "pattern": "^[A-Z]{2}$"},
|
| 31 |
+
"eventDateFrom": {"type": "string", "format": "date", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},
|
| 32 |
+
"eventDateTo": {"type": "string", "format": "date", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},
|
| 33 |
+
"occurrenceStatus": {"type": "string", "enum": ["PRESENT", "ABSENT"]},
|
| 34 |
+
"datasetKey": {"type": "string"}
|
| 35 |
+
}, []),
|
| 36 |
+
"read_only": True,
|
| 37 |
+
"output_schema": _obj_schema({
|
| 38 |
+
"count": {"type": "integer"},
|
| 39 |
+
"results": {"type": "array", "items": OCCURRENCE_SCHEMA}
|
| 40 |
+
}, ["count", "results"])
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"name": "get_occurrence",
|
| 44 |
+
"description": "Retrieve one complete local synthetic occurrence object by its unique GBIF-style numeric key.",
|
| 45 |
+
"input_schema": _obj_schema({"gbifId": {"type": "integer"}}, ["gbifId"]),
|
| 46 |
+
"read_only": True,
|
| 47 |
+
"output_schema": OCCURRENCE_SCHEMA
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"name": "get_dataset",
|
| 51 |
+
"description": "Retrieve one complete local synthetic dataset record by dataset UUID. Dataset evidence can be independently unavailable; in that case this returns UNAVAILABLE with the requested resource identifier.",
|
| 52 |
+
"input_schema": _obj_schema({"datasetKey": {"type": "string"}}, ["datasetKey"]),
|
| 53 |
+
"read_only": True,
|
| 54 |
+
"output_schema": _obj_schema({
|
| 55 |
+
"datasetKey": {"type": "string"},
|
| 56 |
+
"title": {"type": "string"},
|
| 57 |
+
"license": {"type": "string"},
|
| 58 |
+
"publishingCountry": {"type": "string"}
|
| 59 |
+
}, ["datasetKey", "title", "license", "publishingCountry"])
|
| 60 |
+
}
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _error(code, message, **extra):
|
| 65 |
+
e = {"code": code, "message": message}
|
| 66 |
+
e.update(extra)
|
| 67 |
+
return {"ok": False, "error": e}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def call_tool(state, name, arguments):
|
| 71 |
+
if not isinstance(arguments, dict):
|
| 72 |
+
return _error("INVALID_ARGUMENT", "arguments must be an object")
|
| 73 |
+
if name == "search_occurrences":
|
| 74 |
+
allowed = {"acceptedTaxonKey", "country", "eventDateFrom", "eventDateTo", "occurrenceStatus", "datasetKey"}
|
| 75 |
+
unknown = sorted(set(arguments) - allowed)
|
| 76 |
+
if unknown:
|
| 77 |
+
return _error("INVALID_ARGUMENT", "unknown parameter", parameters=unknown)
|
| 78 |
+
if "acceptedTaxonKey" in arguments and (isinstance(arguments["acceptedTaxonKey"], bool) or not isinstance(arguments["acceptedTaxonKey"], int)):
|
| 79 |
+
return _error("INVALID_ARGUMENT", "acceptedTaxonKey must be an integer")
|
| 80 |
+
for k in ("country", "eventDateFrom", "eventDateTo", "occurrenceStatus", "datasetKey"):
|
| 81 |
+
if k in arguments and not isinstance(arguments[k], str):
|
| 82 |
+
return _error("INVALID_ARGUMENT", k + " must be a string")
|
| 83 |
+
if "country" in arguments and re.fullmatch(r"[A-Z]{2}", arguments["country"]) is None:
|
| 84 |
+
return _error("INVALID_ARGUMENT", "country must be a two-letter uppercase code")
|
| 85 |
+
if "occurrenceStatus" in arguments and arguments["occurrenceStatus"] not in ("PRESENT", "ABSENT"):
|
| 86 |
+
return _error("INVALID_ARGUMENT", "unsupported occurrenceStatus")
|
| 87 |
+
for key in ("eventDateFrom", "eventDateTo"):
|
| 88 |
+
if key in arguments:
|
| 89 |
+
try:
|
| 90 |
+
value = date.fromisoformat(arguments[key])
|
| 91 |
+
if value.isoformat() != arguments[key]:
|
| 92 |
+
return _error("INVALID_ARGUMENT", key + " must be a YYYY-MM-DD calendar date")
|
| 93 |
+
except ValueError:
|
| 94 |
+
return _error("INVALID_ARGUMENT", key + " must be a YYYY-MM-DD calendar date")
|
| 95 |
+
if arguments.get("eventDateFrom") and arguments.get("eventDateTo") and arguments["eventDateFrom"] > arguments["eventDateTo"]:
|
| 96 |
+
return _error("INVALID_RANGE", "eventDateFrom is after eventDateTo")
|
| 97 |
+
out = []
|
| 98 |
+
for rec in state.get("occurrences", []):
|
| 99 |
+
if "acceptedTaxonKey" in arguments and rec.get("acceptedTaxonKey") != arguments["acceptedTaxonKey"]:
|
| 100 |
+
continue
|
| 101 |
+
if "country" in arguments and rec.get("country") != arguments["country"]:
|
| 102 |
+
continue
|
| 103 |
+
if "eventDateFrom" in arguments and rec.get("eventDate", "") < arguments["eventDateFrom"]:
|
| 104 |
+
continue
|
| 105 |
+
if "eventDateTo" in arguments and rec.get("eventDate", "") > arguments["eventDateTo"]:
|
| 106 |
+
continue
|
| 107 |
+
if "occurrenceStatus" in arguments and rec.get("occurrenceStatus") != arguments["occurrenceStatus"]:
|
| 108 |
+
continue
|
| 109 |
+
if "datasetKey" in arguments and rec.get("datasetKey") != arguments["datasetKey"]:
|
| 110 |
+
continue
|
| 111 |
+
out.append(deepcopy(rec))
|
| 112 |
+
out.sort(key=lambda x: x["gbifId"])
|
| 113 |
+
return {"ok": True, "result": {"count": len(out), "results": out}}
|
| 114 |
+
if name == "get_occurrence":
|
| 115 |
+
if set(arguments) != {"gbifId"} or isinstance(arguments.get("gbifId"), bool) or not isinstance(arguments.get("gbifId"), int):
|
| 116 |
+
return _error("INVALID_ARGUMENT", "gbifId integer is required")
|
| 117 |
+
for rec in state.get("occurrences", []):
|
| 118 |
+
if rec.get("gbifId") == arguments["gbifId"]:
|
| 119 |
+
return {"ok": True, "result": deepcopy(rec)}
|
| 120 |
+
return _error("NOT_FOUND", "occurrence was not found", resource="occurrence:" + str(arguments["gbifId"]))
|
| 121 |
+
if name == "get_dataset":
|
| 122 |
+
if set(arguments) != {"datasetKey"} or not isinstance(arguments.get("datasetKey"), str):
|
| 123 |
+
return _error("INVALID_ARGUMENT", "datasetKey string is required")
|
| 124 |
+
key = arguments["datasetKey"]
|
| 125 |
+
for ds in state.get("datasets", []):
|
| 126 |
+
if ds.get("datasetKey") == key:
|
| 127 |
+
if not ds.get("available", False):
|
| 128 |
+
return _error("UNAVAILABLE", "dataset evidence is unavailable", resource="dataset:" + key)
|
| 129 |
+
return {"ok": True, "result": deepcopy({k: ds[k] for k in ("datasetKey", "title", "license", "publishingCountry")})}
|
| 130 |
+
return _error("NOT_FOUND", "dataset was not found", resource="dataset:" + key)
|
| 131 |
+
return _error("UNKNOWN_TOOL", "unknown tool name", tool=name)
|
data/environments/eval60_gbif/environment.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Official tool adapter to the exact sealed transaction runtime."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import copy
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import threading
|
| 10 |
+
from typing import Any, Callable
|
| 11 |
+
|
| 12 |
+
from fastmcp.tools import Tool
|
| 13 |
+
from fastmcp.tools.tool import ToolResult
|
| 14 |
+
from pydantic import Field
|
| 15 |
+
from hera_environment import BaseEnvironment, ToolError
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parent
|
| 18 |
+
_spec = importlib.util.spec_from_file_location(__name__ + '_runtime', ROOT/'runtime.py')
|
| 19 |
+
support = importlib.util.module_from_spec(_spec)
|
| 20 |
+
_spec.loader.exec_module(support)
|
| 21 |
+
STATE_SCHEMA = json.loads('{"type": "object"}')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _DomainTool(Tool):
|
| 25 |
+
fn: Callable[..., Any] = Field(exclude=True)
|
| 26 |
+
|
| 27 |
+
async def run(self, arguments: dict[str, Any]) -> ToolResult:
|
| 28 |
+
envelope = self.fn(**arguments)
|
| 29 |
+
return ToolResult(content=json.dumps(envelope,ensure_ascii=False,allow_nan=False),
|
| 30 |
+
structured_content=envelope,is_error=envelope['ok'] is False)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Environment(BaseEnvironment):
|
| 34 |
+
env_name = 'eval60_gbif'
|
| 35 |
+
short_name = 'GBIF'
|
| 36 |
+
always_skip_fields = set()
|
| 37 |
+
mutation_tools = set()
|
| 38 |
+
mutation_id_fields = set()
|
| 39 |
+
tool_kinds = json.loads('{"get_dataset": "lookup", "get_occurrence": "lookup", "search_occurrences": "lookup"}')
|
| 40 |
+
_descriptors = json.loads('[{"description": "Search the local synthetic occurrence index. Filters are exact except the inclusive event-date bounds. Results are complete local occurrence objects; an empty result is returned as count 0.", "input_schema": {"additionalProperties": false, "properties": {"acceptedTaxonKey": {"type": "integer"}, "country": {"pattern": "^[A-Z]{2}$", "type": "string"}, "datasetKey": {"type": "string"}, "eventDateFrom": {"format": "date", "pattern": "^\\\\d{4}-\\\\d{2}-\\\\d{2}$", "type": "string"}, "eventDateTo": {"format": "date", "pattern": "^\\\\d{4}-\\\\d{2}-\\\\d{2}$", "type": "string"}, "occurrenceStatus": {"enum": ["PRESENT", "ABSENT"], "type": "string"}}, "required": [], "type": "object"}, "name": "search_occurrences", "output_schema": {"additionalProperties": false, "properties": {"count": {"type": "integer"}, "results": {"items": {"additionalProperties": false, "properties": {"acceptedTaxonKey": {"type": "integer"}, "coordinateUncertaintyInMeters": {"type": ["number", "null"]}, "country": {"type": "string"}, "datasetKey": {"type": "string"}, "decimalLatitude": {"type": ["number", "null"]}, "decimalLongitude": {"type": ["number", "null"]}, "eventDate": {"format": "date", "type": "string"}, "gbifId": {"type": "integer"}, "hasGeospatialIssue": {"type": "boolean"}, "lastInterpreted": {"type": "string"}, "occurrenceId": {"type": ["string", "null"]}, "occurrenceStatus": {"enum": ["PRESENT", "ABSENT"], "type": "string"}, "scientificName": {"type": "string"}}, "required": ["gbifId", "acceptedTaxonKey", "scientificName", "country", "eventDate", "occurrenceId", "datasetKey", "lastInterpreted", "decimalLatitude", "decimalLongitude", "coordinateUncertaintyInMeters", "occurrenceStatus", "hasGeospatialIssue"], "type": "object"}, "type": "array"}}, "required": ["count", "results"], "type": "object"}, "read_only": true}, {"description": "Retrieve one complete local synthetic occurrence object by its unique GBIF-style numeric key.", "input_schema": {"additionalProperties": false, "properties": {"gbifId": {"type": "integer"}}, "required": ["gbifId"], "type": "object"}, "name": "get_occurrence", "output_schema": {"additionalProperties": false, "properties": {"acceptedTaxonKey": {"type": "integer"}, "coordinateUncertaintyInMeters": {"type": ["number", "null"]}, "country": {"type": "string"}, "datasetKey": {"type": "string"}, "decimalLatitude": {"type": ["number", "null"]}, "decimalLongitude": {"type": ["number", "null"]}, "eventDate": {"format": "date", "type": "string"}, "gbifId": {"type": "integer"}, "hasGeospatialIssue": {"type": "boolean"}, "lastInterpreted": {"type": "string"}, "occurrenceId": {"type": ["string", "null"]}, "occurrenceStatus": {"enum": ["PRESENT", "ABSENT"], "type": "string"}, "scientificName": {"type": "string"}}, "required": ["gbifId", "acceptedTaxonKey", "scientificName", "country", "eventDate", "occurrenceId", "datasetKey", "lastInterpreted", "decimalLatitude", "decimalLongitude", "coordinateUncertaintyInMeters", "occurrenceStatus", "hasGeospatialIssue"], "type": "object"}, "read_only": true}, {"description": "Retrieve one complete local synthetic dataset record by dataset UUID. Dataset evidence can be independently unavailable; in that case this returns UNAVAILABLE with the requested resource identifier.", "input_schema": {"additionalProperties": false, "properties": {"datasetKey": {"type": "string"}}, "required": ["datasetKey"], "type": "object"}, "name": "get_dataset", "output_schema": {"additionalProperties": false, "properties": {"datasetKey": {"type": "string"}, "license": {"type": "string"}, "publishingCountry": {"type": "string"}, "title": {"type": "string"}}, "required": ["datasetKey", "title", "license", "publishingCountry"], "type": "object"}, "read_only": true}]')
|
| 41 |
+
|
| 42 |
+
def _load_state(self, initial_state):
|
| 43 |
+
support.validator(STATE_SCHEMA).validate(initial_state)
|
| 44 |
+
return copy.deepcopy(initial_state)
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def get_empty_state(cls):return {}
|
| 48 |
+
|
| 49 |
+
@classmethod
|
| 50 |
+
def get_example_state(cls):return {}
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def get_state_schema(cls):return copy.deepcopy(STATE_SCHEMA)
|
| 54 |
+
|
| 55 |
+
def _register_tools(self):
|
| 56 |
+
self._transaction_lock = threading.Lock()
|
| 57 |
+
self._transport_attempts = []
|
| 58 |
+
_, actual = support.load_domain(ROOT/'domain')
|
| 59 |
+
if support.canonical(actual) != support.canonical(self._descriptors):
|
| 60 |
+
raise ValueError('Public tool descriptors differ from the sealed domain')
|
| 61 |
+
for item in self._descriptors:
|
| 62 |
+
def bind(name):
|
| 63 |
+
def call(**arguments):return self._invoke_domain(name,arguments)
|
| 64 |
+
return call
|
| 65 |
+
output = None
|
| 66 |
+
if 'output_schema' in item:
|
| 67 |
+
output={'type':'object','oneOf':[
|
| 68 |
+
{'type':'object','required':['ok','result'],'additionalProperties':False,
|
| 69 |
+
'properties':{'ok':{'const':True},'result':copy.deepcopy(item['output_schema'])}},
|
| 70 |
+
{'type':'object','required':['ok','error'],'additionalProperties':False,
|
| 71 |
+
'properties':{'ok':{'const':False},'error':{'type':'object','required':['code','message'],
|
| 72 |
+
'properties':{'code':{'type':'string','minLength':1},'message':{'type':'string'}}}}}]}
|
| 73 |
+
self.mcp.add_tool(_DomainTool(name=item['name'],description=item['description'],
|
| 74 |
+
parameters=copy.deepcopy(item['input_schema']),output_schema=output,fn=bind(item['name'])))
|
| 75 |
+
|
| 76 |
+
def _invoke_domain(self, name, arguments):
|
| 77 |
+
with self._transaction_lock:
|
| 78 |
+
before = copy.deepcopy(self.state)
|
| 79 |
+
if len(support.canonical({'tool':name,'arguments':arguments})) > 32768:
|
| 80 |
+
raise ToolError('PUBLIC_REQUEST_LIMIT')
|
| 81 |
+
request = {'action':'transition','state':before,'tool':name,'arguments':arguments}
|
| 82 |
+
try:
|
| 83 |
+
process = subprocess.run([sys.executable,'-I','-B',str(ROOT/'runtime.py'),
|
| 84 |
+
'--environment',str(ROOT/'domain'),'--max-observation-bytes','32768'],
|
| 85 |
+
input=support.canonical(request),capture_output=True,timeout=120,
|
| 86 |
+
cwd=str(ROOT),env={'PATH':'/usr/bin:/bin','PYTHONDONTWRITEBYTECODE':'1'})
|
| 87 |
+
result = support.strict(process.stdout)
|
| 88 |
+
if process.returncode or set(result) != {'state','observation','dispatched'}:
|
| 89 |
+
raise ValueError('Transaction worker failed')
|
| 90 |
+
observation = result['observation']
|
| 91 |
+
support.canonical(observation)
|
| 92 |
+
self.state = copy.deepcopy(result['state'])
|
| 93 |
+
except Exception as exc:
|
| 94 |
+
self.state = before
|
| 95 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 96 |
+
'observation':None,'dispatched':None,'error':'TRANSACTION_INFRASTRUCTURE_ERROR'})
|
| 97 |
+
raise ToolError('TRANSACTION_INFRASTRUCTURE_ERROR') from exc
|
| 98 |
+
error = None if observation['ok'] else json.dumps(observation['error'],ensure_ascii=False)
|
| 99 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 100 |
+
'observation':copy.deepcopy(observation),'dispatched':result['dispatched']})
|
| 101 |
+
# Keep the semantic event stream identical to controller.public.
|
| 102 |
+
# Rejected pre-dispatch requests remain attempts but cannot count
|
| 103 |
+
# as observed domain evidence. MCP may itself reject extra keys
|
| 104 |
+
# before this adapter; that is a transport error, not a domain event.
|
| 105 |
+
if result['dispatched']:
|
| 106 |
+
self._log_tool_call(name,copy.deepcopy(arguments),copy.deepcopy(observation),
|
| 107 |
+
success=observation['ok'],error=error)
|
| 108 |
+
return observation
|
data/environments/eval60_gbif/runtime.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small offline transaction boundary for reviewed, candidate-specific tools.
|
| 2 |
+
|
| 3 |
+
This is not a sandbox for hostile Python. The trusted controller runs this
|
| 4 |
+
worker in a fresh interpreter for every call and keeps its state output private.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
from contextlib import redirect_stderr, redirect_stdout
|
| 10 |
+
from copy import deepcopy
|
| 11 |
+
import importlib.util
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import re
|
| 16 |
+
import sys
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
from jsonschema import Draft202012Validator, FormatChecker, validators
|
| 20 |
+
|
| 21 |
+
sys.dont_write_bytecode = True
|
| 22 |
+
MAX_REQUEST_BYTES = 32768
|
| 23 |
+
MAX_INTERNAL_BYTES = 16 * 1024 * 1024
|
| 24 |
+
DEFAULT_OBSERVATION_BYTES = 32768
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def require(condition, message):
|
| 28 |
+
if not condition:
|
| 29 |
+
raise ValueError(message)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def canonical(value):
|
| 33 |
+
# Reject Python-only coercions such as integer object keys or tuples.
|
| 34 |
+
def check(item):
|
| 35 |
+
if item is None or type(item) in (str, bool, int):
|
| 36 |
+
return
|
| 37 |
+
if type(item) is float:
|
| 38 |
+
require(math.isfinite(item), 'Nonfinite JSON number')
|
| 39 |
+
return
|
| 40 |
+
if type(item) is list:
|
| 41 |
+
for child in item:
|
| 42 |
+
check(child)
|
| 43 |
+
return
|
| 44 |
+
if type(item) is dict:
|
| 45 |
+
require(all(type(key) is str for key in item), 'JSON keys must be strings')
|
| 46 |
+
for child in item.values():
|
| 47 |
+
check(child)
|
| 48 |
+
return
|
| 49 |
+
raise ValueError('Value is not JSON')
|
| 50 |
+
check(value)
|
| 51 |
+
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
| 52 |
+
sort_keys=True, separators=(',', ':')).encode('utf-8')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def strict(raw):
|
| 56 |
+
if type(raw) is bytes:
|
| 57 |
+
raw = raw.decode('utf-8', errors='strict')
|
| 58 |
+
require(type(raw) is str, 'Expected JSON bytes or text')
|
| 59 |
+
def pairs(items):
|
| 60 |
+
result = {}
|
| 61 |
+
for key, value in items:
|
| 62 |
+
require(key not in result, 'Duplicate JSON key')
|
| 63 |
+
result[key] = value
|
| 64 |
+
return result
|
| 65 |
+
value = json.loads(raw, object_pairs_hook=pairs,
|
| 66 |
+
parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Nonfinite JSON')))
|
| 67 |
+
canonical(value)
|
| 68 |
+
return value
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read(path):
|
| 72 |
+
path = Path(path)
|
| 73 |
+
require(path.is_file() and not path.is_symlink(), 'Expected a regular file')
|
| 74 |
+
return strict(path.read_bytes())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
_TYPE_CHECKER = Draft202012Validator.TYPE_CHECKER.redefine_many({
|
| 78 |
+
'integer': lambda checker, value: type(value) is int,
|
| 79 |
+
'number': lambda checker, value: type(value) is int or (type(value) is float and math.isfinite(value)),
|
| 80 |
+
})
|
| 81 |
+
StrictValidator = validators.extend(Draft202012Validator, type_checker=_TYPE_CHECKER)
|
| 82 |
+
|
| 83 |
+
# Load the pinned optional format checker by bundle-relative path. It requires
|
| 84 |
+
# no network, installed extras, sys.path changes, or historical checkout.
|
| 85 |
+
_date_path = Path(__file__).resolve().parent / 'vendor/rfc3339_validator.py'
|
| 86 |
+
_date_spec = importlib.util.spec_from_file_location('_curated_rfc3339', _date_path)
|
| 87 |
+
_date_module = importlib.util.module_from_spec(_date_spec)
|
| 88 |
+
_date_spec.loader.exec_module(_date_module)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def validator(schema):
|
| 92 |
+
require(type(schema) in (dict, bool), 'Schema must be a JSON Schema')
|
| 93 |
+
canonical(schema)
|
| 94 |
+
formats = FormatChecker()
|
| 95 |
+
@formats.checks('date-time')
|
| 96 |
+
def date_time(value):
|
| 97 |
+
return not isinstance(value, str) or _date_module.validate_rfc3339(value.upper())
|
| 98 |
+
visited = set()
|
| 99 |
+
def inspect(value):
|
| 100 |
+
if type(value) is dict:
|
| 101 |
+
if id(value) in visited:
|
| 102 |
+
return
|
| 103 |
+
visited.add(id(value))
|
| 104 |
+
require(value != {'truncated': True}, 'Truncated schemas are unsupported')
|
| 105 |
+
require('$id' not in value and '$dynamicRef' not in value,
|
| 106 |
+
'Schema resource rebasing and dynamic references are unsupported')
|
| 107 |
+
if 'format' in value:
|
| 108 |
+
require(type(value['format']) is str and value['format'] in formats.checkers,
|
| 109 |
+
'Unsupported schema format')
|
| 110 |
+
if '$ref' in value:
|
| 111 |
+
ref = value['$ref']
|
| 112 |
+
require(type(ref) is str and (ref == '#' or ref.startswith('#/')),
|
| 113 |
+
'Only local JSON Pointer schema references are allowed')
|
| 114 |
+
current = schema
|
| 115 |
+
if ref != '#':
|
| 116 |
+
for part in ref[2:].split('/'):
|
| 117 |
+
part = part.replace('~1', '/').replace('~0', '~')
|
| 118 |
+
if type(current) is list:
|
| 119 |
+
require(part.isdigit(), 'Invalid local schema reference')
|
| 120 |
+
current = current[int(part)]
|
| 121 |
+
else:
|
| 122 |
+
require(type(current) is dict and part in current,
|
| 123 |
+
'Missing local schema reference')
|
| 124 |
+
current = current[part]
|
| 125 |
+
require(type(current) in (dict, bool), 'Schema reference is not a schema')
|
| 126 |
+
# A local reference may target a schema stored outside the
|
| 127 |
+
# standard schema keywords; inspect that target as well.
|
| 128 |
+
inspect(current)
|
| 129 |
+
# Walk schema locations, not property names or literal const/enum
|
| 130 |
+
# data (a business field named "format" is not a schema keyword).
|
| 131 |
+
for keyword in ('properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'):
|
| 132 |
+
if keyword in value:
|
| 133 |
+
require(type(value[keyword]) is dict, 'Invalid schema map')
|
| 134 |
+
for child in value[keyword].values():
|
| 135 |
+
inspect(child)
|
| 136 |
+
for keyword in ('allOf', 'anyOf', 'oneOf', 'prefixItems'):
|
| 137 |
+
if keyword in value:
|
| 138 |
+
require(type(value[keyword]) is list, 'Invalid schema sequence')
|
| 139 |
+
for child in value[keyword]:
|
| 140 |
+
inspect(child)
|
| 141 |
+
for keyword in ('items', 'contains', 'additionalProperties', 'propertyNames',
|
| 142 |
+
'unevaluatedProperties', 'unevaluatedItems', 'not', 'if', 'then', 'else'):
|
| 143 |
+
if keyword in value:
|
| 144 |
+
inspect(value[keyword])
|
| 145 |
+
inspect(schema)
|
| 146 |
+
Draft202012Validator.check_schema(schema)
|
| 147 |
+
return StrictValidator(schema, format_checker=formats)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class _BoundedSink:
|
| 151 |
+
def __init__(self):
|
| 152 |
+
self.size = 0
|
| 153 |
+
|
| 154 |
+
def write(self, value):
|
| 155 |
+
self.size += len(value.encode('utf-8'))
|
| 156 |
+
require(self.size <= 16384, 'Domain diagnostic output exceeded limit')
|
| 157 |
+
return len(value)
|
| 158 |
+
|
| 159 |
+
def flush(self):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def load_domain(environment):
|
| 164 |
+
environment = Path(environment)
|
| 165 |
+
require(environment.is_dir() and not environment.is_symlink(), 'Invalid environment directory')
|
| 166 |
+
path = environment / 'domain_tools.py'
|
| 167 |
+
require(path.is_file() and not path.is_symlink(), 'Invalid domain module')
|
| 168 |
+
spec = importlib.util.spec_from_file_location('_curated_domain_tools', path)
|
| 169 |
+
domain = importlib.util.module_from_spec(spec)
|
| 170 |
+
# No sys.path injection and no reuse of an earlier module's global state.
|
| 171 |
+
sys.modules[spec.name] = domain
|
| 172 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 173 |
+
spec.loader.exec_module(domain)
|
| 174 |
+
require(callable(getattr(domain, 'call_tool', None)), 'Domain call_tool is missing')
|
| 175 |
+
descriptors = deepcopy(getattr(domain, 'TOOL_SCHEMAS', None))
|
| 176 |
+
require(type(descriptors) is list and bool(descriptors), 'Tool schemas must be a nonempty list')
|
| 177 |
+
names = set()
|
| 178 |
+
for item in descriptors:
|
| 179 |
+
require(type(item) is dict and set(item) <= {
|
| 180 |
+
'name', 'description', 'input_schema', 'output_schema', 'read_only'
|
| 181 |
+
} and {'name', 'description', 'input_schema', 'read_only'} <= set(item),
|
| 182 |
+
'Invalid tool descriptor fields')
|
| 183 |
+
name = item['name']
|
| 184 |
+
require(type(name) is str and re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,127}', name)
|
| 185 |
+
and name not in names, 'Invalid or duplicate tool name')
|
| 186 |
+
names.add(name)
|
| 187 |
+
require(type(item['description']) is str and bool(item['description'].strip()),
|
| 188 |
+
'Tool description is required')
|
| 189 |
+
require(type(item['read_only']) is bool, 'read_only must be boolean')
|
| 190 |
+
schema = item['input_schema']
|
| 191 |
+
require(type(schema) is dict and schema.get('type') == 'object'
|
| 192 |
+
and schema.get('additionalProperties') is False,
|
| 193 |
+
'Tool input must explicitly prohibit extra arguments')
|
| 194 |
+
validator(schema)
|
| 195 |
+
if 'output_schema' in item:
|
| 196 |
+
validator(item['output_schema'])
|
| 197 |
+
return domain, descriptors
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def state_validator(environment):
|
| 201 |
+
path = Path(environment) / 'state_schema.json'
|
| 202 |
+
return validator(read(path)) if path.exists() else validator({'type': 'object'})
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def error(code, message):
|
| 206 |
+
return {'ok': False, 'error': {'code': code, 'message': message}}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def transition(environment, state, name, arguments, *, max_observation_bytes=DEFAULT_OBSERVATION_BYTES):
|
| 210 |
+
"""Return private {state, observation, dispatched}; never mutate inputs."""
|
| 211 |
+
canonical(state)
|
| 212 |
+
canonical(arguments)
|
| 213 |
+
require(type(state) is dict, 'State must be an object')
|
| 214 |
+
state_check = state_validator(environment)
|
| 215 |
+
state_check.validate(state)
|
| 216 |
+
domain, descriptors = load_domain(environment)
|
| 217 |
+
by_name = {item['name']: item for item in descriptors}
|
| 218 |
+
before, working = deepcopy(state), deepcopy(state)
|
| 219 |
+
def result(observation, dispatched, next_state=None):
|
| 220 |
+
return {'state': deepcopy(before if next_state is None else next_state),
|
| 221 |
+
'observation': deepcopy(observation), 'dispatched': dispatched}
|
| 222 |
+
if type(name) is not str or name not in by_name:
|
| 223 |
+
return result(error('UNKNOWN_TOOL', 'The requested tool is not public.'), False)
|
| 224 |
+
descriptor = by_name[name]
|
| 225 |
+
try:
|
| 226 |
+
require(type(arguments) is dict, 'Arguments must be an object')
|
| 227 |
+
validator(descriptor['input_schema']).validate(arguments)
|
| 228 |
+
except Exception:
|
| 229 |
+
return result(error('INVALID_ARGUMENTS', 'Arguments do not satisfy the public schema.'), False)
|
| 230 |
+
try:
|
| 231 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 232 |
+
observation = domain.call_tool(working, name, deepcopy(arguments))
|
| 233 |
+
except Exception:
|
| 234 |
+
return result(error('DOMAIN_EXECUTION_ERROR', 'The tool could not complete.'), True)
|
| 235 |
+
try:
|
| 236 |
+
require(type(observation) is dict and type(observation.get('ok')) is bool,
|
| 237 |
+
'Invalid domain envelope')
|
| 238 |
+
if observation['ok']:
|
| 239 |
+
require(set(observation) == {'ok', 'result'}, 'Invalid success envelope')
|
| 240 |
+
else:
|
| 241 |
+
require(set(observation) == {'ok', 'error'} and type(observation['error']) is dict,
|
| 242 |
+
'Invalid error envelope')
|
| 243 |
+
require(type(observation['error'].get('code')) is str and bool(observation['error']['code'])
|
| 244 |
+
and type(observation['error'].get('message')) is str, 'Invalid domain error')
|
| 245 |
+
encoded = canonical(observation)
|
| 246 |
+
require(type(max_observation_bytes) is int and 512 <= max_observation_bytes <= 1048576,
|
| 247 |
+
'Invalid observation limit')
|
| 248 |
+
if len(encoded) > max_observation_bytes:
|
| 249 |
+
return result(error('OBSERVATION_LIMIT', 'Tool result exceeds the public response limit.'), True)
|
| 250 |
+
if descriptor['read_only'] and canonical(working) != canonical(before):
|
| 251 |
+
return result(error('READ_ONLY_VIOLATION', 'A read-only tool attempted to change state.'), True)
|
| 252 |
+
if not observation['ok']:
|
| 253 |
+
return result(observation, True)
|
| 254 |
+
if 'output_schema' in descriptor:
|
| 255 |
+
validator(descriptor['output_schema']).validate(observation['result'])
|
| 256 |
+
state_check.validate(working)
|
| 257 |
+
canonical(working)
|
| 258 |
+
except Exception:
|
| 259 |
+
return result(error('INVALID_TOOL_RESULT', 'Tool output or state violates its contract.'), True)
|
| 260 |
+
return result(observation, True, working)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def main(argv=None):
|
| 264 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 265 |
+
parser.add_argument('--environment', type=Path, required=True)
|
| 266 |
+
parser.add_argument('--max-observation-bytes', type=int, default=DEFAULT_OBSERVATION_BYTES)
|
| 267 |
+
args = parser.parse_args(argv)
|
| 268 |
+
try:
|
| 269 |
+
raw = sys.stdin.buffer.read(MAX_INTERNAL_BYTES + 1)
|
| 270 |
+
require(len(raw) <= MAX_INTERNAL_BYTES, 'Internal request exceeds limit')
|
| 271 |
+
request = strict(raw)
|
| 272 |
+
with (patch('socket.socket', side_effect=RuntimeError('Offline worker forbids network')),
|
| 273 |
+
patch('socket.create_connection', side_effect=RuntimeError('Offline worker forbids network'))):
|
| 274 |
+
if request == {'action': 'describe'}:
|
| 275 |
+
_, descriptors = load_domain(args.environment)
|
| 276 |
+
state_validator(args.environment).validate(read(args.environment / 'state.json'))
|
| 277 |
+
value = {'tools': descriptors}
|
| 278 |
+
else:
|
| 279 |
+
require(type(request) is dict and set(request) == {'action', 'state', 'tool', 'arguments'}
|
| 280 |
+
and request['action'] == 'transition', 'Invalid internal request')
|
| 281 |
+
value = transition(args.environment, request['state'], request['tool'], request['arguments'],
|
| 282 |
+
max_observation_bytes=args.max_observation_bytes)
|
| 283 |
+
sys.stdout.buffer.write(canonical(value) + b'\n')
|
| 284 |
+
return 0
|
| 285 |
+
except Exception:
|
| 286 |
+
sys.stdout.buffer.write(canonical({'worker_error': 'RUNTIME_VALIDATION_FAILED'}) + b'\n')
|
| 287 |
+
return 1
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == '__main__':
|
| 291 |
+
raise SystemExit(main())
|
data/environments/eval60_gbif/vendor/rfc3339_validator.LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2019, Nicolas Aimetti
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
data/environments/eval60_gbif/vendor/rfc3339_validator.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Vendored 0.1.4; Python 3-only compatibility patch, see provenance.json.
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
__author__ = """Nicolas Aimetti"""
|
| 5 |
+
__email__ = 'naimetti@yahoo.com.ar'
|
| 6 |
+
__version__ = '0.1.4'
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
import calendar
|
| 10 |
+
|
| 11 |
+
RFC3339_REGEX_FLAGS = re.ASCII
|
| 12 |
+
|
| 13 |
+
RFC3339_REGEX = re.compile(r"""
|
| 14 |
+
^
|
| 15 |
+
(\d{4}) # Year
|
| 16 |
+
-
|
| 17 |
+
(0[1-9]|1[0-2]) # Month
|
| 18 |
+
-
|
| 19 |
+
(\d{2}) # Day
|
| 20 |
+
T
|
| 21 |
+
(?:[01]\d|2[0123]) # Hours
|
| 22 |
+
:
|
| 23 |
+
(?:[0-5]\d) # Minutes
|
| 24 |
+
:
|
| 25 |
+
(?:[0-5]\d) # Seconds
|
| 26 |
+
(?:\.\d+)? # Secfrac
|
| 27 |
+
(?: Z # UTC
|
| 28 |
+
| [+-](?:[01]\d|2[0123]):[0-5]\d # Offset
|
| 29 |
+
)
|
| 30 |
+
$
|
| 31 |
+
""", re.VERBOSE | RFC3339_REGEX_FLAGS)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def validate_rfc3339(date_string):
|
| 35 |
+
"""
|
| 36 |
+
Validates dates against RFC3339 datetime format
|
| 37 |
+
Leap seconds are no supported.
|
| 38 |
+
"""
|
| 39 |
+
m = RFC3339_REGEX.match(date_string)
|
| 40 |
+
if m is None:
|
| 41 |
+
return False
|
| 42 |
+
year, month, day = map(int, m.groups())
|
| 43 |
+
if not year:
|
| 44 |
+
# Year 0 is not valid a valid date
|
| 45 |
+
return False
|
| 46 |
+
(_, max_day) = calendar.monthrange(year, month)
|
| 47 |
+
if not 1 <= day <= max_day:
|
| 48 |
+
return False
|
| 49 |
+
return True
|
data/environments/eval60_gitlab/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Manually curated evaluation environment."""
|
data/environments/eval60_gitlab/domain/domain_tools.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _obj(properties, required):
|
| 5 |
+
return {"type": "object", "properties": properties, "required": required, "additionalProperties": False}
|
| 6 |
+
|
| 7 |
+
_PROJECT = _obj({
|
| 8 |
+
"id": {"type": "integer"}, "path": {"type": "string"}, "name": {"type": "string"},
|
| 9 |
+
"default_branch": {"type": "string"}, "visibility": {"type": "string", "enum": ["private", "internal", "public"]}
|
| 10 |
+
}, ["id", "path", "name", "default_branch", "visibility"])
|
| 11 |
+
|
| 12 |
+
_MR = _obj({
|
| 13 |
+
"id": {"type": "integer"}, "iid": {"type": "integer"}, "project_id": {"type": "integer"},
|
| 14 |
+
"title": {"type": "string"}, "description": {"type": "string"},
|
| 15 |
+
"state": {"type": "string", "enum": ["opened", "closed", "merged"]},
|
| 16 |
+
"draft": {"type": "boolean"}, "target_branch": {"type": "string"},
|
| 17 |
+
"source_branch": {"type": "string"}, "author_username": {"type": "string"},
|
| 18 |
+
"created_at": {"type": "string"}, "merge_status": {"type": "string"},
|
| 19 |
+
"detailed_merge_status": {"type": "string"}, "has_conflicts": {"type": "boolean"},
|
| 20 |
+
"blocking_discussions_resolved": {"type": "boolean"}, "web_url": {"type": "string"}
|
| 21 |
+
}, ["id", "iid", "project_id", "title", "description", "state", "draft", "target_branch", "source_branch", "author_username", "created_at", "merge_status", "detailed_merge_status", "has_conflicts", "blocking_discussions_resolved", "web_url"])
|
| 22 |
+
|
| 23 |
+
_PIPELINE = _obj({
|
| 24 |
+
"id": {"type": "integer"}, "project_id": {"type": "integer"}, "merge_request_id": {"type": "integer"},
|
| 25 |
+
"sha": {"type": "string"}, "status": {"type": "string", "enum": ["created", "pending", "running", "success", "failed", "canceled", "skipped"]},
|
| 26 |
+
"created_at": {"type": "string"}, "web_url": {"type": "string"}
|
| 27 |
+
}, ["id", "project_id", "merge_request_id", "sha", "status", "created_at", "web_url"])
|
| 28 |
+
|
| 29 |
+
_DISCUSSION = _obj({
|
| 30 |
+
"id": {"type": "string"}, "merge_request_id": {"type": "integer"}, "blocking": {"type": "boolean"},
|
| 31 |
+
"resolved": {"type": "boolean"}, "created_at": {"type": "string"}, "author_username": {"type": "string"}
|
| 32 |
+
}, ["id", "merge_request_id", "blocking", "resolved", "created_at", "author_username"])
|
| 33 |
+
|
| 34 |
+
_APPROVAL = _obj({
|
| 35 |
+
"merge_request_id": {"type": "integer"}, "approvals_required": {"type": "integer", "minimum": 0},
|
| 36 |
+
"approvals_obtained": {"type": "integer", "minimum": 0}, "approved_by_usernames": {"type": "array", "items": {"type": "string"}},
|
| 37 |
+
"rules_satisfied": {"type": "boolean"}, "updated_at": {"type": "string"}
|
| 38 |
+
}, ["merge_request_id", "approvals_required", "approvals_obtained", "approved_by_usernames", "rules_satisfied", "updated_at"])
|
| 39 |
+
|
| 40 |
+
TOOL_SCHEMAS = [
|
| 41 |
+
{
|
| 42 |
+
"name": "get_project",
|
| 43 |
+
"description": "Retrieve one complete synthetic local project record by its full path. This offline simulation models documented GitLab project identifiers but is not an API-compatible clone.",
|
| 44 |
+
"input_schema": _obj({"path": {"type": "string", "minLength": 1}}, ["path"]),
|
| 45 |
+
"read_only": True,
|
| 46 |
+
"output_schema": _obj({"project": _PROJECT}, ["project"])
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"name": "list_project_merge_requests",
|
| 50 |
+
"description": "List complete synthetic local merge-request records for a project, with optional exact state and target-branch filters. An empty filtered match is reported as NO_MATCH. Fields include both legacy merge_status and detailed_merge_status so callers can apply the documented preference.",
|
| 51 |
+
"input_schema": _obj({
|
| 52 |
+
"project_id": {"type": "integer"},
|
| 53 |
+
"state": {"type": "string", "enum": ["opened", "closed", "merged", "all"]},
|
| 54 |
+
"target_branch": {"type": ["string", "null"]}
|
| 55 |
+
}, ["project_id", "state", "target_branch"]),
|
| 56 |
+
"read_only": True,
|
| 57 |
+
"output_schema": _obj({"merge_requests": {"type": "array", "items": _MR}, "count": {"type": "integer", "minimum": 0}}, ["merge_requests", "count"])
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"name": "list_merge_request_pipelines",
|
| 61 |
+
"description": "List all synthetic local pipeline records linked to one merge request. The collection may legitimately be empty. This operation does not choose a latest pipeline.",
|
| 62 |
+
"input_schema": _obj({"project_id": {"type": "integer"}, "merge_request_iid": {"type": "integer"}}, ["project_id", "merge_request_iid"]),
|
| 63 |
+
"read_only": True,
|
| 64 |
+
"output_schema": _obj({"pipelines": {"type": "array", "items": _PIPELINE}, "count": {"type": "integer", "minimum": 0}}, ["pipelines", "count"])
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"name": "list_merge_request_discussions",
|
| 68 |
+
"description": "List all synthetic local discussion summaries linked to one merge request. The collection may legitimately be empty; blocking and resolved are local summary fields.",
|
| 69 |
+
"input_schema": _obj({"project_id": {"type": "integer"}, "merge_request_iid": {"type": "integer"}}, ["project_id", "merge_request_iid"]),
|
| 70 |
+
"read_only": True,
|
| 71 |
+
"output_schema": _obj({"discussions": {"type": "array", "items": _DISCUSSION}, "count": {"type": "integer", "minimum": 0}}, ["discussions", "count"])
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"name": "get_merge_request_approval_state",
|
| 75 |
+
"description": "Retrieve the complete synthetic local approval-state record for one merge request. Approval requirements are local policy records, separate from deprecated merge-request approval-count fields.",
|
| 76 |
+
"input_schema": _obj({"project_id": {"type": "integer"}, "merge_request_iid": {"type": "integer"}}, ["project_id", "merge_request_iid"]),
|
| 77 |
+
"read_only": True,
|
| 78 |
+
"output_schema": _obj({"approval_state": _APPROVAL}, ["approval_state"])
|
| 79 |
+
}
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _err(code, message, **extra):
|
| 84 |
+
e = {"code": code, "message": message}
|
| 85 |
+
e.update(extra)
|
| 86 |
+
return {"ok": False, "error": e}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _valid(arguments, keys, types):
|
| 90 |
+
if not isinstance(arguments, dict):
|
| 91 |
+
return False
|
| 92 |
+
if set(arguments) != set(keys):
|
| 93 |
+
return False
|
| 94 |
+
for k, t in types.items():
|
| 95 |
+
v = arguments[k]
|
| 96 |
+
if t == "int" and (not isinstance(v, int) or isinstance(v, bool)):
|
| 97 |
+
return False
|
| 98 |
+
if t == "str" and (not isinstance(v, str) or not v):
|
| 99 |
+
return False
|
| 100 |
+
return True
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _project(state, project_id):
|
| 104 |
+
for p in state.get("projects", []):
|
| 105 |
+
if p.get("id") == project_id:
|
| 106 |
+
return p
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _mr(state, project_id, iid):
|
| 111 |
+
for m in state.get("merge_requests", []):
|
| 112 |
+
if m.get("project_id") == project_id and m.get("iid") == iid:
|
| 113 |
+
return m
|
| 114 |
+
return None
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def call_tool(state, name, arguments):
|
| 118 |
+
if name == "get_project":
|
| 119 |
+
if not _valid(arguments, ["path"], {"path": "str"}):
|
| 120 |
+
return _err("INVALID_ARGUMENT", "Expected exactly one non-empty string field: path.")
|
| 121 |
+
for p in state.get("projects", []):
|
| 122 |
+
if p.get("path") == arguments["path"]:
|
| 123 |
+
return {"ok": True, "result": {"project": deepcopy(p)}}
|
| 124 |
+
return _err("NOT_FOUND", "Project path was not found.", resource="project:" + arguments["path"])
|
| 125 |
+
|
| 126 |
+
if name == "list_project_merge_requests":
|
| 127 |
+
if not _valid(arguments, ["project_id", "state", "target_branch"], {"project_id": "int"}):
|
| 128 |
+
return _err("INVALID_ARGUMENT", "Expected project_id integer, supported state, and string-or-null target_branch.")
|
| 129 |
+
if arguments["state"] not in ("opened", "closed", "merged", "all") or not (arguments["target_branch"] is None or isinstance(arguments["target_branch"], str)):
|
| 130 |
+
return _err("INVALID_ARGUMENT", "Expected project_id integer, supported state, and string-or-null target_branch.")
|
| 131 |
+
if _project(state, arguments["project_id"]) is None:
|
| 132 |
+
return _err("NOT_FOUND", "Project ID was not found.", resource="project:%s" % arguments["project_id"])
|
| 133 |
+
rows = [m for m in state.get("merge_requests", []) if m["project_id"] == arguments["project_id"]]
|
| 134 |
+
if arguments["state"] != "all":
|
| 135 |
+
rows = [m for m in rows if m["state"] == arguments["state"]]
|
| 136 |
+
if arguments["target_branch"] is not None:
|
| 137 |
+
rows = [m for m in rows if m["target_branch"] == arguments["target_branch"]]
|
| 138 |
+
if not rows:
|
| 139 |
+
return _err("NO_MATCH", "No merge requests match the supplied filters.")
|
| 140 |
+
rows.sort(key=lambda x: x["iid"])
|
| 141 |
+
return {"ok": True, "result": {"merge_requests": deepcopy(rows), "count": len(rows)}}
|
| 142 |
+
|
| 143 |
+
if name in ("list_merge_request_pipelines", "list_merge_request_discussions", "get_merge_request_approval_state"):
|
| 144 |
+
if not _valid(arguments, ["project_id", "merge_request_iid"], {"project_id": "int", "merge_request_iid": "int"}):
|
| 145 |
+
return _err("INVALID_ARGUMENT", "Expected exactly integer project_id and merge_request_iid.")
|
| 146 |
+
if _project(state, arguments["project_id"]) is None:
|
| 147 |
+
return _err("NOT_FOUND", "Project ID was not found.", resource="project:%s" % arguments["project_id"])
|
| 148 |
+
mr = _mr(state, arguments["project_id"], arguments["merge_request_iid"])
|
| 149 |
+
if mr is None:
|
| 150 |
+
return _err("NOT_FOUND", "Merge request IID was not found in this project.", resource="merge_request:%s:!%s" % (arguments["project_id"], arguments["merge_request_iid"]))
|
| 151 |
+
mid = str(mr["id"])
|
| 152 |
+
if name == "list_merge_request_pipelines":
|
| 153 |
+
rows = [x for x in state.get("pipelines", []) if x["merge_request_id"] == mr["id"]]
|
| 154 |
+
rows.sort(key=lambda x: (x["created_at"], x["id"]))
|
| 155 |
+
return {"ok": True, "result": {"pipelines": deepcopy(rows), "count": len(rows)}}
|
| 156 |
+
if name == "list_merge_request_discussions":
|
| 157 |
+
rows = [x for x in state.get("discussions", []) if x["merge_request_id"] == mr["id"]]
|
| 158 |
+
rows.sort(key=lambda x: (x["created_at"], x["id"]))
|
| 159 |
+
return {"ok": True, "result": {"discussions": deepcopy(rows), "count": len(rows)}}
|
| 160 |
+
resource = "approval_state:" + mid
|
| 161 |
+
if state.get("availability", {}).get("approval_states", {}).get(mid) is False:
|
| 162 |
+
return _err("UNAVAILABLE", "The requested approval-state resource is unavailable.", resource=resource)
|
| 163 |
+
rec = state.get("approval_states", {}).get(mid)
|
| 164 |
+
if rec is None:
|
| 165 |
+
return _err("NOT_FOUND", "Approval-state record was not found.", resource=resource)
|
| 166 |
+
return {"ok": True, "result": {"approval_state": deepcopy(rec)}}
|
| 167 |
+
|
| 168 |
+
return _err("UNKNOWN_TOOL", "Unknown tool name.")
|
data/environments/eval60_gitlab/environment.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Official tool adapter to the exact sealed transaction runtime."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import copy
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import threading
|
| 10 |
+
from typing import Any, Callable
|
| 11 |
+
|
| 12 |
+
from fastmcp.tools import Tool
|
| 13 |
+
from fastmcp.tools.tool import ToolResult
|
| 14 |
+
from pydantic import Field
|
| 15 |
+
from hera_environment import BaseEnvironment, ToolError
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parent
|
| 18 |
+
_spec = importlib.util.spec_from_file_location(__name__ + '_runtime', ROOT/'runtime.py')
|
| 19 |
+
support = importlib.util.module_from_spec(_spec)
|
| 20 |
+
_spec.loader.exec_module(support)
|
| 21 |
+
STATE_SCHEMA = json.loads('{"type": "object"}')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _DomainTool(Tool):
|
| 25 |
+
fn: Callable[..., Any] = Field(exclude=True)
|
| 26 |
+
|
| 27 |
+
async def run(self, arguments: dict[str, Any]) -> ToolResult:
|
| 28 |
+
envelope = self.fn(**arguments)
|
| 29 |
+
return ToolResult(content=json.dumps(envelope,ensure_ascii=False,allow_nan=False),
|
| 30 |
+
structured_content=envelope,is_error=envelope['ok'] is False)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Environment(BaseEnvironment):
|
| 34 |
+
env_name = 'eval60_gitlab'
|
| 35 |
+
short_name = 'GitLab'
|
| 36 |
+
always_skip_fields = set()
|
| 37 |
+
mutation_tools = set()
|
| 38 |
+
mutation_id_fields = set()
|
| 39 |
+
tool_kinds = json.loads('{"get_merge_request_approval_state": "lookup", "get_project": "lookup", "list_merge_request_discussions": "lookup", "list_merge_request_pipelines": "lookup", "list_project_merge_requests": "lookup"}')
|
| 40 |
+
_descriptors = json.loads('[{"description": "Retrieve one complete synthetic local project record by its full path. This offline simulation models documented GitLab project identifiers but is not an API-compatible clone.", "input_schema": {"additionalProperties": false, "properties": {"path": {"minLength": 1, "type": "string"}}, "required": ["path"], "type": "object"}, "name": "get_project", "output_schema": {"additionalProperties": false, "properties": {"project": {"additionalProperties": false, "properties": {"default_branch": {"type": "string"}, "id": {"type": "integer"}, "name": {"type": "string"}, "path": {"type": "string"}, "visibility": {"enum": ["private", "internal", "public"], "type": "string"}}, "required": ["id", "path", "name", "default_branch", "visibility"], "type": "object"}}, "required": ["project"], "type": "object"}, "read_only": true}, {"description": "List complete synthetic local merge-request records for a project, with optional exact state and target-branch filters. An empty filtered match is reported as NO_MATCH. Fields include both legacy merge_status and detailed_merge_status so callers can apply the documented preference.", "input_schema": {"additionalProperties": false, "properties": {"project_id": {"type": "integer"}, "state": {"enum": ["opened", "closed", "merged", "all"], "type": "string"}, "target_branch": {"type": ["string", "null"]}}, "required": ["project_id", "state", "target_branch"], "type": "object"}, "name": "list_project_merge_requests", "output_schema": {"additionalProperties": false, "properties": {"count": {"minimum": 0, "type": "integer"}, "merge_requests": {"items": {"additionalProperties": false, "properties": {"author_username": {"type": "string"}, "blocking_discussions_resolved": {"type": "boolean"}, "created_at": {"type": "string"}, "description": {"type": "string"}, "detailed_merge_status": {"type": "string"}, "draft": {"type": "boolean"}, "has_conflicts": {"type": "boolean"}, "id": {"type": "integer"}, "iid": {"type": "integer"}, "merge_status": {"type": "string"}, "project_id": {"type": "integer"}, "source_branch": {"type": "string"}, "state": {"enum": ["opened", "closed", "merged"], "type": "string"}, "target_branch": {"type": "string"}, "title": {"type": "string"}, "web_url": {"type": "string"}}, "required": ["id", "iid", "project_id", "title", "description", "state", "draft", "target_branch", "source_branch", "author_username", "created_at", "merge_status", "detailed_merge_status", "has_conflicts", "blocking_discussions_resolved", "web_url"], "type": "object"}, "type": "array"}}, "required": ["merge_requests", "count"], "type": "object"}, "read_only": true}, {"description": "List all synthetic local pipeline records linked to one merge request. The collection may legitimately be empty. This operation does not choose a latest pipeline.", "input_schema": {"additionalProperties": false, "properties": {"merge_request_iid": {"type": "integer"}, "project_id": {"type": "integer"}}, "required": ["project_id", "merge_request_iid"], "type": "object"}, "name": "list_merge_request_pipelines", "output_schema": {"additionalProperties": false, "properties": {"count": {"minimum": 0, "type": "integer"}, "pipelines": {"items": {"additionalProperties": false, "properties": {"created_at": {"type": "string"}, "id": {"type": "integer"}, "merge_request_id": {"type": "integer"}, "project_id": {"type": "integer"}, "sha": {"type": "string"}, "status": {"enum": ["created", "pending", "running", "success", "failed", "canceled", "skipped"], "type": "string"}, "web_url": {"type": "string"}}, "required": ["id", "project_id", "merge_request_id", "sha", "status", "created_at", "web_url"], "type": "object"}, "type": "array"}}, "required": ["pipelines", "count"], "type": "object"}, "read_only": true}, {"description": "List all synthetic local discussion summaries linked to one merge request. The collection may legitimately be empty; blocking and resolved are local summary fields.", "input_schema": {"additionalProperties": false, "properties": {"merge_request_iid": {"type": "integer"}, "project_id": {"type": "integer"}}, "required": ["project_id", "merge_request_iid"], "type": "object"}, "name": "list_merge_request_discussions", "output_schema": {"additionalProperties": false, "properties": {"count": {"minimum": 0, "type": "integer"}, "discussions": {"items": {"additionalProperties": false, "properties": {"author_username": {"type": "string"}, "blocking": {"type": "boolean"}, "created_at": {"type": "string"}, "id": {"type": "string"}, "merge_request_id": {"type": "integer"}, "resolved": {"type": "boolean"}}, "required": ["id", "merge_request_id", "blocking", "resolved", "created_at", "author_username"], "type": "object"}, "type": "array"}}, "required": ["discussions", "count"], "type": "object"}, "read_only": true}, {"description": "Retrieve the complete synthetic local approval-state record for one merge request. Approval requirements are local policy records, separate from deprecated merge-request approval-count fields.", "input_schema": {"additionalProperties": false, "properties": {"merge_request_iid": {"type": "integer"}, "project_id": {"type": "integer"}}, "required": ["project_id", "merge_request_iid"], "type": "object"}, "name": "get_merge_request_approval_state", "output_schema": {"additionalProperties": false, "properties": {"approval_state": {"additionalProperties": false, "properties": {"approvals_obtained": {"minimum": 0, "type": "integer"}, "approvals_required": {"minimum": 0, "type": "integer"}, "approved_by_usernames": {"items": {"type": "string"}, "type": "array"}, "merge_request_id": {"type": "integer"}, "rules_satisfied": {"type": "boolean"}, "updated_at": {"type": "string"}}, "required": ["merge_request_id", "approvals_required", "approvals_obtained", "approved_by_usernames", "rules_satisfied", "updated_at"], "type": "object"}}, "required": ["approval_state"], "type": "object"}, "read_only": true}]')
|
| 41 |
+
|
| 42 |
+
def _load_state(self, initial_state):
|
| 43 |
+
support.validator(STATE_SCHEMA).validate(initial_state)
|
| 44 |
+
return copy.deepcopy(initial_state)
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def get_empty_state(cls):return {}
|
| 48 |
+
|
| 49 |
+
@classmethod
|
| 50 |
+
def get_example_state(cls):return {}
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def get_state_schema(cls):return copy.deepcopy(STATE_SCHEMA)
|
| 54 |
+
|
| 55 |
+
def _register_tools(self):
|
| 56 |
+
self._transaction_lock = threading.Lock()
|
| 57 |
+
self._transport_attempts = []
|
| 58 |
+
_, actual = support.load_domain(ROOT/'domain')
|
| 59 |
+
if support.canonical(actual) != support.canonical(self._descriptors):
|
| 60 |
+
raise ValueError('Public tool descriptors differ from the sealed domain')
|
| 61 |
+
for item in self._descriptors:
|
| 62 |
+
def bind(name):
|
| 63 |
+
def call(**arguments):return self._invoke_domain(name,arguments)
|
| 64 |
+
return call
|
| 65 |
+
output = None
|
| 66 |
+
if 'output_schema' in item:
|
| 67 |
+
output={'type':'object','oneOf':[
|
| 68 |
+
{'type':'object','required':['ok','result'],'additionalProperties':False,
|
| 69 |
+
'properties':{'ok':{'const':True},'result':copy.deepcopy(item['output_schema'])}},
|
| 70 |
+
{'type':'object','required':['ok','error'],'additionalProperties':False,
|
| 71 |
+
'properties':{'ok':{'const':False},'error':{'type':'object','required':['code','message'],
|
| 72 |
+
'properties':{'code':{'type':'string','minLength':1},'message':{'type':'string'}}}}}]}
|
| 73 |
+
self.mcp.add_tool(_DomainTool(name=item['name'],description=item['description'],
|
| 74 |
+
parameters=copy.deepcopy(item['input_schema']),output_schema=output,fn=bind(item['name'])))
|
| 75 |
+
|
| 76 |
+
def _invoke_domain(self, name, arguments):
|
| 77 |
+
with self._transaction_lock:
|
| 78 |
+
before = copy.deepcopy(self.state)
|
| 79 |
+
if len(support.canonical({'tool':name,'arguments':arguments})) > 32768:
|
| 80 |
+
raise ToolError('PUBLIC_REQUEST_LIMIT')
|
| 81 |
+
request = {'action':'transition','state':before,'tool':name,'arguments':arguments}
|
| 82 |
+
try:
|
| 83 |
+
process = subprocess.run([sys.executable,'-I','-B',str(ROOT/'runtime.py'),
|
| 84 |
+
'--environment',str(ROOT/'domain'),'--max-observation-bytes','32768'],
|
| 85 |
+
input=support.canonical(request),capture_output=True,timeout=120,
|
| 86 |
+
cwd=str(ROOT),env={'PATH':'/usr/bin:/bin','PYTHONDONTWRITEBYTECODE':'1'})
|
| 87 |
+
result = support.strict(process.stdout)
|
| 88 |
+
if process.returncode or set(result) != {'state','observation','dispatched'}:
|
| 89 |
+
raise ValueError('Transaction worker failed')
|
| 90 |
+
observation = result['observation']
|
| 91 |
+
support.canonical(observation)
|
| 92 |
+
self.state = copy.deepcopy(result['state'])
|
| 93 |
+
except Exception as exc:
|
| 94 |
+
self.state = before
|
| 95 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 96 |
+
'observation':None,'dispatched':None,'error':'TRANSACTION_INFRASTRUCTURE_ERROR'})
|
| 97 |
+
raise ToolError('TRANSACTION_INFRASTRUCTURE_ERROR') from exc
|
| 98 |
+
error = None if observation['ok'] else json.dumps(observation['error'],ensure_ascii=False)
|
| 99 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 100 |
+
'observation':copy.deepcopy(observation),'dispatched':result['dispatched']})
|
| 101 |
+
# Keep the semantic event stream identical to controller.public.
|
| 102 |
+
# Rejected pre-dispatch requests remain attempts but cannot count
|
| 103 |
+
# as observed domain evidence. MCP may itself reject extra keys
|
| 104 |
+
# before this adapter; that is a transport error, not a domain event.
|
| 105 |
+
if result['dispatched']:
|
| 106 |
+
self._log_tool_call(name,copy.deepcopy(arguments),copy.deepcopy(observation),
|
| 107 |
+
success=observation['ok'],error=error)
|
| 108 |
+
return observation
|
data/environments/eval60_gitlab/runtime.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small offline transaction boundary for reviewed, candidate-specific tools.
|
| 2 |
+
|
| 3 |
+
This is not a sandbox for hostile Python. The trusted controller runs this
|
| 4 |
+
worker in a fresh interpreter for every call and keeps its state output private.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
from contextlib import redirect_stderr, redirect_stdout
|
| 10 |
+
from copy import deepcopy
|
| 11 |
+
import importlib.util
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import re
|
| 16 |
+
import sys
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
from jsonschema import Draft202012Validator, FormatChecker, validators
|
| 20 |
+
|
| 21 |
+
sys.dont_write_bytecode = True
|
| 22 |
+
MAX_REQUEST_BYTES = 32768
|
| 23 |
+
MAX_INTERNAL_BYTES = 16 * 1024 * 1024
|
| 24 |
+
DEFAULT_OBSERVATION_BYTES = 32768
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def require(condition, message):
|
| 28 |
+
if not condition:
|
| 29 |
+
raise ValueError(message)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def canonical(value):
|
| 33 |
+
# Reject Python-only coercions such as integer object keys or tuples.
|
| 34 |
+
def check(item):
|
| 35 |
+
if item is None or type(item) in (str, bool, int):
|
| 36 |
+
return
|
| 37 |
+
if type(item) is float:
|
| 38 |
+
require(math.isfinite(item), 'Nonfinite JSON number')
|
| 39 |
+
return
|
| 40 |
+
if type(item) is list:
|
| 41 |
+
for child in item:
|
| 42 |
+
check(child)
|
| 43 |
+
return
|
| 44 |
+
if type(item) is dict:
|
| 45 |
+
require(all(type(key) is str for key in item), 'JSON keys must be strings')
|
| 46 |
+
for child in item.values():
|
| 47 |
+
check(child)
|
| 48 |
+
return
|
| 49 |
+
raise ValueError('Value is not JSON')
|
| 50 |
+
check(value)
|
| 51 |
+
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
| 52 |
+
sort_keys=True, separators=(',', ':')).encode('utf-8')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def strict(raw):
|
| 56 |
+
if type(raw) is bytes:
|
| 57 |
+
raw = raw.decode('utf-8', errors='strict')
|
| 58 |
+
require(type(raw) is str, 'Expected JSON bytes or text')
|
| 59 |
+
def pairs(items):
|
| 60 |
+
result = {}
|
| 61 |
+
for key, value in items:
|
| 62 |
+
require(key not in result, 'Duplicate JSON key')
|
| 63 |
+
result[key] = value
|
| 64 |
+
return result
|
| 65 |
+
value = json.loads(raw, object_pairs_hook=pairs,
|
| 66 |
+
parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Nonfinite JSON')))
|
| 67 |
+
canonical(value)
|
| 68 |
+
return value
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read(path):
|
| 72 |
+
path = Path(path)
|
| 73 |
+
require(path.is_file() and not path.is_symlink(), 'Expected a regular file')
|
| 74 |
+
return strict(path.read_bytes())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
_TYPE_CHECKER = Draft202012Validator.TYPE_CHECKER.redefine_many({
|
| 78 |
+
'integer': lambda checker, value: type(value) is int,
|
| 79 |
+
'number': lambda checker, value: type(value) is int or (type(value) is float and math.isfinite(value)),
|
| 80 |
+
})
|
| 81 |
+
StrictValidator = validators.extend(Draft202012Validator, type_checker=_TYPE_CHECKER)
|
| 82 |
+
|
| 83 |
+
# Load the pinned optional format checker by bundle-relative path. It requires
|
| 84 |
+
# no network, installed extras, sys.path changes, or historical checkout.
|
| 85 |
+
_date_path = Path(__file__).resolve().parent / 'vendor/rfc3339_validator.py'
|
| 86 |
+
_date_spec = importlib.util.spec_from_file_location('_curated_rfc3339', _date_path)
|
| 87 |
+
_date_module = importlib.util.module_from_spec(_date_spec)
|
| 88 |
+
_date_spec.loader.exec_module(_date_module)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def validator(schema):
|
| 92 |
+
require(type(schema) in (dict, bool), 'Schema must be a JSON Schema')
|
| 93 |
+
canonical(schema)
|
| 94 |
+
formats = FormatChecker()
|
| 95 |
+
@formats.checks('date-time')
|
| 96 |
+
def date_time(value):
|
| 97 |
+
return not isinstance(value, str) or _date_module.validate_rfc3339(value.upper())
|
| 98 |
+
visited = set()
|
| 99 |
+
def inspect(value):
|
| 100 |
+
if type(value) is dict:
|
| 101 |
+
if id(value) in visited:
|
| 102 |
+
return
|
| 103 |
+
visited.add(id(value))
|
| 104 |
+
require(value != {'truncated': True}, 'Truncated schemas are unsupported')
|
| 105 |
+
require('$id' not in value and '$dynamicRef' not in value,
|
| 106 |
+
'Schema resource rebasing and dynamic references are unsupported')
|
| 107 |
+
if 'format' in value:
|
| 108 |
+
require(type(value['format']) is str and value['format'] in formats.checkers,
|
| 109 |
+
'Unsupported schema format')
|
| 110 |
+
if '$ref' in value:
|
| 111 |
+
ref = value['$ref']
|
| 112 |
+
require(type(ref) is str and (ref == '#' or ref.startswith('#/')),
|
| 113 |
+
'Only local JSON Pointer schema references are allowed')
|
| 114 |
+
current = schema
|
| 115 |
+
if ref != '#':
|
| 116 |
+
for part in ref[2:].split('/'):
|
| 117 |
+
part = part.replace('~1', '/').replace('~0', '~')
|
| 118 |
+
if type(current) is list:
|
| 119 |
+
require(part.isdigit(), 'Invalid local schema reference')
|
| 120 |
+
current = current[int(part)]
|
| 121 |
+
else:
|
| 122 |
+
require(type(current) is dict and part in current,
|
| 123 |
+
'Missing local schema reference')
|
| 124 |
+
current = current[part]
|
| 125 |
+
require(type(current) in (dict, bool), 'Schema reference is not a schema')
|
| 126 |
+
# A local reference may target a schema stored outside the
|
| 127 |
+
# standard schema keywords; inspect that target as well.
|
| 128 |
+
inspect(current)
|
| 129 |
+
# Walk schema locations, not property names or literal const/enum
|
| 130 |
+
# data (a business field named "format" is not a schema keyword).
|
| 131 |
+
for keyword in ('properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'):
|
| 132 |
+
if keyword in value:
|
| 133 |
+
require(type(value[keyword]) is dict, 'Invalid schema map')
|
| 134 |
+
for child in value[keyword].values():
|
| 135 |
+
inspect(child)
|
| 136 |
+
for keyword in ('allOf', 'anyOf', 'oneOf', 'prefixItems'):
|
| 137 |
+
if keyword in value:
|
| 138 |
+
require(type(value[keyword]) is list, 'Invalid schema sequence')
|
| 139 |
+
for child in value[keyword]:
|
| 140 |
+
inspect(child)
|
| 141 |
+
for keyword in ('items', 'contains', 'additionalProperties', 'propertyNames',
|
| 142 |
+
'unevaluatedProperties', 'unevaluatedItems', 'not', 'if', 'then', 'else'):
|
| 143 |
+
if keyword in value:
|
| 144 |
+
inspect(value[keyword])
|
| 145 |
+
inspect(schema)
|
| 146 |
+
Draft202012Validator.check_schema(schema)
|
| 147 |
+
return StrictValidator(schema, format_checker=formats)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class _BoundedSink:
|
| 151 |
+
def __init__(self):
|
| 152 |
+
self.size = 0
|
| 153 |
+
|
| 154 |
+
def write(self, value):
|
| 155 |
+
self.size += len(value.encode('utf-8'))
|
| 156 |
+
require(self.size <= 16384, 'Domain diagnostic output exceeded limit')
|
| 157 |
+
return len(value)
|
| 158 |
+
|
| 159 |
+
def flush(self):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def load_domain(environment):
|
| 164 |
+
environment = Path(environment)
|
| 165 |
+
require(environment.is_dir() and not environment.is_symlink(), 'Invalid environment directory')
|
| 166 |
+
path = environment / 'domain_tools.py'
|
| 167 |
+
require(path.is_file() and not path.is_symlink(), 'Invalid domain module')
|
| 168 |
+
spec = importlib.util.spec_from_file_location('_curated_domain_tools', path)
|
| 169 |
+
domain = importlib.util.module_from_spec(spec)
|
| 170 |
+
# No sys.path injection and no reuse of an earlier module's global state.
|
| 171 |
+
sys.modules[spec.name] = domain
|
| 172 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 173 |
+
spec.loader.exec_module(domain)
|
| 174 |
+
require(callable(getattr(domain, 'call_tool', None)), 'Domain call_tool is missing')
|
| 175 |
+
descriptors = deepcopy(getattr(domain, 'TOOL_SCHEMAS', None))
|
| 176 |
+
require(type(descriptors) is list and bool(descriptors), 'Tool schemas must be a nonempty list')
|
| 177 |
+
names = set()
|
| 178 |
+
for item in descriptors:
|
| 179 |
+
require(type(item) is dict and set(item) <= {
|
| 180 |
+
'name', 'description', 'input_schema', 'output_schema', 'read_only'
|
| 181 |
+
} and {'name', 'description', 'input_schema', 'read_only'} <= set(item),
|
| 182 |
+
'Invalid tool descriptor fields')
|
| 183 |
+
name = item['name']
|
| 184 |
+
require(type(name) is str and re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,127}', name)
|
| 185 |
+
and name not in names, 'Invalid or duplicate tool name')
|
| 186 |
+
names.add(name)
|
| 187 |
+
require(type(item['description']) is str and bool(item['description'].strip()),
|
| 188 |
+
'Tool description is required')
|
| 189 |
+
require(type(item['read_only']) is bool, 'read_only must be boolean')
|
| 190 |
+
schema = item['input_schema']
|
| 191 |
+
require(type(schema) is dict and schema.get('type') == 'object'
|
| 192 |
+
and schema.get('additionalProperties') is False,
|
| 193 |
+
'Tool input must explicitly prohibit extra arguments')
|
| 194 |
+
validator(schema)
|
| 195 |
+
if 'output_schema' in item:
|
| 196 |
+
validator(item['output_schema'])
|
| 197 |
+
return domain, descriptors
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def state_validator(environment):
|
| 201 |
+
path = Path(environment) / 'state_schema.json'
|
| 202 |
+
return validator(read(path)) if path.exists() else validator({'type': 'object'})
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def error(code, message):
|
| 206 |
+
return {'ok': False, 'error': {'code': code, 'message': message}}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def transition(environment, state, name, arguments, *, max_observation_bytes=DEFAULT_OBSERVATION_BYTES):
|
| 210 |
+
"""Return private {state, observation, dispatched}; never mutate inputs."""
|
| 211 |
+
canonical(state)
|
| 212 |
+
canonical(arguments)
|
| 213 |
+
require(type(state) is dict, 'State must be an object')
|
| 214 |
+
state_check = state_validator(environment)
|
| 215 |
+
state_check.validate(state)
|
| 216 |
+
domain, descriptors = load_domain(environment)
|
| 217 |
+
by_name = {item['name']: item for item in descriptors}
|
| 218 |
+
before, working = deepcopy(state), deepcopy(state)
|
| 219 |
+
def result(observation, dispatched, next_state=None):
|
| 220 |
+
return {'state': deepcopy(before if next_state is None else next_state),
|
| 221 |
+
'observation': deepcopy(observation), 'dispatched': dispatched}
|
| 222 |
+
if type(name) is not str or name not in by_name:
|
| 223 |
+
return result(error('UNKNOWN_TOOL', 'The requested tool is not public.'), False)
|
| 224 |
+
descriptor = by_name[name]
|
| 225 |
+
try:
|
| 226 |
+
require(type(arguments) is dict, 'Arguments must be an object')
|
| 227 |
+
validator(descriptor['input_schema']).validate(arguments)
|
| 228 |
+
except Exception:
|
| 229 |
+
return result(error('INVALID_ARGUMENTS', 'Arguments do not satisfy the public schema.'), False)
|
| 230 |
+
try:
|
| 231 |
+
with redirect_stdout(_BoundedSink()), redirect_stderr(_BoundedSink()):
|
| 232 |
+
observation = domain.call_tool(working, name, deepcopy(arguments))
|
| 233 |
+
except Exception:
|
| 234 |
+
return result(error('DOMAIN_EXECUTION_ERROR', 'The tool could not complete.'), True)
|
| 235 |
+
try:
|
| 236 |
+
require(type(observation) is dict and type(observation.get('ok')) is bool,
|
| 237 |
+
'Invalid domain envelope')
|
| 238 |
+
if observation['ok']:
|
| 239 |
+
require(set(observation) == {'ok', 'result'}, 'Invalid success envelope')
|
| 240 |
+
else:
|
| 241 |
+
require(set(observation) == {'ok', 'error'} and type(observation['error']) is dict,
|
| 242 |
+
'Invalid error envelope')
|
| 243 |
+
require(type(observation['error'].get('code')) is str and bool(observation['error']['code'])
|
| 244 |
+
and type(observation['error'].get('message')) is str, 'Invalid domain error')
|
| 245 |
+
encoded = canonical(observation)
|
| 246 |
+
require(type(max_observation_bytes) is int and 512 <= max_observation_bytes <= 1048576,
|
| 247 |
+
'Invalid observation limit')
|
| 248 |
+
if len(encoded) > max_observation_bytes:
|
| 249 |
+
return result(error('OBSERVATION_LIMIT', 'Tool result exceeds the public response limit.'), True)
|
| 250 |
+
if descriptor['read_only'] and canonical(working) != canonical(before):
|
| 251 |
+
return result(error('READ_ONLY_VIOLATION', 'A read-only tool attempted to change state.'), True)
|
| 252 |
+
if not observation['ok']:
|
| 253 |
+
return result(observation, True)
|
| 254 |
+
if 'output_schema' in descriptor:
|
| 255 |
+
validator(descriptor['output_schema']).validate(observation['result'])
|
| 256 |
+
state_check.validate(working)
|
| 257 |
+
canonical(working)
|
| 258 |
+
except Exception:
|
| 259 |
+
return result(error('INVALID_TOOL_RESULT', 'Tool output or state violates its contract.'), True)
|
| 260 |
+
return result(observation, True, working)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def main(argv=None):
|
| 264 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 265 |
+
parser.add_argument('--environment', type=Path, required=True)
|
| 266 |
+
parser.add_argument('--max-observation-bytes', type=int, default=DEFAULT_OBSERVATION_BYTES)
|
| 267 |
+
args = parser.parse_args(argv)
|
| 268 |
+
try:
|
| 269 |
+
raw = sys.stdin.buffer.read(MAX_INTERNAL_BYTES + 1)
|
| 270 |
+
require(len(raw) <= MAX_INTERNAL_BYTES, 'Internal request exceeds limit')
|
| 271 |
+
request = strict(raw)
|
| 272 |
+
with (patch('socket.socket', side_effect=RuntimeError('Offline worker forbids network')),
|
| 273 |
+
patch('socket.create_connection', side_effect=RuntimeError('Offline worker forbids network'))):
|
| 274 |
+
if request == {'action': 'describe'}:
|
| 275 |
+
_, descriptors = load_domain(args.environment)
|
| 276 |
+
state_validator(args.environment).validate(read(args.environment / 'state.json'))
|
| 277 |
+
value = {'tools': descriptors}
|
| 278 |
+
else:
|
| 279 |
+
require(type(request) is dict and set(request) == {'action', 'state', 'tool', 'arguments'}
|
| 280 |
+
and request['action'] == 'transition', 'Invalid internal request')
|
| 281 |
+
value = transition(args.environment, request['state'], request['tool'], request['arguments'],
|
| 282 |
+
max_observation_bytes=args.max_observation_bytes)
|
| 283 |
+
sys.stdout.buffer.write(canonical(value) + b'\n')
|
| 284 |
+
return 0
|
| 285 |
+
except Exception:
|
| 286 |
+
sys.stdout.buffer.write(canonical({'worker_error': 'RUNTIME_VALIDATION_FAILED'}) + b'\n')
|
| 287 |
+
return 1
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == '__main__':
|
| 291 |
+
raise SystemExit(main())
|
data/environments/eval60_gitlab/vendor/rfc3339_validator.LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2019, Nicolas Aimetti
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
data/environments/eval60_gitlab/vendor/rfc3339_validator.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Vendored 0.1.4; Python 3-only compatibility patch, see provenance.json.
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
__author__ = """Nicolas Aimetti"""
|
| 5 |
+
__email__ = 'naimetti@yahoo.com.ar'
|
| 6 |
+
__version__ = '0.1.4'
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
import calendar
|
| 10 |
+
|
| 11 |
+
RFC3339_REGEX_FLAGS = re.ASCII
|
| 12 |
+
|
| 13 |
+
RFC3339_REGEX = re.compile(r"""
|
| 14 |
+
^
|
| 15 |
+
(\d{4}) # Year
|
| 16 |
+
-
|
| 17 |
+
(0[1-9]|1[0-2]) # Month
|
| 18 |
+
-
|
| 19 |
+
(\d{2}) # Day
|
| 20 |
+
T
|
| 21 |
+
(?:[01]\d|2[0123]) # Hours
|
| 22 |
+
:
|
| 23 |
+
(?:[0-5]\d) # Minutes
|
| 24 |
+
:
|
| 25 |
+
(?:[0-5]\d) # Seconds
|
| 26 |
+
(?:\.\d+)? # Secfrac
|
| 27 |
+
(?: Z # UTC
|
| 28 |
+
| [+-](?:[01]\d|2[0123]):[0-5]\d # Offset
|
| 29 |
+
)
|
| 30 |
+
$
|
| 31 |
+
""", re.VERBOSE | RFC3339_REGEX_FLAGS)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def validate_rfc3339(date_string):
|
| 35 |
+
"""
|
| 36 |
+
Validates dates against RFC3339 datetime format
|
| 37 |
+
Leap seconds are no supported.
|
| 38 |
+
"""
|
| 39 |
+
m = RFC3339_REGEX.match(date_string)
|
| 40 |
+
if m is None:
|
| 41 |
+
return False
|
| 42 |
+
year, month, day = map(int, m.groups())
|
| 43 |
+
if not year:
|
| 44 |
+
# Year 0 is not valid a valid date
|
| 45 |
+
return False
|
| 46 |
+
(_, max_day) = calendar.monthrange(year, month)
|
| 47 |
+
if not 1 <= day <= max_day:
|
| 48 |
+
return False
|
| 49 |
+
return True
|
data/environments/eval60_inaturalist/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Manually curated evaluation environment."""
|
data/environments/eval60_inaturalist/domain/domain_tools.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
from datetime import date
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def _obj_schema(properties, required):
|
| 6 |
+
return {"type": "object", "properties": properties, "required": required, "additionalProperties": False}
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
TOOL_SCHEMAS = [
|
| 10 |
+
{
|
| 11 |
+
"name": "list_taxa",
|
| 12 |
+
"description": "List complete synthetic taxon-directory records. Query is a case-insensitive substring of scientific or common name; use an empty string for the full modest directory.",
|
| 13 |
+
"input_schema": _obj_schema({
|
| 14 |
+
"query": {"type": "string"},
|
| 15 |
+
"active_only": {"type": "boolean"}
|
| 16 |
+
}, ["query", "active_only"]),
|
| 17 |
+
"read_only": True
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"name": "list_places",
|
| 21 |
+
"description": "List complete synthetic place-directory records. Query is a case-insensitive substring of name or official code; use an empty string for all places.",
|
| 22 |
+
"input_schema": _obj_schema({"query": {"type": "string"}}, ["query"]),
|
| 23 |
+
"read_only": True
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"name": "search_observations",
|
| 27 |
+
"description": "Search complete synthetic observation records using observed local calendar dates. taxon_id can include descendants in the local taxon tree. Results are ordered by observation ID ascending. Photo records are separate resources referenced by photo_ids.",
|
| 28 |
+
"input_schema": _obj_schema({
|
| 29 |
+
"taxon_id": {"type": "integer", "minimum": 1},
|
| 30 |
+
"include_descendants": {"type": "boolean"},
|
| 31 |
+
"place_id": {"type": "integer", "minimum": 1},
|
| 32 |
+
"observed_on_or_after": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},
|
| 33 |
+
"observed_on_or_before": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},
|
| 34 |
+
"quality_grade": {"type": "string", "enum": ["research", "needs_id", "casual"]},
|
| 35 |
+
"captive": {"type": "boolean"},
|
| 36 |
+
"taxon_active": {"type": "boolean"}
|
| 37 |
+
}, ["taxon_id", "include_descendants", "place_id", "observed_on_or_after", "observed_on_or_before", "quality_grade", "captive", "taxon_active"]),
|
| 38 |
+
"read_only": True
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"name": "get_observation",
|
| 42 |
+
"description": "Get one complete synthetic observation by ID. This does not include separate photo-asset records.",
|
| 43 |
+
"input_schema": _obj_schema({"observation_id": {"type": "integer", "minimum": 1}}, ["observation_id"]),
|
| 44 |
+
"read_only": True
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"name": "list_photo_assets",
|
| 48 |
+
"description": "List complete synthetic photo-asset records for the supplied observation IDs. Returns an UNAVAILABLE error naming photo_asset_catalog when that catalog cannot be accessed. Empty input is allowed and returns an empty list.",
|
| 49 |
+
"input_schema": _obj_schema({
|
| 50 |
+
"observation_ids": {"type": "array", "items": {"type": "integer", "minimum": 1}, "uniqueItems": True}
|
| 51 |
+
}, ["observation_ids"]),
|
| 52 |
+
"read_only": True
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"name": "get_photo_asset",
|
| 56 |
+
"description": "Get one complete synthetic photo-asset record by photo ID. Returns an UNAVAILABLE error naming photo_asset_catalog when that catalog cannot be accessed.",
|
| 57 |
+
"input_schema": _obj_schema({"photo_id": {"type": "integer", "minimum": 1}}, ["photo_id"]),
|
| 58 |
+
"read_only": True
|
| 59 |
+
}
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _error(code, message, **extra):
|
| 64 |
+
error = {"code": code, "message": message}
|
| 65 |
+
error.update(extra)
|
| 66 |
+
return {"ok": False, "error": error}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _collection(rows):
|
| 70 |
+
return {"total": len(rows), "items": deepcopy(rows)}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _valid_date(value):
|
| 74 |
+
if not isinstance(value, str) or len(value) != 10 or value[4] != "-" or value[7] != "-":
|
| 75 |
+
return False
|
| 76 |
+
try:
|
| 77 |
+
year, month, day = [int(part) for part in value.split("-")]
|
| 78 |
+
date(year, month, day)
|
| 79 |
+
return True
|
| 80 |
+
except (TypeError, ValueError):
|
| 81 |
+
return False
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _check_args(name, arguments):
|
| 85 |
+
if not isinstance(arguments, dict):
|
| 86 |
+
return "arguments must be an object"
|
| 87 |
+
schema = None
|
| 88 |
+
for item in TOOL_SCHEMAS:
|
| 89 |
+
if item["name"] == name:
|
| 90 |
+
schema = item["input_schema"]
|
| 91 |
+
break
|
| 92 |
+
if schema is None:
|
| 93 |
+
return None
|
| 94 |
+
allowed = set(schema["properties"])
|
| 95 |
+
unknown = set(arguments) - allowed
|
| 96 |
+
if unknown:
|
| 97 |
+
return "unknown argument(s): " + ", ".join(sorted(unknown))
|
| 98 |
+
missing = set(schema["required"]) - set(arguments)
|
| 99 |
+
if missing:
|
| 100 |
+
return "missing argument(s): " + ", ".join(sorted(missing))
|
| 101 |
+
return None
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _find(records, resource_id):
|
| 105 |
+
for record in records:
|
| 106 |
+
if record.get("id") == resource_id:
|
| 107 |
+
return record
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _photo_available(state):
|
| 112 |
+
return bool(state.get("availability", {}).get("photo_asset_catalog"))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def call_tool(state, name, arguments):
|
| 116 |
+
names = {item["name"] for item in TOOL_SCHEMAS}
|
| 117 |
+
if name not in names:
|
| 118 |
+
return _error("UNKNOWN_TOOL", "Unknown tool: " + str(name))
|
| 119 |
+
problem = _check_args(name, arguments)
|
| 120 |
+
if problem:
|
| 121 |
+
return _error("INVALID_ARGUMENT", problem)
|
| 122 |
+
|
| 123 |
+
if name == "list_taxa":
|
| 124 |
+
query = arguments["query"]
|
| 125 |
+
active_only = arguments["active_only"]
|
| 126 |
+
if not isinstance(query, str) or not isinstance(active_only, bool):
|
| 127 |
+
return _error("INVALID_ARGUMENT", "query must be a string and active_only must be boolean")
|
| 128 |
+
folded = query.casefold()
|
| 129 |
+
rows = [
|
| 130 |
+
record for record in state.get("taxa", [])
|
| 131 |
+
if (not active_only or record.get("active") is True)
|
| 132 |
+
and (folded in record.get("scientific_name", "").casefold()
|
| 133 |
+
or folded in record.get("common_name", "").casefold())
|
| 134 |
+
]
|
| 135 |
+
return {"ok": True, "result": _collection(rows)}
|
| 136 |
+
|
| 137 |
+
if name == "list_places":
|
| 138 |
+
query = arguments["query"]
|
| 139 |
+
if not isinstance(query, str):
|
| 140 |
+
return _error("INVALID_ARGUMENT", "query must be a string")
|
| 141 |
+
folded = query.casefold()
|
| 142 |
+
rows = [
|
| 143 |
+
record for record in state.get("places", [])
|
| 144 |
+
if folded in record.get("name", "").casefold()
|
| 145 |
+
or folded in record.get("official_code", "").casefold()
|
| 146 |
+
]
|
| 147 |
+
return {"ok": True, "result": _collection(rows)}
|
| 148 |
+
|
| 149 |
+
if name == "get_observation":
|
| 150 |
+
observation_id = arguments["observation_id"]
|
| 151 |
+
if isinstance(observation_id, bool) or not isinstance(observation_id, int) or observation_id < 1:
|
| 152 |
+
return _error("INVALID_ARGUMENT", "observation_id must be a positive integer")
|
| 153 |
+
row = _find(state.get("observations", []), observation_id)
|
| 154 |
+
if row is None:
|
| 155 |
+
return _error("NOT_FOUND", "Observation not found", resource="observation:" + str(observation_id))
|
| 156 |
+
return {"ok": True, "result": deepcopy(row)}
|
| 157 |
+
|
| 158 |
+
if name == "search_observations":
|
| 159 |
+
args = arguments
|
| 160 |
+
if any(isinstance(args[key], bool) or not isinstance(args[key], int) or args[key] < 1
|
| 161 |
+
for key in ("taxon_id", "place_id")):
|
| 162 |
+
return _error("INVALID_ARGUMENT", "taxon_id and place_id must be positive integers")
|
| 163 |
+
for key in ("include_descendants", "captive", "taxon_active"):
|
| 164 |
+
if not isinstance(args[key], bool):
|
| 165 |
+
return _error("INVALID_ARGUMENT", key + " must be boolean")
|
| 166 |
+
if args["quality_grade"] not in ("research", "needs_id", "casual"):
|
| 167 |
+
return _error("INVALID_ARGUMENT", "invalid quality_grade")
|
| 168 |
+
if not _valid_date(args["observed_on_or_after"]) or not _valid_date(args["observed_on_or_before"]):
|
| 169 |
+
return _error("INVALID_ARGUMENT", "date filters must be valid YYYY-MM-DD dates")
|
| 170 |
+
if args["observed_on_or_after"] > args["observed_on_or_before"]:
|
| 171 |
+
return _error("INVALID_ARGUMENT", "date lower bound is after upper bound")
|
| 172 |
+
if _find(state.get("taxa", []), args["taxon_id"]) is None:
|
| 173 |
+
return _error("NOT_FOUND", "Taxon not found", resource="taxon:" + str(args["taxon_id"]))
|
| 174 |
+
if _find(state.get("places", []), args["place_id"]) is None:
|
| 175 |
+
return _error("NOT_FOUND", "Place not found", resource="place:" + str(args["place_id"]))
|
| 176 |
+
|
| 177 |
+
allowed_taxa = {args["taxon_id"]}
|
| 178 |
+
if args["include_descendants"]:
|
| 179 |
+
changed = True
|
| 180 |
+
while changed:
|
| 181 |
+
changed = False
|
| 182 |
+
for taxon in state.get("taxa", []):
|
| 183 |
+
if taxon.get("parent_id") in allowed_taxa and taxon.get("id") not in allowed_taxa:
|
| 184 |
+
allowed_taxa.add(taxon["id"])
|
| 185 |
+
changed = True
|
| 186 |
+
|
| 187 |
+
taxa_by_id = {taxon["id"]: taxon for taxon in state.get("taxa", [])}
|
| 188 |
+
rows = []
|
| 189 |
+
for record in state.get("observations", []):
|
| 190 |
+
assigned_taxon = taxa_by_id.get(record.get("taxon_id"), {})
|
| 191 |
+
if (record.get("taxon_id") in allowed_taxa
|
| 192 |
+
and record.get("place_id") == args["place_id"]
|
| 193 |
+
and args["observed_on_or_after"] <= record.get("observed_on", "") <= args["observed_on_or_before"]
|
| 194 |
+
and record.get("quality_grade") == args["quality_grade"]
|
| 195 |
+
and record.get("captive") is args["captive"]
|
| 196 |
+
and assigned_taxon.get("active") is args["taxon_active"]):
|
| 197 |
+
rows.append(record)
|
| 198 |
+
rows.sort(key=lambda record: record["id"])
|
| 199 |
+
return {"ok": True, "result": _collection(rows)}
|
| 200 |
+
|
| 201 |
+
if name in ("list_photo_assets", "get_photo_asset"):
|
| 202 |
+
# Validate request shape and types before testing backend availability.
|
| 203 |
+
if name == "get_photo_asset":
|
| 204 |
+
ident = arguments.get("photo_id")
|
| 205 |
+
if type(ident) is not int or ident < 1:
|
| 206 |
+
return _error("INVALID_ARGUMENT", "photo_id must be a positive integer")
|
| 207 |
+
else:
|
| 208 |
+
ids = arguments.get("observation_ids")
|
| 209 |
+
if not isinstance(ids, list) or any(type(x) is not int or x < 1 for x in ids) or len(ids) != len(set(ids)):
|
| 210 |
+
return _error("INVALID_ARGUMENT", "observation_ids must be unique positive integers")
|
| 211 |
+
if not _photo_available(state):
|
| 212 |
+
return _error("UNAVAILABLE", "The photo asset catalog is unavailable", resource="photo_asset_catalog")
|
| 213 |
+
photos = state.get("photo_assets", [])
|
| 214 |
+
|
| 215 |
+
if name == "get_photo_asset":
|
| 216 |
+
photo_id = arguments["photo_id"]
|
| 217 |
+
if isinstance(photo_id, bool) or not isinstance(photo_id, int) or photo_id < 1:
|
| 218 |
+
return _error("INVALID_ARGUMENT", "photo_id must be a positive integer")
|
| 219 |
+
row = _find(photos, photo_id)
|
| 220 |
+
if row is None:
|
| 221 |
+
return _error("NOT_FOUND", "Photo asset not found", resource="photo_asset:" + str(photo_id))
|
| 222 |
+
return {"ok": True, "result": deepcopy(row)}
|
| 223 |
+
|
| 224 |
+
observation_ids = arguments["observation_ids"]
|
| 225 |
+
if (not isinstance(observation_ids, list)
|
| 226 |
+
or any(isinstance(value, bool) or not isinstance(value, int) or value < 1
|
| 227 |
+
for value in observation_ids)
|
| 228 |
+
or len(observation_ids) != len(set(observation_ids))):
|
| 229 |
+
return _error("INVALID_ARGUMENT", "observation_ids must be unique positive integers")
|
| 230 |
+
known = {record["id"] for record in state.get("observations", [])}
|
| 231 |
+
unknown = [value for value in observation_ids if value not in known]
|
| 232 |
+
if unknown:
|
| 233 |
+
return _error("NOT_FOUND", "Observation not found", resource="observation:" + str(unknown[0]))
|
| 234 |
+
wanted = set(observation_ids)
|
| 235 |
+
rows = [photo for photo in photos if photo.get("observation_id") in wanted]
|
| 236 |
+
rows.sort(key=lambda photo: (photo["observation_id"], photo["position"], photo["id"]))
|
| 237 |
+
return {"ok": True, "result": _collection(rows)}
|
| 238 |
+
|
| 239 |
+
return _error("UNKNOWN_TOOL", "Unknown tool: " + str(name))
|
data/environments/eval60_inaturalist/environment.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Official tool adapter to the exact sealed transaction runtime."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import copy
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import threading
|
| 10 |
+
from typing import Any, Callable
|
| 11 |
+
|
| 12 |
+
from fastmcp.tools import Tool
|
| 13 |
+
from fastmcp.tools.tool import ToolResult
|
| 14 |
+
from pydantic import Field
|
| 15 |
+
from hera_environment import BaseEnvironment, ToolError
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parent
|
| 18 |
+
_spec = importlib.util.spec_from_file_location(__name__ + '_runtime', ROOT/'runtime.py')
|
| 19 |
+
support = importlib.util.module_from_spec(_spec)
|
| 20 |
+
_spec.loader.exec_module(support)
|
| 21 |
+
STATE_SCHEMA = json.loads('{"type": "object"}')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _DomainTool(Tool):
|
| 25 |
+
fn: Callable[..., Any] = Field(exclude=True)
|
| 26 |
+
|
| 27 |
+
async def run(self, arguments: dict[str, Any]) -> ToolResult:
|
| 28 |
+
envelope = self.fn(**arguments)
|
| 29 |
+
return ToolResult(content=json.dumps(envelope,ensure_ascii=False,allow_nan=False),
|
| 30 |
+
structured_content=envelope,is_error=envelope['ok'] is False)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Environment(BaseEnvironment):
|
| 34 |
+
env_name = 'eval60_inaturalist'
|
| 35 |
+
short_name = 'iNaturalist'
|
| 36 |
+
always_skip_fields = set()
|
| 37 |
+
mutation_tools = set()
|
| 38 |
+
mutation_id_fields = set()
|
| 39 |
+
tool_kinds = json.loads('{"get_observation": "lookup", "get_photo_asset": "lookup", "list_photo_assets": "lookup", "list_places": "lookup", "list_taxa": "lookup", "search_observations": "lookup"}')
|
| 40 |
+
_descriptors = json.loads('[{"description": "List complete synthetic taxon-directory records. Query is a case-insensitive substring of scientific or common name; use an empty string for the full modest directory.", "input_schema": {"additionalProperties": false, "properties": {"active_only": {"type": "boolean"}, "query": {"type": "string"}}, "required": ["query", "active_only"], "type": "object"}, "name": "list_taxa", "read_only": true}, {"description": "List complete synthetic place-directory records. Query is a case-insensitive substring of name or official code; use an empty string for all places.", "input_schema": {"additionalProperties": false, "properties": {"query": {"type": "string"}}, "required": ["query"], "type": "object"}, "name": "list_places", "read_only": true}, {"description": "Search complete synthetic observation records using observed local calendar dates. taxon_id can include descendants in the local taxon tree. Results are ordered by observation ID ascending. Photo records are separate resources referenced by photo_ids.", "input_schema": {"additionalProperties": false, "properties": {"captive": {"type": "boolean"}, "include_descendants": {"type": "boolean"}, "observed_on_or_after": {"pattern": "^\\\\d{4}-\\\\d{2}-\\\\d{2}$", "type": "string"}, "observed_on_or_before": {"pattern": "^\\\\d{4}-\\\\d{2}-\\\\d{2}$", "type": "string"}, "place_id": {"minimum": 1, "type": "integer"}, "quality_grade": {"enum": ["research", "needs_id", "casual"], "type": "string"}, "taxon_active": {"type": "boolean"}, "taxon_id": {"minimum": 1, "type": "integer"}}, "required": ["taxon_id", "include_descendants", "place_id", "observed_on_or_after", "observed_on_or_before", "quality_grade", "captive", "taxon_active"], "type": "object"}, "name": "search_observations", "read_only": true}, {"description": "Get one complete synthetic observation by ID. This does not include separate photo-asset records.", "input_schema": {"additionalProperties": false, "properties": {"observation_id": {"minimum": 1, "type": "integer"}}, "required": ["observation_id"], "type": "object"}, "name": "get_observation", "read_only": true}, {"description": "List complete synthetic photo-asset records for the supplied observation IDs. Returns an UNAVAILABLE error naming photo_asset_catalog when that catalog cannot be accessed. Empty input is allowed and returns an empty list.", "input_schema": {"additionalProperties": false, "properties": {"observation_ids": {"items": {"minimum": 1, "type": "integer"}, "type": "array", "uniqueItems": true}}, "required": ["observation_ids"], "type": "object"}, "name": "list_photo_assets", "read_only": true}, {"description": "Get one complete synthetic photo-asset record by photo ID. Returns an UNAVAILABLE error naming photo_asset_catalog when that catalog cannot be accessed.", "input_schema": {"additionalProperties": false, "properties": {"photo_id": {"minimum": 1, "type": "integer"}}, "required": ["photo_id"], "type": "object"}, "name": "get_photo_asset", "read_only": true}]')
|
| 41 |
+
|
| 42 |
+
def _load_state(self, initial_state):
|
| 43 |
+
support.validator(STATE_SCHEMA).validate(initial_state)
|
| 44 |
+
return copy.deepcopy(initial_state)
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def get_empty_state(cls):return {}
|
| 48 |
+
|
| 49 |
+
@classmethod
|
| 50 |
+
def get_example_state(cls):return {}
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def get_state_schema(cls):return copy.deepcopy(STATE_SCHEMA)
|
| 54 |
+
|
| 55 |
+
def _register_tools(self):
|
| 56 |
+
self._transaction_lock = threading.Lock()
|
| 57 |
+
self._transport_attempts = []
|
| 58 |
+
_, actual = support.load_domain(ROOT/'domain')
|
| 59 |
+
if support.canonical(actual) != support.canonical(self._descriptors):
|
| 60 |
+
raise ValueError('Public tool descriptors differ from the sealed domain')
|
| 61 |
+
for item in self._descriptors:
|
| 62 |
+
def bind(name):
|
| 63 |
+
def call(**arguments):return self._invoke_domain(name,arguments)
|
| 64 |
+
return call
|
| 65 |
+
output = None
|
| 66 |
+
if 'output_schema' in item:
|
| 67 |
+
output={'type':'object','oneOf':[
|
| 68 |
+
{'type':'object','required':['ok','result'],'additionalProperties':False,
|
| 69 |
+
'properties':{'ok':{'const':True},'result':copy.deepcopy(item['output_schema'])}},
|
| 70 |
+
{'type':'object','required':['ok','error'],'additionalProperties':False,
|
| 71 |
+
'properties':{'ok':{'const':False},'error':{'type':'object','required':['code','message'],
|
| 72 |
+
'properties':{'code':{'type':'string','minLength':1},'message':{'type':'string'}}}}}]}
|
| 73 |
+
self.mcp.add_tool(_DomainTool(name=item['name'],description=item['description'],
|
| 74 |
+
parameters=copy.deepcopy(item['input_schema']),output_schema=output,fn=bind(item['name'])))
|
| 75 |
+
|
| 76 |
+
def _invoke_domain(self, name, arguments):
|
| 77 |
+
with self._transaction_lock:
|
| 78 |
+
before = copy.deepcopy(self.state)
|
| 79 |
+
if len(support.canonical({'tool':name,'arguments':arguments})) > 32768:
|
| 80 |
+
raise ToolError('PUBLIC_REQUEST_LIMIT')
|
| 81 |
+
request = {'action':'transition','state':before,'tool':name,'arguments':arguments}
|
| 82 |
+
try:
|
| 83 |
+
process = subprocess.run([sys.executable,'-I','-B',str(ROOT/'runtime.py'),
|
| 84 |
+
'--environment',str(ROOT/'domain'),'--max-observation-bytes','32768'],
|
| 85 |
+
input=support.canonical(request),capture_output=True,timeout=120,
|
| 86 |
+
cwd=str(ROOT),env={'PATH':'/usr/bin:/bin','PYTHONDONTWRITEBYTECODE':'1'})
|
| 87 |
+
result = support.strict(process.stdout)
|
| 88 |
+
if process.returncode or set(result) != {'state','observation','dispatched'}:
|
| 89 |
+
raise ValueError('Transaction worker failed')
|
| 90 |
+
observation = result['observation']
|
| 91 |
+
support.canonical(observation)
|
| 92 |
+
self.state = copy.deepcopy(result['state'])
|
| 93 |
+
except Exception as exc:
|
| 94 |
+
self.state = before
|
| 95 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 96 |
+
'observation':None,'dispatched':None,'error':'TRANSACTION_INFRASTRUCTURE_ERROR'})
|
| 97 |
+
raise ToolError('TRANSACTION_INFRASTRUCTURE_ERROR') from exc
|
| 98 |
+
error = None if observation['ok'] else json.dumps(observation['error'],ensure_ascii=False)
|
| 99 |
+
self._transport_attempts.append({'tool':name,'arguments':copy.deepcopy(arguments),
|
| 100 |
+
'observation':copy.deepcopy(observation),'dispatched':result['dispatched']})
|
| 101 |
+
# Keep the semantic event stream identical to controller.public.
|
| 102 |
+
# Rejected pre-dispatch requests remain attempts but cannot count
|
| 103 |
+
# as observed domain evidence. MCP may itself reject extra keys
|
| 104 |
+
# before this adapter; that is a transport error, not a domain event.
|
| 105 |
+
if result['dispatched']:
|
| 106 |
+
self._log_tool_call(name,copy.deepcopy(arguments),copy.deepcopy(observation),
|
| 107 |
+
success=observation['ok'],error=error)
|
| 108 |
+
return observation
|