agentsml-impl 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentsml_impl/__init__.py +3 -0
- agentsml_impl/cli.py +472 -0
- agentsml_impl/compiler/__init__.py +1 -0
- agentsml_impl/compiler/capabilities.py +330 -0
- agentsml_impl/compiler/conditions.py +177 -0
- agentsml_impl/compiler/diagnostics.py +112 -0
- agentsml_impl/compiler/durations.py +31 -0
- agentsml_impl/compiler/expressions.py +123 -0
- agentsml_impl/compiler/identifiers.py +60 -0
- agentsml_impl/compiler/ir.py +391 -0
- agentsml_impl/compiler/limits.py +28 -0
- agentsml_impl/compiler/loader.py +83 -0
- agentsml_impl/compiler/naming.py +87 -0
- agentsml_impl/compiler/planner.py +79 -0
- agentsml_impl/compiler/render.py +90 -0
- agentsml_impl/compiler/schema_validation.py +121 -0
- agentsml_impl/compiler/semantic_validation.py +424 -0
- agentsml_impl/protocols/__init__.py +1 -0
- agentsml_impl/runtime/__init__.py +1 -0
- agentsml_impl/runtime/events.py +59 -0
- agentsml_impl/runtime/json_schema.py +138 -0
- agentsml_impl/runtime/tools.py +145 -0
- agentsml_impl/schemas/agentsml.schema.json +406 -0
- agentsml_impl/schemas/v0.1/agentsml.schema.json +628 -0
- agentsml_impl/schemas/v0.2/agentsml.schema.json +363 -0
- agentsml_impl/schemas/v0.3/agentsml.schema.json +406 -0
- agentsml_impl/targets/__init__.py +1 -0
- agentsml_impl/targets/a2a/__init__.py +0 -0
- agentsml_impl/targets/a2a/adapter.py +94 -0
- agentsml_impl/targets/a2a/capabilities.yaml +25 -0
- agentsml_impl/targets/ag2/__init__.py +0 -0
- agentsml_impl/targets/ag2/adapter.py +655 -0
- agentsml_impl/targets/ag2/capabilities.yaml +37 -0
- agentsml_impl/targets/ag_ui/__init__.py +0 -0
- agentsml_impl/targets/ag_ui/adapter.py +123 -0
- agentsml_impl/targets/ag_ui/capabilities.yaml +25 -0
- agentsml_impl/targets/agno/__init__.py +0 -0
- agentsml_impl/targets/agno/adapter.py +191 -0
- agentsml_impl/targets/agno/capabilities.yaml +26 -0
- agentsml_impl/targets/ap2/__init__.py +0 -0
- agentsml_impl/targets/ap2/adapter.py +84 -0
- agentsml_impl/targets/ap2/capabilities.yaml +25 -0
- agentsml_impl/targets/base.py +157 -0
- agentsml_impl/targets/bedrock_agentcore/__init__.py +0 -0
- agentsml_impl/targets/bedrock_agentcore/adapter.py +592 -0
- agentsml_impl/targets/bedrock_agentcore/capabilities.yaml +26 -0
- agentsml_impl/targets/claude_agent_sdk/__init__.py +0 -0
- agentsml_impl/targets/claude_agent_sdk/adapter.py +178 -0
- agentsml_impl/targets/claude_agent_sdk/capabilities.yaml +26 -0
- agentsml_impl/targets/crewai/__init__.py +0 -0
- agentsml_impl/targets/crewai/adapter.py +441 -0
- agentsml_impl/targets/crewai/capabilities.yaml +30 -0
- agentsml_impl/targets/databricks/__init__.py +0 -0
- agentsml_impl/targets/databricks/adapter.py +427 -0
- agentsml_impl/targets/databricks/capabilities.yaml +26 -0
- agentsml_impl/targets/flowise/__init__.py +0 -0
- agentsml_impl/targets/flowise/adapter.py +71 -0
- agentsml_impl/targets/flowise/capabilities.yaml +26 -0
- agentsml_impl/targets/google_adk/__init__.py +0 -0
- agentsml_impl/targets/google_adk/adapter.py +589 -0
- agentsml_impl/targets/google_adk/capabilities.yaml +36 -0
- agentsml_impl/targets/langchain/__init__.py +1 -0
- agentsml_impl/targets/langchain/adapter.py +351 -0
- agentsml_impl/targets/langchain/capabilities.yaml +30 -0
- agentsml_impl/targets/langflow/__init__.py +0 -0
- agentsml_impl/targets/langflow/adapter.py +147 -0
- agentsml_impl/targets/langflow/capabilities.yaml +26 -0
- agentsml_impl/targets/langgraph/__init__.py +0 -0
- agentsml_impl/targets/langgraph/adapter.py +911 -0
- agentsml_impl/targets/langgraph/capabilities.yaml +33 -0
- agentsml_impl/targets/llamaindex/__init__.py +1 -0
- agentsml_impl/targets/llamaindex/adapter.py +406 -0
- agentsml_impl/targets/llamaindex/capabilities.yaml +31 -0
- agentsml_impl/targets/lyzr/__init__.py +0 -0
- agentsml_impl/targets/lyzr/adapter.py +146 -0
- agentsml_impl/targets/lyzr/capabilities.yaml +26 -0
- agentsml_impl/targets/mastra/__init__.py +0 -0
- agentsml_impl/targets/mastra/adapter.py +635 -0
- agentsml_impl/targets/mastra/capabilities.yaml +32 -0
- agentsml_impl/targets/mcp_server/__init__.py +0 -0
- agentsml_impl/targets/mcp_server/adapter.py +141 -0
- agentsml_impl/targets/mcp_server/capabilities.yaml +25 -0
- agentsml_impl/targets/microsoft_agent_framework/__init__.py +0 -0
- agentsml_impl/targets/microsoft_agent_framework/adapter.py +563 -0
- agentsml_impl/targets/microsoft_agent_framework/capabilities.yaml +26 -0
- agentsml_impl/targets/n8n/__init__.py +0 -0
- agentsml_impl/targets/n8n/adapter.py +139 -0
- agentsml_impl/targets/n8n/capabilities.yaml +26 -0
- agentsml_impl/targets/openai_agents/__init__.py +0 -0
- agentsml_impl/targets/openai_agents/adapter.py +175 -0
- agentsml_impl/targets/openai_agents/capabilities.yaml +27 -0
- agentsml_impl/targets/pydantic_ai/__init__.py +0 -0
- agentsml_impl/targets/pydantic_ai/adapter.py +922 -0
- agentsml_impl/targets/pydantic_ai/capabilities.yaml +37 -0
- agentsml_impl/targets/registry.py +290 -0
- agentsml_impl/targets/relevance_ai/__init__.py +0 -0
- agentsml_impl/targets/relevance_ai/adapter.py +66 -0
- agentsml_impl/targets/relevance_ai/capabilities.yaml +26 -0
- agentsml_impl/targets/smolagents/__init__.py +0 -0
- agentsml_impl/targets/smolagents/adapter.py +210 -0
- agentsml_impl/targets/smolagents/capabilities.yaml +27 -0
- agentsml_impl/targets/snowflake_cortex/__init__.py +0 -0
- agentsml_impl/targets/snowflake_cortex/adapter.py +167 -0
- agentsml_impl/targets/snowflake_cortex/capabilities.yaml +26 -0
- agentsml_impl/targets/spring_ai/__init__.py +1 -0
- agentsml_impl/targets/spring_ai/adapter.py +626 -0
- agentsml_impl/targets/spring_ai/capabilities.yaml +31 -0
- agentsml_impl/targets/strands_agents/__init__.py +1 -0
- agentsml_impl/targets/strands_agents/adapter.py +309 -0
- agentsml_impl/targets/strands_agents/capabilities.yaml +29 -0
- agentsml_impl/targets/support_matrix.py +91 -0
- agentsml_impl/targets/ucp/__init__.py +0 -0
- agentsml_impl/targets/ucp/adapter.py +86 -0
- agentsml_impl/targets/ucp/capabilities.yaml +25 -0
- agentsml_impl/targets/vercel_ai/__init__.py +1 -0
- agentsml_impl/targets/vercel_ai/adapter.py +349 -0
- agentsml_impl/targets/vercel_ai/capabilities.yaml +30 -0
- agentsml_impl/targets/vertex_agent_engine/__init__.py +0 -0
- agentsml_impl/targets/vertex_agent_engine/adapter.py +407 -0
- agentsml_impl/targets/vertex_agent_engine/capabilities.yaml +26 -0
- agentsml_impl/targets/zapier_agents/__init__.py +0 -0
- agentsml_impl/targets/zapier_agents/adapter.py +106 -0
- agentsml_impl/targets/zapier_agents/capabilities.yaml +26 -0
- agentsml_impl-0.2.0.dist-info/METADATA +109 -0
- agentsml_impl-0.2.0.dist-info/RECORD +129 -0
- agentsml_impl-0.2.0.dist-info/WHEEL +5 -0
- agentsml_impl-0.2.0.dist-info/entry_points.txt +3 -0
- agentsml_impl-0.2.0.dist-info/licenses/LICENSE +28 -0
- agentsml_impl-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Target-language identifier helpers for generated source."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import keyword
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Callable, Iterable
|
|
8
|
+
|
|
9
|
+
_JAVA_KEYWORDS = {
|
|
10
|
+
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char",
|
|
11
|
+
"class", "const", "continue", "default", "do", "double", "else", "enum",
|
|
12
|
+
"extends", "final", "finally", "float", "for", "goto", "if", "implements",
|
|
13
|
+
"import", "instanceof", "int", "interface", "long", "native", "new",
|
|
14
|
+
"package", "private", "protected", "public", "return", "short", "static",
|
|
15
|
+
"strictfp", "super", "switch", "synchronized", "this", "throw", "throws",
|
|
16
|
+
"transient", "try", "void", "volatile", "while",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
_JS_KEYWORDS = {
|
|
20
|
+
"await", "break", "case", "catch", "class", "const", "continue", "debugger",
|
|
21
|
+
"default", "delete", "do", "else", "enum", "export", "extends", "false",
|
|
22
|
+
"finally", "for", "function", "if", "implements", "import", "in",
|
|
23
|
+
"instanceof", "interface", "let", "new", "null", "package", "private",
|
|
24
|
+
"protected", "public", "return", "static", "super", "switch", "this",
|
|
25
|
+
"throw", "true", "try", "typeof", "var", "void", "while", "with", "yield",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def snake_identifier(value: str, *, prefix: str = "value") -> str:
|
|
30
|
+
result = _words_to_snake(value)
|
|
31
|
+
if not result or result[0].isdigit():
|
|
32
|
+
result = f"{prefix}_{result}" if result else prefix
|
|
33
|
+
if keyword.iskeyword(result):
|
|
34
|
+
result += "_"
|
|
35
|
+
return result
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def pascal_identifier(value: str, *, prefix: str = "Generated") -> str:
|
|
39
|
+
words = _words(value)
|
|
40
|
+
result = "".join(word[:1].upper() + word[1:] for word in words)
|
|
41
|
+
if not result or result[0].isdigit():
|
|
42
|
+
result = prefix + result
|
|
43
|
+
return result
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def camel_identifier(value: str, *, prefix: str = "value", language: str = "javascript") -> str:
|
|
47
|
+
words = _words(value)
|
|
48
|
+
if words:
|
|
49
|
+
result = words[0].lower() + "".join(word[:1].upper() + word[1:] for word in words[1:])
|
|
50
|
+
else:
|
|
51
|
+
result = prefix
|
|
52
|
+
if result[0].isdigit():
|
|
53
|
+
result = prefix + result[:1].upper() + result[1:]
|
|
54
|
+
reserved = _JAVA_KEYWORDS if language == "java" else _JS_KEYWORDS
|
|
55
|
+
if result in reserved:
|
|
56
|
+
result += "Value"
|
|
57
|
+
return result
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def unique_identifiers(
|
|
61
|
+
values: Iterable[str],
|
|
62
|
+
transform: Callable[[str], str],
|
|
63
|
+
*,
|
|
64
|
+
separator: str = "_",
|
|
65
|
+
) -> dict[str, str]:
|
|
66
|
+
"""Return deterministic, collision-free identifiers for raw names."""
|
|
67
|
+
result: dict[str, str] = {}
|
|
68
|
+
used: set[str] = set()
|
|
69
|
+
for value in values:
|
|
70
|
+
base = transform(value)
|
|
71
|
+
candidate = base
|
|
72
|
+
suffix = 2
|
|
73
|
+
while candidate in used:
|
|
74
|
+
candidate = f"{base}{separator}{suffix}"
|
|
75
|
+
suffix += 1
|
|
76
|
+
result[value] = candidate
|
|
77
|
+
used.add(candidate)
|
|
78
|
+
return result
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _words_to_snake(value: str) -> str:
|
|
82
|
+
return "_".join(word.lower() for word in _words(value))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _words(value: str) -> list[str]:
|
|
86
|
+
split_camel = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", value)
|
|
87
|
+
return [part for part in re.split(r"[^A-Za-z0-9]+", split_camel) if part]
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""CORE-008: Generation Planner — produce a target-independent plan before rendering."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from agentsml_impl.compiler.ir import AgentSystemIR, WorkflowIR
|
|
9
|
+
from agentsml_impl.compiler.diagnostics import DiagnosticSet
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _sanitize_name(name: str) -> str:
|
|
13
|
+
"""Convert an AgentsML metadata name to a safe Python/TS package name."""
|
|
14
|
+
s = name.lower()
|
|
15
|
+
s = re.sub(r"[^a-z0-9_]", "_", s)
|
|
16
|
+
s = re.sub(r"_+", "_", s)
|
|
17
|
+
s = s.strip("_")
|
|
18
|
+
if s and s[0].isdigit():
|
|
19
|
+
s = "agent_" + s
|
|
20
|
+
return s or "agentsml_agent"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class GenerationPlan:
|
|
25
|
+
project_name: str
|
|
26
|
+
package_name: str
|
|
27
|
+
target: str
|
|
28
|
+
main_workflow_key: str
|
|
29
|
+
all_workflow_keys: list[str]
|
|
30
|
+
agent_keys: list[str]
|
|
31
|
+
tool_keys: list[str]
|
|
32
|
+
artifact_list: list[str] = field(default_factory=list)
|
|
33
|
+
has_mcp: bool = False
|
|
34
|
+
has_a2a: bool = False
|
|
35
|
+
has_approvals: bool = False
|
|
36
|
+
has_cycles: bool = False
|
|
37
|
+
has_edges: bool = False
|
|
38
|
+
profiles: list[str] = field(default_factory=list)
|
|
39
|
+
metadata_version: Optional[str] = None
|
|
40
|
+
description: Optional[str] = None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def build_plan(ir: AgentSystemIR, target: str, diagnostics: DiagnosticSet) -> GenerationPlan:
|
|
44
|
+
"""Build a GenerationPlan from the IR for a given target."""
|
|
45
|
+
project_name = ir.metadata.name
|
|
46
|
+
package_name = _sanitize_name(project_name)
|
|
47
|
+
|
|
48
|
+
# Select main workflow
|
|
49
|
+
workflow_keys = list(ir.workflows.keys())
|
|
50
|
+
if "main" in ir.workflows:
|
|
51
|
+
main_wf_key = "main"
|
|
52
|
+
elif workflow_keys:
|
|
53
|
+
main_wf_key = workflow_keys[0]
|
|
54
|
+
else:
|
|
55
|
+
main_wf_key = ""
|
|
56
|
+
|
|
57
|
+
has_mcp = any(t.is_mcp() for t in ir.tools.values()) or bool(ir.mcp_servers)
|
|
58
|
+
has_a2a = bool(ir.a2a_agents)
|
|
59
|
+
has_approvals = any(step.approval for wf in ir.workflows.values() for step in wf.steps)
|
|
60
|
+
has_cycles = any(wf.has_cycles() for wf in ir.workflows.values())
|
|
61
|
+
has_edges = any(wf.edges for wf in ir.workflows.values())
|
|
62
|
+
|
|
63
|
+
return GenerationPlan(
|
|
64
|
+
project_name=project_name,
|
|
65
|
+
package_name=package_name,
|
|
66
|
+
target=target,
|
|
67
|
+
main_workflow_key=main_wf_key,
|
|
68
|
+
all_workflow_keys=workflow_keys,
|
|
69
|
+
agent_keys=list(ir.agents.keys()),
|
|
70
|
+
tool_keys=list(ir.tools.keys()),
|
|
71
|
+
has_mcp=has_mcp,
|
|
72
|
+
has_a2a=has_a2a,
|
|
73
|
+
has_approvals=has_approvals,
|
|
74
|
+
has_cycles=has_cycles,
|
|
75
|
+
has_edges=has_edges,
|
|
76
|
+
profiles=ir.profiles.all_profiles(),
|
|
77
|
+
metadata_version=ir.metadata.version,
|
|
78
|
+
description=ir.metadata.description,
|
|
79
|
+
)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""CORE-009: Template Renderer and File Writer — Jinja2-based safe rendering."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
import json
|
|
5
|
+
import shutil
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Optional
|
|
8
|
+
|
|
9
|
+
import jinja2
|
|
10
|
+
|
|
11
|
+
_TEMPLATES_ROOT = Path(__file__).parent.parent / "templates"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _get_env(extra_templates_dir: Optional[Path] = None) -> jinja2.Environment:
|
|
15
|
+
"""Build a Jinja2 environment with package templates."""
|
|
16
|
+
loaders: list[jinja2.BaseLoader] = []
|
|
17
|
+
if extra_templates_dir and extra_templates_dir.exists():
|
|
18
|
+
loaders.append(jinja2.FileSystemLoader(str(extra_templates_dir)))
|
|
19
|
+
loaders.append(jinja2.FileSystemLoader(str(_TEMPLATES_ROOT)))
|
|
20
|
+
loader = jinja2.ChoiceLoader(loaders)
|
|
21
|
+
env = jinja2.Environment(loader=loader, autoescape=False, keep_trailing_newline=True)
|
|
22
|
+
env.globals["zip"] = zip
|
|
23
|
+
return env
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def render_template(
|
|
27
|
+
template_name: str,
|
|
28
|
+
context: dict[str, Any],
|
|
29
|
+
extra_templates_dir: Optional[Path] = None,
|
|
30
|
+
) -> str:
|
|
31
|
+
"""Render a Jinja2 template by name to a string."""
|
|
32
|
+
env = _get_env(extra_templates_dir)
|
|
33
|
+
try:
|
|
34
|
+
tpl = env.get_template(template_name)
|
|
35
|
+
except jinja2.TemplateNotFound:
|
|
36
|
+
raise FileNotFoundError(f"Template not found: {template_name}")
|
|
37
|
+
return tpl.render(**context)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def render_string(template_str: str, context: dict[str, Any]) -> str:
|
|
41
|
+
"""Render a Jinja2 template from a raw string."""
|
|
42
|
+
env = jinja2.Environment(autoescape=False, keep_trailing_newline=True)
|
|
43
|
+
env.globals["zip"] = zip
|
|
44
|
+
tpl = env.from_string(template_str)
|
|
45
|
+
return tpl.render(**context)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _safe_output_path(out_dir: Path, relative: str) -> Path:
|
|
49
|
+
"""Resolve and verify output path does not escape out_dir."""
|
|
50
|
+
out_path = (out_dir / relative).resolve()
|
|
51
|
+
if not str(out_path).startswith(str(out_dir.resolve())):
|
|
52
|
+
raise PermissionError(f"Output path escape detected: {relative!r} -> {out_path}")
|
|
53
|
+
return out_path
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def write_file(out_dir: Path, relative_path: str, content: str, overwrite: bool = True) -> Path:
|
|
57
|
+
"""Write content to a file under out_dir, creating parent dirs as needed."""
|
|
58
|
+
dest = _safe_output_path(out_dir, relative_path)
|
|
59
|
+
if dest.exists() and not overwrite:
|
|
60
|
+
return dest
|
|
61
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
62
|
+
dest.write_text(content, encoding="utf-8")
|
|
63
|
+
return dest
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def toml_string(value: str) -> str:
|
|
67
|
+
"""Return a valid TOML basic string literal for ``value``.
|
|
68
|
+
|
|
69
|
+
JSON string escaping is a subset of TOML basic-string escaping, so this keeps
|
|
70
|
+
multi-line descriptions and quotes from producing an invalid TOML file.
|
|
71
|
+
"""
|
|
72
|
+
return json.dumps(value, ensure_ascii=False)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def copy_file(out_dir: Path, relative_path: str, source: Path, overwrite: bool = True) -> Path:
|
|
76
|
+
"""Copy a source file to out_dir/relative_path."""
|
|
77
|
+
dest = _safe_output_path(out_dir, relative_path)
|
|
78
|
+
if dest.exists() and not overwrite:
|
|
79
|
+
return dest
|
|
80
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
81
|
+
shutil.copy2(source, dest)
|
|
82
|
+
return dest
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def plan_files(
|
|
86
|
+
files: dict[str, str],
|
|
87
|
+
out_dir: Path,
|
|
88
|
+
) -> list[tuple[str, Path]]:
|
|
89
|
+
"""Return a list of (relative_path, resolved_path) without writing. Dry-run support."""
|
|
90
|
+
return [(rel, _safe_output_path(out_dir, rel)) for rel in files]
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""CORE-002: JSON Schema Validation — validate AgentsML YAML against the public schema."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import jsonschema
|
|
10
|
+
import jsonschema.validators
|
|
11
|
+
|
|
12
|
+
from agentsml_impl.compiler.diagnostics import DiagCode, DiagnosticSet, Severity
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# Bundled package schemas directory and repository schemas directory.
|
|
16
|
+
_BUNDLED_SCHEMAS_DIR = Path(__file__).parent.parent / "schemas"
|
|
17
|
+
_REPO_SCHEMAS_DIR = (
|
|
18
|
+
Path(__file__).parent.parent.parent.parent.parent / "agentsml" / "schemas"
|
|
19
|
+
)
|
|
20
|
+
_DEFAULT_SCHEMA_PATH = _REPO_SCHEMAS_DIR / "agentsml.schema.json"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def resolve_schema_path(version: str | None = None, explicit_path: Path | None = None) -> Path:
|
|
24
|
+
"""Resolve the JSON Schema file path based on document version and availability."""
|
|
25
|
+
if explicit_path is not None:
|
|
26
|
+
return explicit_path
|
|
27
|
+
|
|
28
|
+
v = str(version).strip() if version else "0.2"
|
|
29
|
+
v_dir = v if v.startswith("v") else f"v{v}"
|
|
30
|
+
|
|
31
|
+
candidates = [
|
|
32
|
+
_REPO_SCHEMAS_DIR / v_dir / "agentsml.schema.json",
|
|
33
|
+
_REPO_SCHEMAS_DIR / "agentsml.schema.json",
|
|
34
|
+
_BUNDLED_SCHEMAS_DIR / v_dir / "agentsml.schema.json",
|
|
35
|
+
_BUNDLED_SCHEMAS_DIR / "agentsml.schema.json",
|
|
36
|
+
]
|
|
37
|
+
for c in candidates:
|
|
38
|
+
if c.exists():
|
|
39
|
+
return c
|
|
40
|
+
return _DEFAULT_SCHEMA_PATH
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _load_schema(schema_path: Path) -> dict:
|
|
44
|
+
"""Load and parse the JSON Schema file."""
|
|
45
|
+
if not schema_path.exists():
|
|
46
|
+
raise FileNotFoundError(f"Schema not found: {schema_path}")
|
|
47
|
+
return json.loads(schema_path.read_text(encoding="utf-8"))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _json_path(error: jsonschema.ValidationError) -> str:
|
|
51
|
+
"""Convert a jsonschema error path to a dot-notation string."""
|
|
52
|
+
parts = list(error.absolute_path)
|
|
53
|
+
if not parts:
|
|
54
|
+
return "(root)"
|
|
55
|
+
tokens = []
|
|
56
|
+
for p in parts:
|
|
57
|
+
if isinstance(p, int):
|
|
58
|
+
tokens.append(f"[{p}]")
|
|
59
|
+
else:
|
|
60
|
+
tokens.append(str(p))
|
|
61
|
+
return ".".join(t if not t.startswith("[") else t for t in tokens).replace(".[", "[")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def validate_schema(
|
|
65
|
+
doc: dict[str, Any],
|
|
66
|
+
diagnostics: DiagnosticSet,
|
|
67
|
+
schema_path: Path | None = None,
|
|
68
|
+
) -> bool:
|
|
69
|
+
"""Validate a parsed AgentsML document against the JSON Schema.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
doc: Parsed AgentsML document dict.
|
|
73
|
+
diagnostics: DiagnosticSet to accumulate validation errors.
|
|
74
|
+
schema_path: Path to agentsml.schema.json. Uses default if None.
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
True if the document passes schema validation, False otherwise.
|
|
78
|
+
"""
|
|
79
|
+
doc_version = doc.get("agentsml") if isinstance(doc, dict) else None
|
|
80
|
+
sp = resolve_schema_path(doc_version, schema_path)
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
schema = _load_schema(sp)
|
|
84
|
+
except FileNotFoundError as exc:
|
|
85
|
+
diagnostics.add_error(
|
|
86
|
+
DiagCode.GENERATION_FAILED,
|
|
87
|
+
str(exc),
|
|
88
|
+
recommendation=f"Ensure the public AgentsML schema exists at {sp}.",
|
|
89
|
+
)
|
|
90
|
+
return False
|
|
91
|
+
except json.JSONDecodeError as exc:
|
|
92
|
+
diagnostics.add_error(
|
|
93
|
+
DiagCode.GENERATION_FAILED,
|
|
94
|
+
f"Failed to parse schema JSON: {exc}",
|
|
95
|
+
)
|
|
96
|
+
return False
|
|
97
|
+
|
|
98
|
+
# Use Draft 2020-12 validator.
|
|
99
|
+
validator_cls = jsonschema.validators.validator_for(schema)
|
|
100
|
+
validator = validator_cls(schema)
|
|
101
|
+
|
|
102
|
+
errors = sorted(validator.iter_errors(doc), key=lambda e: list(e.absolute_path))
|
|
103
|
+
|
|
104
|
+
for error in errors:
|
|
105
|
+
path = _json_path(error)
|
|
106
|
+
# Root-level missing required fields are fatal; others are errors.
|
|
107
|
+
severity = Severity.FATAL if not list(error.absolute_path) else Severity.ERROR
|
|
108
|
+
if severity == Severity.FATAL:
|
|
109
|
+
diagnostics.add_fatal(
|
|
110
|
+
DiagCode.MISSING_SCHEMA,
|
|
111
|
+
f"Schema validation error at {path}: {error.message}",
|
|
112
|
+
path=path,
|
|
113
|
+
)
|
|
114
|
+
else:
|
|
115
|
+
diagnostics.add_error(
|
|
116
|
+
DiagCode.MISSING_SCHEMA,
|
|
117
|
+
f"Schema validation error at {path}: {error.message}",
|
|
118
|
+
path=path,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
return not diagnostics.has_errors()
|