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.
Files changed (129) hide show
  1. agentsml_impl/__init__.py +3 -0
  2. agentsml_impl/cli.py +472 -0
  3. agentsml_impl/compiler/__init__.py +1 -0
  4. agentsml_impl/compiler/capabilities.py +330 -0
  5. agentsml_impl/compiler/conditions.py +177 -0
  6. agentsml_impl/compiler/diagnostics.py +112 -0
  7. agentsml_impl/compiler/durations.py +31 -0
  8. agentsml_impl/compiler/expressions.py +123 -0
  9. agentsml_impl/compiler/identifiers.py +60 -0
  10. agentsml_impl/compiler/ir.py +391 -0
  11. agentsml_impl/compiler/limits.py +28 -0
  12. agentsml_impl/compiler/loader.py +83 -0
  13. agentsml_impl/compiler/naming.py +87 -0
  14. agentsml_impl/compiler/planner.py +79 -0
  15. agentsml_impl/compiler/render.py +90 -0
  16. agentsml_impl/compiler/schema_validation.py +121 -0
  17. agentsml_impl/compiler/semantic_validation.py +424 -0
  18. agentsml_impl/protocols/__init__.py +1 -0
  19. agentsml_impl/runtime/__init__.py +1 -0
  20. agentsml_impl/runtime/events.py +59 -0
  21. agentsml_impl/runtime/json_schema.py +138 -0
  22. agentsml_impl/runtime/tools.py +145 -0
  23. agentsml_impl/schemas/agentsml.schema.json +406 -0
  24. agentsml_impl/schemas/v0.1/agentsml.schema.json +628 -0
  25. agentsml_impl/schemas/v0.2/agentsml.schema.json +363 -0
  26. agentsml_impl/schemas/v0.3/agentsml.schema.json +406 -0
  27. agentsml_impl/targets/__init__.py +1 -0
  28. agentsml_impl/targets/a2a/__init__.py +0 -0
  29. agentsml_impl/targets/a2a/adapter.py +94 -0
  30. agentsml_impl/targets/a2a/capabilities.yaml +25 -0
  31. agentsml_impl/targets/ag2/__init__.py +0 -0
  32. agentsml_impl/targets/ag2/adapter.py +655 -0
  33. agentsml_impl/targets/ag2/capabilities.yaml +37 -0
  34. agentsml_impl/targets/ag_ui/__init__.py +0 -0
  35. agentsml_impl/targets/ag_ui/adapter.py +123 -0
  36. agentsml_impl/targets/ag_ui/capabilities.yaml +25 -0
  37. agentsml_impl/targets/agno/__init__.py +0 -0
  38. agentsml_impl/targets/agno/adapter.py +191 -0
  39. agentsml_impl/targets/agno/capabilities.yaml +26 -0
  40. agentsml_impl/targets/ap2/__init__.py +0 -0
  41. agentsml_impl/targets/ap2/adapter.py +84 -0
  42. agentsml_impl/targets/ap2/capabilities.yaml +25 -0
  43. agentsml_impl/targets/base.py +157 -0
  44. agentsml_impl/targets/bedrock_agentcore/__init__.py +0 -0
  45. agentsml_impl/targets/bedrock_agentcore/adapter.py +592 -0
  46. agentsml_impl/targets/bedrock_agentcore/capabilities.yaml +26 -0
  47. agentsml_impl/targets/claude_agent_sdk/__init__.py +0 -0
  48. agentsml_impl/targets/claude_agent_sdk/adapter.py +178 -0
  49. agentsml_impl/targets/claude_agent_sdk/capabilities.yaml +26 -0
  50. agentsml_impl/targets/crewai/__init__.py +0 -0
  51. agentsml_impl/targets/crewai/adapter.py +441 -0
  52. agentsml_impl/targets/crewai/capabilities.yaml +30 -0
  53. agentsml_impl/targets/databricks/__init__.py +0 -0
  54. agentsml_impl/targets/databricks/adapter.py +427 -0
  55. agentsml_impl/targets/databricks/capabilities.yaml +26 -0
  56. agentsml_impl/targets/flowise/__init__.py +0 -0
  57. agentsml_impl/targets/flowise/adapter.py +71 -0
  58. agentsml_impl/targets/flowise/capabilities.yaml +26 -0
  59. agentsml_impl/targets/google_adk/__init__.py +0 -0
  60. agentsml_impl/targets/google_adk/adapter.py +589 -0
  61. agentsml_impl/targets/google_adk/capabilities.yaml +36 -0
  62. agentsml_impl/targets/langchain/__init__.py +1 -0
  63. agentsml_impl/targets/langchain/adapter.py +351 -0
  64. agentsml_impl/targets/langchain/capabilities.yaml +30 -0
  65. agentsml_impl/targets/langflow/__init__.py +0 -0
  66. agentsml_impl/targets/langflow/adapter.py +147 -0
  67. agentsml_impl/targets/langflow/capabilities.yaml +26 -0
  68. agentsml_impl/targets/langgraph/__init__.py +0 -0
  69. agentsml_impl/targets/langgraph/adapter.py +911 -0
  70. agentsml_impl/targets/langgraph/capabilities.yaml +33 -0
  71. agentsml_impl/targets/llamaindex/__init__.py +1 -0
  72. agentsml_impl/targets/llamaindex/adapter.py +406 -0
  73. agentsml_impl/targets/llamaindex/capabilities.yaml +31 -0
  74. agentsml_impl/targets/lyzr/__init__.py +0 -0
  75. agentsml_impl/targets/lyzr/adapter.py +146 -0
  76. agentsml_impl/targets/lyzr/capabilities.yaml +26 -0
  77. agentsml_impl/targets/mastra/__init__.py +0 -0
  78. agentsml_impl/targets/mastra/adapter.py +635 -0
  79. agentsml_impl/targets/mastra/capabilities.yaml +32 -0
  80. agentsml_impl/targets/mcp_server/__init__.py +0 -0
  81. agentsml_impl/targets/mcp_server/adapter.py +141 -0
  82. agentsml_impl/targets/mcp_server/capabilities.yaml +25 -0
  83. agentsml_impl/targets/microsoft_agent_framework/__init__.py +0 -0
  84. agentsml_impl/targets/microsoft_agent_framework/adapter.py +563 -0
  85. agentsml_impl/targets/microsoft_agent_framework/capabilities.yaml +26 -0
  86. agentsml_impl/targets/n8n/__init__.py +0 -0
  87. agentsml_impl/targets/n8n/adapter.py +139 -0
  88. agentsml_impl/targets/n8n/capabilities.yaml +26 -0
  89. agentsml_impl/targets/openai_agents/__init__.py +0 -0
  90. agentsml_impl/targets/openai_agents/adapter.py +175 -0
  91. agentsml_impl/targets/openai_agents/capabilities.yaml +27 -0
  92. agentsml_impl/targets/pydantic_ai/__init__.py +0 -0
  93. agentsml_impl/targets/pydantic_ai/adapter.py +922 -0
  94. agentsml_impl/targets/pydantic_ai/capabilities.yaml +37 -0
  95. agentsml_impl/targets/registry.py +290 -0
  96. agentsml_impl/targets/relevance_ai/__init__.py +0 -0
  97. agentsml_impl/targets/relevance_ai/adapter.py +66 -0
  98. agentsml_impl/targets/relevance_ai/capabilities.yaml +26 -0
  99. agentsml_impl/targets/smolagents/__init__.py +0 -0
  100. agentsml_impl/targets/smolagents/adapter.py +210 -0
  101. agentsml_impl/targets/smolagents/capabilities.yaml +27 -0
  102. agentsml_impl/targets/snowflake_cortex/__init__.py +0 -0
  103. agentsml_impl/targets/snowflake_cortex/adapter.py +167 -0
  104. agentsml_impl/targets/snowflake_cortex/capabilities.yaml +26 -0
  105. agentsml_impl/targets/spring_ai/__init__.py +1 -0
  106. agentsml_impl/targets/spring_ai/adapter.py +626 -0
  107. agentsml_impl/targets/spring_ai/capabilities.yaml +31 -0
  108. agentsml_impl/targets/strands_agents/__init__.py +1 -0
  109. agentsml_impl/targets/strands_agents/adapter.py +309 -0
  110. agentsml_impl/targets/strands_agents/capabilities.yaml +29 -0
  111. agentsml_impl/targets/support_matrix.py +91 -0
  112. agentsml_impl/targets/ucp/__init__.py +0 -0
  113. agentsml_impl/targets/ucp/adapter.py +86 -0
  114. agentsml_impl/targets/ucp/capabilities.yaml +25 -0
  115. agentsml_impl/targets/vercel_ai/__init__.py +1 -0
  116. agentsml_impl/targets/vercel_ai/adapter.py +349 -0
  117. agentsml_impl/targets/vercel_ai/capabilities.yaml +30 -0
  118. agentsml_impl/targets/vertex_agent_engine/__init__.py +0 -0
  119. agentsml_impl/targets/vertex_agent_engine/adapter.py +407 -0
  120. agentsml_impl/targets/vertex_agent_engine/capabilities.yaml +26 -0
  121. agentsml_impl/targets/zapier_agents/__init__.py +0 -0
  122. agentsml_impl/targets/zapier_agents/adapter.py +106 -0
  123. agentsml_impl/targets/zapier_agents/capabilities.yaml +26 -0
  124. agentsml_impl-0.2.0.dist-info/METADATA +109 -0
  125. agentsml_impl-0.2.0.dist-info/RECORD +129 -0
  126. agentsml_impl-0.2.0.dist-info/WHEEL +5 -0
  127. agentsml_impl-0.2.0.dist-info/entry_points.txt +3 -0
  128. agentsml_impl-0.2.0.dist-info/licenses/LICENSE +28 -0
  129. agentsml_impl-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,330 @@
1
+ """CORE-007: Capability Analysis — compare IR features against target capabilities."""
2
+
3
+ from __future__ import annotations
4
+ import yaml
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from agentsml_impl.compiler.ir import AgentSystemIR
9
+ from agentsml_impl.compiler.diagnostics import DiagCode, DiagnosticSet
10
+
11
+ _TARGETS_ROOT = Path(__file__).parent.parent / "targets"
12
+ _SUPPORTED_CAPABILITY_VALUES = {"native", "adapter", "manual", "lossy", "unsupported"}
13
+ _PROFILE_TO_FEATURE = {
14
+ "agentsml-a2a": "a2a",
15
+ "agentsml-core": None,
16
+ "agentsml-graph": "graph_edges",
17
+ "agentsml-mcp": "mcp",
18
+ "agentsml-observability": "observability",
19
+ "agentsml-ui": "ag_ui",
20
+ }
21
+
22
+
23
+ def _normalize_target_name(target: str) -> str:
24
+ """Normalize target names across CLI/display and directory forms."""
25
+ return target.strip().lower().replace("-", "_")
26
+
27
+
28
+ def _capabilities_path(target: str) -> Path:
29
+ return _TARGETS_ROOT / _normalize_target_name(target) / "capabilities.yaml"
30
+
31
+
32
+ def load_capabilities(target: str) -> dict[str, Any]:
33
+ """Load the capabilities.yaml for a target. Returns empty dict if not found."""
34
+ cap_path = _capabilities_path(target)
35
+ if not cap_path.exists():
36
+ return {}
37
+ return yaml.safe_load(cap_path.read_text(encoding="utf-8")) or {}
38
+
39
+
40
+ def _cap_value(caps: dict, key: str) -> str:
41
+ """Return capability value or 'unsupported'."""
42
+ return caps.get("supports", {}).get(key, "unsupported")
43
+
44
+
45
+ def _profile_support_from_declarations(caps: dict[str, Any]) -> dict[str, str]:
46
+ raw_profiles = caps.get("profiles")
47
+ if raw_profiles is None:
48
+ return {}
49
+
50
+ resolved: dict[str, str] = {}
51
+ if isinstance(raw_profiles, list):
52
+ for profile in raw_profiles:
53
+ if isinstance(profile, str):
54
+ resolved[profile] = "native"
55
+ return resolved
56
+
57
+ if not isinstance(raw_profiles, dict):
58
+ return {}
59
+
60
+ if "supports" in raw_profiles and isinstance(raw_profiles["supports"], dict):
61
+ raw_profiles = raw_profiles["supports"]
62
+
63
+ for profile, status in raw_profiles.items():
64
+ if isinstance(status, str) and status in _SUPPORTED_CAPABILITY_VALUES:
65
+ resolved[profile] = status
66
+
67
+ grouped_aliases = {
68
+ "supported": "native",
69
+ "native": "native",
70
+ "adapter": "adapter",
71
+ "manual": "manual",
72
+ "lossy": "lossy",
73
+ "partial": "lossy",
74
+ "unsupported": "unsupported",
75
+ }
76
+ for group_name, mapped_status in grouped_aliases.items():
77
+ profiles = raw_profiles.get(group_name)
78
+ if isinstance(profiles, list):
79
+ for profile in profiles:
80
+ if isinstance(profile, str):
81
+ resolved[profile] = mapped_status
82
+
83
+ return resolved
84
+
85
+
86
+ def _infer_profile_support(profile: str, caps: dict[str, Any]) -> str | None:
87
+ feature = _PROFILE_TO_FEATURE.get(profile)
88
+ if feature is None:
89
+ return "native" if profile == "agentsml-core" else None
90
+
91
+ if profile == "agentsml-graph":
92
+ graph_support = _cap_value(caps, "graph_edges")
93
+ condition_support = _cap_value(caps, "graph_conditions")
94
+ cycle_support = _cap_value(caps, "cycles")
95
+ workflow_support = _cap_value(caps, "workflows")
96
+ levels = {graph_support, condition_support, cycle_support, workflow_support}
97
+
98
+ if "unsupported" in levels:
99
+ return "unsupported"
100
+ if "lossy" in levels:
101
+ return "lossy"
102
+ if "manual" in levels:
103
+ return "manual"
104
+ if "adapter" in levels:
105
+ return "adapter"
106
+ return "native"
107
+
108
+ return _cap_value(caps, feature)
109
+
110
+
111
+ def _profile_support(profile: str, caps: dict[str, Any]) -> str | None:
112
+ declared = _profile_support_from_declarations(caps)
113
+ if profile in declared:
114
+ return declared[profile]
115
+ return _infer_profile_support(profile, caps)
116
+
117
+
118
+ def _emit_profile_diagnostic(
119
+ diagnostics: DiagnosticSet,
120
+ *,
121
+ target: str,
122
+ profile: str,
123
+ status: str | None,
124
+ required: bool,
125
+ ) -> None:
126
+ if status == "native":
127
+ return
128
+
129
+ path = "profiles.required" if required else "profiles.optional"
130
+
131
+ if status in (None, "unsupported"):
132
+ add_diag = diagnostics.add_error if required else diagnostics.add_warning
133
+ requirement = "required" if required else "optional"
134
+ support_text = "does not declare support for" if status is None else "does not support"
135
+ add_diag(
136
+ DiagCode.UNSUPPORTED_PROFILE,
137
+ f"Target '{target}' {support_text} {requirement} profile '{profile}'.",
138
+ target=target,
139
+ path=path,
140
+ )
141
+ return
142
+
143
+ if status == "lossy":
144
+ requirement = "required" if required else "optional"
145
+ diagnostics.add_warning(
146
+ DiagCode.LOSSY_MAPPING,
147
+ f"Target '{target}' supports {requirement} profile '{profile}' with lossy mapping.",
148
+ target=target,
149
+ path=path,
150
+ )
151
+ return
152
+
153
+ support_mode = "manual configuration" if status == "manual" else "generated adapter code"
154
+ requirement = "required" if required else "optional"
155
+ diagnostics.add_info(
156
+ DiagCode.REQUIRES_ADAPTER,
157
+ f"Target '{target}' supports {requirement} profile '{profile}' via {support_mode}.",
158
+ target=target,
159
+ path=path,
160
+ )
161
+
162
+
163
+ def analyze_capabilities(
164
+ ir: AgentSystemIR,
165
+ target: str,
166
+ diagnostics: DiagnosticSet,
167
+ ) -> dict[str, Any]:
168
+ """Compare IR features against target capabilities and emit diagnostics.
169
+
170
+ Returns the loaded capabilities dict.
171
+ """
172
+ caps = load_capabilities(target)
173
+ if not caps:
174
+ diagnostics.add_warning(
175
+ DiagCode.TARGET_VERSION_UNKNOWN,
176
+ f"No capabilities.yaml found for target '{target}'.",
177
+ target=target,
178
+ recommendation="Add a capabilities.yaml under targets/{target}/.",
179
+ )
180
+ return {}
181
+
182
+ supports = caps.get("supports", {})
183
+
184
+ def _check(feature: str, diag_code: DiagCode, message: str, path: str = "", recommendation: str = "") -> None:
185
+ val = supports.get(feature, "unsupported")
186
+ if val == "unsupported":
187
+ diagnostics.add_error(diag_code, message, target=target, path=path or None,
188
+ recommendation=recommendation or None)
189
+ elif val == "lossy":
190
+ diagnostics.add_warning(DiagCode.LOSSY_MAPPING, message + " (lossy mapping)",
191
+ target=target, path=path or None)
192
+ elif val == "manual":
193
+ diagnostics.add_info(DiagCode.REQUIRES_ADAPTER,
194
+ message + " (requires manual configuration)", target=target, path=path or None)
195
+ elif val == "adapter":
196
+ diagnostics.add_info(DiagCode.REQUIRES_ADAPTER,
197
+ message + " (generated adapter code required)", target=target, path=path or None)
198
+
199
+ for profile in ir.profiles.required:
200
+ _emit_profile_diagnostic(
201
+ diagnostics,
202
+ target=target,
203
+ profile=profile,
204
+ status=_profile_support(profile, caps),
205
+ required=True,
206
+ )
207
+
208
+ for profile in ir.profiles.optional:
209
+ _emit_profile_diagnostic(
210
+ diagnostics,
211
+ target=target,
212
+ profile=profile,
213
+ status=_profile_support(profile, caps),
214
+ required=False,
215
+ )
216
+
217
+ # Agents
218
+ if ir.agents:
219
+ _check("agents", DiagCode.UNSUPPORTED_FEATURE, "Target does not support agents.", path="agents")
220
+
221
+ # Tools
222
+ if ir.tools:
223
+ _check("tools", DiagCode.UNSUPPORTED_FEATURE, "Target does not support tools.", path="tools")
224
+
225
+ # MCP tools
226
+ has_mcp = any(t.is_mcp() for t in ir.tools.values()) or bool(ir.mcp_servers)
227
+ if has_mcp:
228
+ _check("mcp", DiagCode.UNSUPPORTED_PROFILE,
229
+ "Target does not natively support MCP tools.", path="mcp_servers",
230
+ recommendation="Use a target with native or adapter-level MCP support.")
231
+
232
+ # Workflow edges / graph
233
+ has_edges = any(wf.edges for wf in ir.workflows.values())
234
+ if has_edges:
235
+ _check("graph_edges", DiagCode.UNSUPPORTED_FEATURE,
236
+ "Target does not support arbitrary workflow graph edges.", path="workflows",
237
+ recommendation="Use a target with native graph support such as langgraph.")
238
+
239
+ # Cycles
240
+ has_cycles = any(wf.has_cycles() for wf in ir.workflows.values())
241
+ if has_cycles:
242
+ _check("cycles", DiagCode.UNSUPPORTED_FEATURE,
243
+ "Target does not support cyclic workflow edges.", path="workflows",
244
+ recommendation="Use a target with cycle support such as langgraph.")
245
+
246
+ # Conditional edges
247
+ has_conditions = any(
248
+ edge.condition for wf in ir.workflows.values() for edge in wf.edges
249
+ )
250
+ if has_conditions:
251
+ _check("graph_conditions", DiagCode.UNSUPPORTED_FEATURE,
252
+ "Target does not support conditional workflow edges.", path="workflows",
253
+ recommendation="Use a target with native condition support such as langgraph.")
254
+
255
+ # Human approval
256
+ has_approvals = any(
257
+ step.approval for wf in ir.workflows.values() for step in wf.steps
258
+ )
259
+ if has_approvals:
260
+ _check("human_approval", DiagCode.REQUIRES_ADAPTER,
261
+ "Target does not natively support human approval (HITL) steps.", path="steps.approval")
262
+
263
+ # Retry / reasoning (Draft 0.3): optional manifest keys; absence means lossy.
264
+ for wf_key, wf in ir.workflows.items():
265
+ for step in wf.steps:
266
+ if step.retry is not None and _cap_value(caps, "retry") not in ("native", "adapter", "lossy"):
267
+ diagnostics.add_warning(
268
+ DiagCode.LOSSY_MAPPING,
269
+ f"Step '{step.id}' declares a retry policy that the {target} target does not "
270
+ "map natively; the policy is not enforced in generated code.",
271
+ target=target, path=f"workflows.{wf_key}.steps.{step.id}.retry",
272
+ )
273
+ if (step.retry is not None and step.retry.on_timeout is not None
274
+ and _cap_value(caps, "on_timeout") not in ("native", "adapter")):
275
+ diagnostics.add_warning(
276
+ DiagCode.LOSSY_MAPPING,
277
+ f"Step '{step.id}' sets retry.on_timeout='{step.retry.on_timeout}', which the "
278
+ f"{target} target does not implement; it is ignored.",
279
+ target=target, path=f"workflows.{wf_key}.steps.{step.id}.retry.on_timeout",
280
+ )
281
+ # Tool approval (needs_approval / approval_mode) is only honoured by targets that enforce it.
282
+ if _cap_value(caps, "tool_approval") not in ("native", "adapter"):
283
+ for tool_key, tool in ir.tools.items():
284
+ if tool.needs_approval or tool.approval_mode:
285
+ diagnostics.add_warning(
286
+ DiagCode.LOSSY_MAPPING,
287
+ f"Tool '{tool_key}' requires approval but the {target} target does not enforce "
288
+ "tool approval; gate it manually.",
289
+ target=target, path=f"tools.{tool_key}.needs_approval",
290
+ )
291
+ for ak, agent in ir.agents.items():
292
+ if agent.reasoning is not None and _cap_value(caps, "reasoning") not in ("native", "adapter"):
293
+ diagnostics.add_warning(
294
+ DiagCode.LOSSY_MAPPING,
295
+ f"Agent '{ak}' declares reasoning settings that the {target} target does not "
296
+ "map natively; they are not applied in generated code.",
297
+ target=target, path=f"agents.{ak}.reasoning",
298
+ )
299
+
300
+ # Structured output
301
+ has_output_schema = any(a.output_schema for a in ir.agents.values())
302
+ if has_output_schema:
303
+ _check("structured_output", DiagCode.REQUIRES_ADAPTER,
304
+ "Target requires adapter for structured output validation.", path="agents.output_schema")
305
+
306
+ # A2A
307
+ if ir.a2a_agents:
308
+ _check("a2a", DiagCode.UNSUPPORTED_PROFILE,
309
+ "Target does not natively support A2A agent delegation.",
310
+ recommendation="Use google-adk or ag2 target for native A2A.")
311
+
312
+ # A2A steps are only generated by targets with native A2A support.
313
+ a2a_status = _cap_value(caps, "a2a")
314
+ if a2a_status != "native":
315
+ for wf_key, wf in ir.workflows.items():
316
+ for step in wf.steps:
317
+ if not step.a2a_agent:
318
+ continue
319
+ diagnostics.add_warning(
320
+ DiagCode.REQUIRES_ADAPTER,
321
+ f"Step '{step.id}' delegates to A2A agent '{step.a2a_agent}' and is not "
322
+ f"generated by the {target} target.",
323
+ path=f"workflows.{wf_key}.steps.{step.id}.a2a_agent",
324
+ recommendation=(
325
+ "Wire the remote agent manually in the generated project, or use a target "
326
+ "with native A2A support such as google-adk or ag2."
327
+ ),
328
+ )
329
+
330
+ return caps
@@ -0,0 +1,177 @@
1
+ """CORE-COND: compile AgentsML edge conditions into safe Python predicate source.
2
+
3
+ Supported grammar: comparisons (==, !=, <, <=, >, >=), boolean operators (&&, ||, !),
4
+ parentheses, string/number/boolean/null literals, and dotted or indexed references
5
+ rooted at ``input``, ``state`` or ``steps``. Anything else is rejected, so the emitted
6
+ predicate never executes arbitrary code.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import json
13
+ import re
14
+
15
+ _ROOTS = frozenset({"input", "state", "steps"})
16
+ _COMPARISONS = frozenset({"==", "!=", "<", "<=", ">", ">="})
17
+ _SEGMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_-]*$")
18
+ _TOKEN = re.compile(
19
+ r"""
20
+ (?P<ws>\s+)
21
+ |(?P<str>"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')
22
+ |(?P<num>-?\d+(?:\.\d+)?)
23
+ |(?P<op>==|!=|<=|>=|&&|\|\||<|>|!|\(|\))
24
+ |(?P<name>[A-Za-z_][A-Za-z0-9_-]*)
25
+ |(?P<dot>\.)
26
+ |(?P<lb>\[)
27
+ |(?P<rb>\])
28
+ """,
29
+ re.VERBOSE,
30
+ )
31
+
32
+
33
+ class ConditionError(ValueError):
34
+ """Raised when an edge condition uses syntax outside the supported grammar."""
35
+
36
+
37
+ def compile_condition(raw: str) -> str:
38
+ """Return Python source for a predicate over ``ctx`` (a dict with input/state/steps)."""
39
+ source, _ = compile_condition_with_references(raw)
40
+ return source
41
+
42
+
43
+ def compile_condition_js(raw: str) -> str:
44
+ """Return JavaScript source for a predicate over ``ctx``.
45
+
46
+ The grammar is the same as the Python variant; only the emitted syntax
47
+ differs, so a condition behaves identically in a Python and a TypeScript
48
+ target.
49
+ """
50
+ source, _ = compile_condition_with_references(raw, language="js")
51
+ return source
52
+
53
+
54
+ def compile_condition_with_references(
55
+ raw: str, language: str = "py"
56
+ ) -> tuple[str, list[str]]:
57
+ """Return the predicate source and the dotted references it reads (e.g. ``steps.a.output.x``)."""
58
+ text = raw.strip()
59
+ if text.startswith("${") and text.endswith("}"):
60
+ text = text[2:-1].strip()
61
+ tokens = _tokenize(text)
62
+ parser = _Parser(tokens, language=language)
63
+ source = parser.parse_or()
64
+ if not parser.at_end():
65
+ raise ConditionError(f"unexpected token {parser.peek()[1]!r} in condition {raw!r}")
66
+ return source, parser.references
67
+
68
+
69
+ def _tokenize(text: str) -> list[tuple[str, str]]:
70
+ tokens: list[tuple[str, str]] = []
71
+ pos = 0
72
+ while pos < len(text):
73
+ match = _TOKEN.match(text, pos)
74
+ if not match:
75
+ raise ConditionError(f"unsupported syntax at {text[pos:]!r}")
76
+ kind = match.lastgroup
77
+ if kind != "ws":
78
+ tokens.append((kind, match.group()))
79
+ pos = match.end()
80
+ return tokens
81
+
82
+
83
+ class _Parser:
84
+ def __init__(self, tokens: list[tuple[str, str]], language: str = "py") -> None:
85
+ self._tokens = tokens
86
+ self._pos = 0
87
+ self.references: list[str] = []
88
+ self._js = language == "js"
89
+
90
+ def at_end(self) -> bool:
91
+ return self._pos >= len(self._tokens)
92
+
93
+ def peek(self) -> tuple[str, str]:
94
+ if self.at_end():
95
+ raise ConditionError("unexpected end of condition")
96
+ return self._tokens[self._pos]
97
+
98
+ def _next(self) -> tuple[str, str]:
99
+ token = self.peek()
100
+ self._pos += 1
101
+ return token
102
+
103
+ def _is_op(self, *ops: str) -> bool:
104
+ return not self.at_end() and self._tokens[self._pos][0] == "op" and self._tokens[self._pos][1] in ops
105
+
106
+ def parse_or(self) -> str:
107
+ left = self.parse_and()
108
+ while self._is_op("||"):
109
+ self._next()
110
+ joiner = " || " if self._js else " or "
111
+ left = f"({left}{joiner}{self.parse_and()})"
112
+ return left
113
+
114
+ def parse_and(self) -> str:
115
+ left = self.parse_comparison()
116
+ while self._is_op("&&"):
117
+ self._next()
118
+ joiner = " && " if self._js else " and "
119
+ left = f"({left}{joiner}{self.parse_comparison()})"
120
+ return left
121
+
122
+ def parse_comparison(self) -> str:
123
+ left = self.parse_primary()
124
+ if self._is_op(*_COMPARISONS):
125
+ op = self._next()[1]
126
+ right = self.parse_primary()
127
+ return f"compare({left}, {op!r}, {right})"
128
+ return left
129
+
130
+ def parse_primary(self) -> str:
131
+ kind, text = self._next()
132
+ if kind == "op" and text == "!":
133
+ inner = self.parse_primary()
134
+ return f"(!{inner})" if self._js else f"(not {inner})"
135
+ if kind == "op" and text == "(":
136
+ inner = self.parse_or()
137
+ closing = self._next()
138
+ if closing != ("op", ")"):
139
+ raise ConditionError("expected ')'")
140
+ return f"({inner})"
141
+ if kind == "num":
142
+ return text
143
+ if kind == "str":
144
+ value = ast.literal_eval(text)
145
+ return json.dumps(value) if self._js else repr(value)
146
+ if kind == "name":
147
+ if text == "true":
148
+ return "true" if self._js else "True"
149
+ if text == "false":
150
+ return "false" if self._js else "False"
151
+ if text == "null":
152
+ return "null" if self._js else "None"
153
+ if text in _ROOTS:
154
+ return f"lookup(ctx, {self._path(text)!r})"
155
+ raise ConditionError(f"unexpected token {text!r}")
156
+
157
+ def _path(self, root: str) -> str:
158
+ path = root
159
+ while self._is_op_kind("dot", "lb"):
160
+ kind, _ = self._next()
161
+ if kind == "dot":
162
+ kind, segment = self._next()
163
+ if not (kind == "name" and _SEGMENT.fullmatch(segment)) and not (kind == "num" and segment.isdigit()):
164
+ raise ConditionError(f"invalid path segment {segment!r}")
165
+ path += f".{segment}"
166
+ else:
167
+ kind, index = self._next()
168
+ if kind != "num" or not index.isdigit():
169
+ raise ConditionError("only non-negative integer indexes are supported")
170
+ if self._next()[0] != "rb":
171
+ raise ConditionError("expected ']'")
172
+ path += f".{index}"
173
+ self.references.append(path)
174
+ return path
175
+
176
+ def _is_op_kind(self, *kinds: str) -> bool:
177
+ return not self.at_end() and self._tokens[self._pos][0] in kinds
@@ -0,0 +1,112 @@
1
+ """CORE-004: Diagnostics model — consistent diagnostic data class and YAML output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from enum import Enum
7
+ from typing import Optional
8
+ import yaml
9
+
10
+
11
+ class Severity(str, Enum):
12
+ INFO = "info"
13
+ WARNING = "warning"
14
+ ERROR = "error"
15
+ FATAL = "fatal"
16
+
17
+
18
+ class DiagCode(str, Enum):
19
+ UNSUPPORTED_PROFILE = "unsupported_profile"
20
+ UNSUPPORTED_FEATURE = "unsupported_feature"
21
+ LOSSY_MAPPING = "lossy_mapping"
22
+ REQUIRES_ADAPTER = "requires_adapter"
23
+ REQUIRES_TARGET_EXTENSION = "requires_target_extension"
24
+ MISSING_AUTH_BINDING = "missing_auth_binding"
25
+ MISSING_POLICY = "missing_policy"
26
+ MISSING_SCHEMA = "missing_schema"
27
+ AMBIGUOUS_REFERENCE = "ambiguous_reference"
28
+ UNSAFE_SIDE_EFFECT = "unsafe_side_effect"
29
+ NONPORTABLE_EXPRESSION = "nonportable_expression"
30
+ TARGET_VERSION_UNKNOWN = "target_version_unknown"
31
+ TARGET_NOT_IMPLEMENTED = "target_not_implemented"
32
+ GENERATION_FAILED = "generation_failed"
33
+
34
+
35
+ _SEVERITY_ORDER = {
36
+ Severity.FATAL: 0,
37
+ Severity.ERROR: 1,
38
+ Severity.WARNING: 2,
39
+ Severity.INFO: 3,
40
+ }
41
+
42
+
43
+ @dataclass
44
+ class Diagnostic:
45
+ code: DiagCode
46
+ severity: Severity
47
+ message: str
48
+ path: Optional[str] = None
49
+ target: Optional[str] = None
50
+ recommendation: Optional[str] = None
51
+
52
+ def to_dict(self) -> dict:
53
+ d: dict = {
54
+ "code": self.code.value,
55
+ "severity": self.severity.value,
56
+ "message": self.message,
57
+ }
58
+ if self.path:
59
+ d["path"] = self.path
60
+ if self.target:
61
+ d["target"] = self.target
62
+ if self.recommendation:
63
+ d["recommendation"] = self.recommendation
64
+ return d
65
+
66
+
67
+ @dataclass
68
+ class DiagnosticSet:
69
+ diagnostics: list[Diagnostic] = field(default_factory=list)
70
+
71
+ def add(self, diag: Diagnostic) -> None:
72
+ self.diagnostics.append(diag)
73
+
74
+ def add_info(self, code: DiagCode, message: str, **kwargs) -> None:
75
+ self.add(Diagnostic(code=code, severity=Severity.INFO, message=message, **kwargs))
76
+
77
+ def add_warning(self, code: DiagCode, message: str, **kwargs) -> None:
78
+ self.add(Diagnostic(code=code, severity=Severity.WARNING, message=message, **kwargs))
79
+
80
+ def add_error(self, code: DiagCode, message: str, **kwargs) -> None:
81
+ self.add(Diagnostic(code=code, severity=Severity.ERROR, message=message, **kwargs))
82
+
83
+ def add_fatal(self, code: DiagCode, message: str, **kwargs) -> None:
84
+ self.add(Diagnostic(code=code, severity=Severity.FATAL, message=message, **kwargs))
85
+
86
+ def has_errors(self) -> bool:
87
+ return any(d.severity in (Severity.ERROR, Severity.FATAL) for d in self.diagnostics)
88
+
89
+ def has_fatal(self) -> bool:
90
+ return any(d.severity == Severity.FATAL for d in self.diagnostics)
91
+
92
+ def sorted(self) -> list[Diagnostic]:
93
+ return sorted(
94
+ self.diagnostics,
95
+ key=lambda d: (_SEVERITY_ORDER[d.severity], d.path or "", d.code.value),
96
+ )
97
+
98
+ def to_dict(self) -> dict:
99
+ return {"diagnostics": [d.to_dict() for d in self.sorted()]}
100
+
101
+ def to_yaml(self) -> str:
102
+ return yaml.dump(self.to_dict(), default_flow_style=False, sort_keys=False)
103
+
104
+ def summary(self) -> str:
105
+ counts: dict[str, int] = {}
106
+ for d in self.diagnostics:
107
+ counts[d.severity.value] = counts.get(d.severity.value, 0) + 1
108
+ parts = [f"{v} {k}" for k, v in counts.items()]
109
+ return ", ".join(parts) if parts else "no diagnostics"
110
+
111
+ def __len__(self) -> int:
112
+ return len(self.diagnostics)
@@ -0,0 +1,31 @@
1
+ """Duration parsing shared by target adapters (Draft 0.3 retry/timeout fields)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Optional
7
+
8
+ _UNITS = {"ms": 0.001, "s": 1.0, "m": 60.0, "h": 3600.0}
9
+ _PATTERN = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h)?\s*$", re.IGNORECASE)
10
+
11
+
12
+ _ISO = re.compile(r"^\s*PT(\d+(?:\.\d+)?)([SMH])\s*$", re.IGNORECASE)
13
+
14
+
15
+ def parse_duration_seconds(value: Any) -> Optional[float]:
16
+ """Parse numbers (seconds) and simple strings such as ``2s``, ``500ms``, ``5m``.
17
+
18
+ Also accepts ISO-8601 ``PT<n>S/M/H``. Returns None when the value is absent or not in a supported simple form
19
+ (callers should emit a lossy_mapping warning with the raw value).
20
+ """
21
+ if value is None or isinstance(value, bool):
22
+ return None
23
+ if isinstance(value, (int, float)):
24
+ return float(value)
25
+ iso = _ISO.match(str(value))
26
+ if iso:
27
+ return float(iso.group(1)) * _UNITS[iso.group(2).lower()]
28
+ m = _PATTERN.match(str(value))
29
+ if not m:
30
+ return None
31
+ return float(m.group(1)) * _UNITS[(m.group(2) or "s").lower()]