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,635 @@
|
|
|
1
|
+
"""Mastra target adapter — Level 1 code generation (TypeScript).
|
|
2
|
+
|
|
3
|
+
Fixes (2026-06-09):
|
|
4
|
+
- Multi-agent: generate createNetwork when len(agents) > 1.
|
|
5
|
+
- Add .branch() / .parallel() step generation from workflow edges.
|
|
6
|
+
- Agent Signals for multi-client streaming.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from collections.abc import Iterable
|
|
12
|
+
|
|
13
|
+
from agentsml_impl.compiler.conditions import ConditionError, compile_condition_js
|
|
14
|
+
from agentsml_impl.compiler.ir import AgentSystemIR, ModelIR
|
|
15
|
+
from agentsml_impl.compiler.diagnostics import DiagCode, DiagnosticSet
|
|
16
|
+
from agentsml_impl.compiler.naming import camel_identifier, pascal_identifier, unique_identifiers
|
|
17
|
+
from agentsml_impl.compiler.planner import GenerationPlan
|
|
18
|
+
from agentsml_impl.compiler.render import write_file
|
|
19
|
+
from agentsml_impl.targets.base import TargetAdapter, GenerationResult
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Adapter(TargetAdapter):
|
|
23
|
+
@property
|
|
24
|
+
def name(self) -> str:
|
|
25
|
+
return "mastra"
|
|
26
|
+
|
|
27
|
+
def analyze(self, ir: AgentSystemIR, diagnostics: DiagnosticSet) -> None:
|
|
28
|
+
from agentsml_impl.compiler.capabilities import analyze_capabilities
|
|
29
|
+
analyze_capabilities(ir, self.name, diagnostics)
|
|
30
|
+
|
|
31
|
+
def generate(self, ir: AgentSystemIR, plan: GenerationPlan,
|
|
32
|
+
out_dir: Path, diagnostics: DiagnosticSet) -> GenerationResult:
|
|
33
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
34
|
+
src = out_dir / "src"
|
|
35
|
+
src.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
|
|
37
|
+
is_multi = len(ir.agents) > 1
|
|
38
|
+
|
|
39
|
+
files: list[str] = []
|
|
40
|
+
files += _write_package_json(ir, plan, out_dir, is_multi)
|
|
41
|
+
files += _write_tsconfig(out_dir)
|
|
42
|
+
files += _write_tools(ir, src, out_dir)
|
|
43
|
+
files += _write_agent(ir, plan, src, out_dir)
|
|
44
|
+
if is_multi:
|
|
45
|
+
files += _write_network(ir, plan, src, out_dir, diagnostics)
|
|
46
|
+
files += _write_workflow(ir, plan, src, out_dir, diagnostics)
|
|
47
|
+
files += _write_index(ir, plan, src, out_dir, is_multi)
|
|
48
|
+
files += _write_readme(ir, plan, out_dir, is_multi)
|
|
49
|
+
|
|
50
|
+
return GenerationResult(
|
|
51
|
+
target=self.name, out_dir=out_dir, files_written=files, success=True
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# ---------------------------------------------------------------------------
|
|
56
|
+
# Model provider helpers
|
|
57
|
+
# ---------------------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
def _provider_import_and_expr(model: ModelIR) -> tuple[str, str]:
|
|
60
|
+
"""Return (import_line, model_expr) for the Mastra agent."""
|
|
61
|
+
p = model.provider.lower()
|
|
62
|
+
n = model.name
|
|
63
|
+
if p == "openai":
|
|
64
|
+
return "import { openai } from '@ai-sdk/openai';", f"openai('{n}')"
|
|
65
|
+
if p in ("google", "gemini"):
|
|
66
|
+
return "import { google } from '@ai-sdk/google';", f"google('{n}')"
|
|
67
|
+
if p == "anthropic":
|
|
68
|
+
return "import { anthropic } from '@ai-sdk/anthropic';", f"anthropic('{n}')"
|
|
69
|
+
if p in ("azure", "azure-openai"):
|
|
70
|
+
return "import { openai } from '@ai-sdk/openai';", f"openai('{n}') // Azure: configure AZURE_OPENAI_* env vars"
|
|
71
|
+
# Fallback
|
|
72
|
+
return "import { openai } from '@ai-sdk/openai';", f"openai('{n}') // TODO: check provider {p!r}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _ts_symbol_map(values: Iterable[str], *, prefix: str, suffix: str) -> dict[str, str]:
|
|
76
|
+
return unique_identifiers(
|
|
77
|
+
values,
|
|
78
|
+
lambda value: f"{camel_identifier(value, prefix=prefix, language='javascript')}{suffix}",
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _mastra_export_name(plan: GenerationPlan, suffix: str) -> str:
|
|
83
|
+
return f"{pascal_identifier(plan.project_name, prefix='Mastra')}{suffix}"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _write_package_json(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path, is_multi: bool) -> list[str]:
|
|
87
|
+
|
|
88
|
+
c = f'''\
|
|
89
|
+
{{
|
|
90
|
+
"name": "{plan.package_name}",
|
|
91
|
+
"version": "{ir.metadata.version or '0.1.0'}",
|
|
92
|
+
"type": "module",
|
|
93
|
+
"scripts": {{
|
|
94
|
+
"dev": "tsx watch src/index.ts",
|
|
95
|
+
"start": "node --experimental-strip-types src/index.ts"
|
|
96
|
+
}},
|
|
97
|
+
"dependencies": {{
|
|
98
|
+
"@mastra/core": "^1.83.0",
|
|
99
|
+
"zod": "^3.22.4",
|
|
100
|
+
"@ai-sdk/openai": "^0.0.1",
|
|
101
|
+
"@ai-sdk/anthropic": "^0.0.1",
|
|
102
|
+
"@ai-sdk/google": "^0.0.1"
|
|
103
|
+
}},
|
|
104
|
+
"devDependencies": {{
|
|
105
|
+
"typescript": "^5.0.0",
|
|
106
|
+
"@types/node": "^20.0.0",
|
|
107
|
+
"tsx": "^4.0.0"
|
|
108
|
+
}}
|
|
109
|
+
}}
|
|
110
|
+
'''
|
|
111
|
+
write_file(out_dir, "package.json", c)
|
|
112
|
+
return ["package.json"]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _write_tsconfig(out_dir: Path) -> list[str]:
|
|
116
|
+
c = '''\
|
|
117
|
+
{
|
|
118
|
+
"compilerOptions": {
|
|
119
|
+
"target": "ES2022",
|
|
120
|
+
"module": "ESNext",
|
|
121
|
+
"moduleResolution": "bundler",
|
|
122
|
+
"strict": true,
|
|
123
|
+
"esModuleInterop": true,
|
|
124
|
+
"skipLibCheck": true,
|
|
125
|
+
"forceConsistentCasingInFileNames": true,
|
|
126
|
+
"outDir": "./dist"
|
|
127
|
+
},
|
|
128
|
+
"include": ["src/**/*"]
|
|
129
|
+
}
|
|
130
|
+
'''
|
|
131
|
+
write_file(out_dir, "tsconfig.json", c)
|
|
132
|
+
return ["tsconfig.json"]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _write_tools(ir: AgentSystemIR, src: Path, out_dir: Path) -> list[str]:
|
|
136
|
+
if not ir.tools:
|
|
137
|
+
return []
|
|
138
|
+
tool_exports = _ts_symbol_map(list(ir.tools.keys()), prefix="tool", suffix="Tool")
|
|
139
|
+
blocks = []
|
|
140
|
+
for k, tool in ir.tools.items():
|
|
141
|
+
desc = tool.description.replace('"', '\\"')
|
|
142
|
+
# Generate Zod schema from input_schema if available
|
|
143
|
+
zod_schema = _json_schema_to_zod(tool.input_schema)
|
|
144
|
+
blocks.append(f'''\
|
|
145
|
+
export const {tool_exports[k]} = createTool({{
|
|
146
|
+
name: "{k}",
|
|
147
|
+
description: "{desc}",
|
|
148
|
+
schema: {zod_schema},
|
|
149
|
+
execute: async ({{ context }}) => {{
|
|
150
|
+
// TODO: implement
|
|
151
|
+
throw new Error("{k}: not implemented");
|
|
152
|
+
}},
|
|
153
|
+
}});
|
|
154
|
+
''')
|
|
155
|
+
|
|
156
|
+
c = f'''\
|
|
157
|
+
import {{ createTool }} from '@mastra/core';
|
|
158
|
+
import {{ z }} from 'zod';
|
|
159
|
+
|
|
160
|
+
{chr(10).join(blocks)}
|
|
161
|
+
'''
|
|
162
|
+
rel = "src/tools.ts"
|
|
163
|
+
write_file(out_dir, rel, c)
|
|
164
|
+
return [rel]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _json_schema_to_zod(schema: dict | None) -> str:
|
|
168
|
+
"""Convert simple JSON schema to Zod expression (best-effort)."""
|
|
169
|
+
if not schema:
|
|
170
|
+
return "z.any()"
|
|
171
|
+
t = schema.get("type")
|
|
172
|
+
if t == "string":
|
|
173
|
+
return "z.string()"
|
|
174
|
+
if t == "number":
|
|
175
|
+
return "z.number()"
|
|
176
|
+
if t == "boolean":
|
|
177
|
+
return "z.boolean()"
|
|
178
|
+
if t == "array":
|
|
179
|
+
items = schema.get("items", {})
|
|
180
|
+
return f"z.array({_json_schema_to_zod(items)})"
|
|
181
|
+
if t == "object":
|
|
182
|
+
props = schema.get("properties", {})
|
|
183
|
+
if not props:
|
|
184
|
+
return "z.record(z.any())"
|
|
185
|
+
fields = ", ".join(
|
|
186
|
+
f"{k}: {_json_schema_to_zod(v)}" for k, v in props.items()
|
|
187
|
+
)
|
|
188
|
+
return f"z.object({{ {fields} }})"
|
|
189
|
+
return "z.any()"
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _write_agent(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path) -> list[str]:
|
|
193
|
+
agent_blocks = []
|
|
194
|
+
provider_imports: set[str] = set()
|
|
195
|
+
agent_exports = _ts_symbol_map(list(ir.agents.keys()), prefix="agent", suffix="Agent")
|
|
196
|
+
tool_exports = _ts_symbol_map(list(ir.tools.keys()), prefix="tool", suffix="Tool") if ir.tools else {}
|
|
197
|
+
|
|
198
|
+
tools_import = (
|
|
199
|
+
f"import {{ {', '.join(tool_exports[k] for k in ir.tools.keys())} }} from './tools.js';"
|
|
200
|
+
if ir.tools else ""
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
for ak, agent in ir.agents.items():
|
|
204
|
+
inst = agent.instructions.replace('`', '\\`')
|
|
205
|
+
tools_ref = "\n".join(
|
|
206
|
+
f" {tool_exports[t]},"
|
|
207
|
+
for t in agent.tools if t in ir.tools
|
|
208
|
+
)
|
|
209
|
+
model = ir.models.get(agent.model)
|
|
210
|
+
if model:
|
|
211
|
+
pimp, pexpr = _provider_import_and_expr(model)
|
|
212
|
+
provider_imports.add(pimp)
|
|
213
|
+
model_line = f" model: {pexpr},"
|
|
214
|
+
else:
|
|
215
|
+
provider_imports.add("import { openai } from '@ai-sdk/openai';")
|
|
216
|
+
model_line = " model: openai('gpt-4o'),"
|
|
217
|
+
|
|
218
|
+
agent_blocks.append(f'''\
|
|
219
|
+
export const {agent_exports[ak]} = new Agent({{
|
|
220
|
+
name: "{ak}",
|
|
221
|
+
instructions: `{inst}`,
|
|
222
|
+
{model_line}
|
|
223
|
+
tools: {{
|
|
224
|
+
{tools_ref}
|
|
225
|
+
}},
|
|
226
|
+
}});
|
|
227
|
+
''')
|
|
228
|
+
|
|
229
|
+
provider_import_str = "\n".join(sorted(provider_imports))
|
|
230
|
+
|
|
231
|
+
c = f'''\
|
|
232
|
+
import {{ Agent }} from '@mastra/core';
|
|
233
|
+
{provider_import_str}
|
|
234
|
+
{tools_import}
|
|
235
|
+
|
|
236
|
+
{chr(10).join(agent_blocks)}
|
|
237
|
+
'''
|
|
238
|
+
rel = "src/agent.ts"
|
|
239
|
+
write_file(out_dir, rel, c)
|
|
240
|
+
return [rel]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _write_network(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
|
|
244
|
+
"""Generate createNetwork for multi-agent coordination."""
|
|
245
|
+
ds.add_info(DiagCode.REQUIRES_ADAPTER,
|
|
246
|
+
"Multi-agent workflow detected. Generating createNetwork for Mastra agent network.",
|
|
247
|
+
path="agents")
|
|
248
|
+
|
|
249
|
+
agent_names = list(ir.agents.keys())
|
|
250
|
+
agent_exports = _ts_symbol_map(agent_names, prefix="agent", suffix="Agent")
|
|
251
|
+
network_export = _mastra_export_name(plan, "Network")
|
|
252
|
+
|
|
253
|
+
# Default model for network routing
|
|
254
|
+
first_model = next(iter(ir.models.values()), None)
|
|
255
|
+
if first_model:
|
|
256
|
+
pimp, pexpr = _provider_import_and_expr(first_model)
|
|
257
|
+
else:
|
|
258
|
+
pimp = "import { openai } from '@ai-sdk/openai';"
|
|
259
|
+
pexpr = "openai('gpt-4o')"
|
|
260
|
+
|
|
261
|
+
c = f'''\
|
|
262
|
+
/**
|
|
263
|
+
* Mastra Agent Network for {plan.project_name}.
|
|
264
|
+
*
|
|
265
|
+
* createNetwork coordinates multiple agents, allowing them to hand off
|
|
266
|
+
* tasks to each other based on the network router's decisions.
|
|
267
|
+
*/
|
|
268
|
+
import {{ createNetwork }} from '@mastra/core/network';
|
|
269
|
+
{pimp}
|
|
270
|
+
import {{ {', '.join(agent_exports[ak] for ak in agent_names)} }} from './agent.js';
|
|
271
|
+
|
|
272
|
+
export const {network_export} = createNetwork({{
|
|
273
|
+
name: "{plan.project_name} Network",
|
|
274
|
+
agents: [{", ".join(agent_exports[ak] for ak in agent_names)}],
|
|
275
|
+
defaultModel: {pexpr},
|
|
276
|
+
/**
|
|
277
|
+
* Optional: custom router to control which agent handles each message.
|
|
278
|
+
* router: async ({{ network, messages, runtimeContext }}) => {{ ... }}
|
|
279
|
+
*/
|
|
280
|
+
}});
|
|
281
|
+
'''
|
|
282
|
+
rel = "src/network.ts"
|
|
283
|
+
write_file(out_dir, rel, c)
|
|
284
|
+
return [rel]
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _workflow_graph(wf, ds: DiagnosticSet, plan: GenerationPlan) -> dict:
|
|
288
|
+
"""Work out how the workflow edges map onto the Mastra flow entries.
|
|
289
|
+
|
|
290
|
+
Mastra builds a workflow as a chain of flow entries: ``.then(step)``,
|
|
291
|
+
``.branch([[condition, step]])``, ``.parallel([steps])`` and
|
|
292
|
+
``.dowhile(step, condition)``. The AgentsML edges decide which entry
|
|
293
|
+
follows which step.
|
|
294
|
+
"""
|
|
295
|
+
step_ids = [s.id for s in wf.steps]
|
|
296
|
+
successors: dict[str, list[str]] = {sid: [] for sid in step_ids}
|
|
297
|
+
conditions: dict[str, list[tuple[str, str]]] = {sid: [] for sid in step_ids}
|
|
298
|
+
predecessors: dict[str, list[str]] = {sid: [] for sid in step_ids}
|
|
299
|
+
edge_path = f"workflows.{plan.main_workflow_key}.edges"
|
|
300
|
+
|
|
301
|
+
if wf.edges:
|
|
302
|
+
for edge in wf.edges:
|
|
303
|
+
if edge.from_step not in successors or edge.to_step not in successors:
|
|
304
|
+
ds.add_warning(
|
|
305
|
+
DiagCode.AMBIGUOUS_REFERENCE,
|
|
306
|
+
f"Edge {edge.from_step} -> {edge.to_step} references an undeclared step.",
|
|
307
|
+
path=edge_path,
|
|
308
|
+
recommendation="Declare both steps in the workflow.",
|
|
309
|
+
)
|
|
310
|
+
continue
|
|
311
|
+
if edge.condition:
|
|
312
|
+
try:
|
|
313
|
+
predicate = compile_condition_js(str(edge.condition))
|
|
314
|
+
except ConditionError as exc:
|
|
315
|
+
ds.add_warning(
|
|
316
|
+
DiagCode.NONPORTABLE_EXPRESSION,
|
|
317
|
+
f"Condition on edge {edge.from_step} -> {edge.to_step} was not compiled "
|
|
318
|
+
f"({exc}); the edge is never taken.",
|
|
319
|
+
path=edge_path,
|
|
320
|
+
recommendation=(
|
|
321
|
+
"Use comparisons, &&, ||, ! and input/state/steps references."
|
|
322
|
+
),
|
|
323
|
+
)
|
|
324
|
+
continue
|
|
325
|
+
conditions[edge.from_step].append((predicate, edge.to_step))
|
|
326
|
+
predecessors[edge.to_step].append(edge.from_step)
|
|
327
|
+
else:
|
|
328
|
+
successors[edge.from_step].append(edge.to_step)
|
|
329
|
+
predecessors[edge.to_step].append(edge.from_step)
|
|
330
|
+
else:
|
|
331
|
+
for src, dst in zip(step_ids, step_ids[1:]):
|
|
332
|
+
successors[src].append(dst)
|
|
333
|
+
predecessors[dst].append(src)
|
|
334
|
+
|
|
335
|
+
for sid, targets in successors.items():
|
|
336
|
+
if len(targets) > 1:
|
|
337
|
+
ds.add_warning(
|
|
338
|
+
DiagCode.LOSSY_MAPPING,
|
|
339
|
+
f"Step '{sid}' has {len(targets)} unconditional successors. The generated "
|
|
340
|
+
"Mastra workflow runs them as a .parallel() group.",
|
|
341
|
+
path=edge_path,
|
|
342
|
+
recommendation="Use a target with explicit fan-out semantics.",
|
|
343
|
+
)
|
|
344
|
+
for sid, sources in predecessors.items():
|
|
345
|
+
if len(sources) > 1:
|
|
346
|
+
ds.add_warning(
|
|
347
|
+
DiagCode.LOSSY_MAPPING,
|
|
348
|
+
f"Step '{sid}' joins {len(sources)} branches. The generated Mastra workflow "
|
|
349
|
+
"does not wait for all of them.",
|
|
350
|
+
path=edge_path,
|
|
351
|
+
recommendation="Use a target with join support, or merge the branches upstream.",
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
# Topological order; a cycle is broken at the first back edge.
|
|
355
|
+
order: list[str] = []
|
|
356
|
+
remaining = list(step_ids)
|
|
357
|
+
cycle_step: str | None = None
|
|
358
|
+
while remaining:
|
|
359
|
+
progressed = False
|
|
360
|
+
for sid in list(remaining):
|
|
361
|
+
pending = [p for p in predecessors[sid] if p in remaining]
|
|
362
|
+
if not pending:
|
|
363
|
+
order.append(sid)
|
|
364
|
+
remaining.remove(sid)
|
|
365
|
+
progressed = True
|
|
366
|
+
if not progressed:
|
|
367
|
+
cycle_step = remaining[0]
|
|
368
|
+
order.append(remaining.pop(0))
|
|
369
|
+
|
|
370
|
+
if cycle_step is not None:
|
|
371
|
+
ds.add_warning(
|
|
372
|
+
DiagCode.LOSSY_MAPPING,
|
|
373
|
+
f"The workflow contains a cycle at step '{cycle_step}'. The generated Mastra "
|
|
374
|
+
"workflow repeats that step with a bounded iteration count.",
|
|
375
|
+
path=edge_path,
|
|
376
|
+
recommendation="Set an explicit iteration budget for the loop.",
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
return {
|
|
380
|
+
"successors": successors,
|
|
381
|
+
"conditions": conditions,
|
|
382
|
+
"predecessors": predecessors,
|
|
383
|
+
"order": order,
|
|
384
|
+
"cycle_step": cycle_step,
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _write_workflow(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
|
|
389
|
+
"""Generate a Mastra workflow that follows the AgentsML workflow edges."""
|
|
390
|
+
wf = ir.workflows.get(plan.main_workflow_key)
|
|
391
|
+
if not wf or not wf.steps:
|
|
392
|
+
return []
|
|
393
|
+
|
|
394
|
+
steps = wf.steps
|
|
395
|
+
agent_exports = _ts_symbol_map(list(ir.agents.keys()), prefix="agent", suffix="Agent")
|
|
396
|
+
step_exports = _ts_symbol_map([s.id for s in steps], prefix="step", suffix="Step")
|
|
397
|
+
workflow_export = _mastra_export_name(plan, "Workflow")
|
|
398
|
+
|
|
399
|
+
graph = _workflow_graph(wf, ds, plan)
|
|
400
|
+
successors: dict[str, list[str]] = graph["successors"]
|
|
401
|
+
conditions: dict[str, list[str]] = graph["conditions"]
|
|
402
|
+
order: list[str] = graph["order"]
|
|
403
|
+
cycle_step: str | None = graph["cycle_step"]
|
|
404
|
+
|
|
405
|
+
step_by_id = {s.id: s for s in steps}
|
|
406
|
+
|
|
407
|
+
# ── Step definitions ────────────────────────────────────────────────────
|
|
408
|
+
step_blocks: list[str] = []
|
|
409
|
+
for step in steps:
|
|
410
|
+
ak = step.agent or next(iter(ir.agents.keys()), "unknown")
|
|
411
|
+
var = step_exports[step.id]
|
|
412
|
+
step_blocks.append(f"""const {var} = createStep({{
|
|
413
|
+
id: "{step.id}",
|
|
414
|
+
inputSchema: z.any(),
|
|
415
|
+
outputSchema: z.object({{ output: z.string(), question: z.string().optional() }}).passthrough(),
|
|
416
|
+
execute: async ({{ inputData }}) => {{
|
|
417
|
+
const previous = (inputData ?? {{}}) as Record<string, unknown>;
|
|
418
|
+
workflowContext.input = {{ ...workflowContext.input, ...previous }};
|
|
419
|
+
const q = (previous.question as string) ?? (workflowContext.input.question as string) ?? "";
|
|
420
|
+
// Agent: {ak}
|
|
421
|
+
const result = await {agent_exports[ak]}.generate(q);
|
|
422
|
+
const output = {{ output: result.text, question: q }};
|
|
423
|
+
workflowContext.steps["{step.id}"] = {{ output: output.output }};
|
|
424
|
+
return output;
|
|
425
|
+
}},
|
|
426
|
+
}});""")
|
|
427
|
+
|
|
428
|
+
# ── Flow entries ────────────────────────────────────────────────────────
|
|
429
|
+
entries: list[str] = []
|
|
430
|
+
added: set[str] = set()
|
|
431
|
+
for sid in order:
|
|
432
|
+
if sid in added:
|
|
433
|
+
continue
|
|
434
|
+
step = step_by_id[sid]
|
|
435
|
+
var = step_exports[sid]
|
|
436
|
+
added.add(sid)
|
|
437
|
+
entries.append(f" .then({var})")
|
|
438
|
+
|
|
439
|
+
conds = conditions.get(sid, [])
|
|
440
|
+
uncond = successors.get(sid, [])
|
|
441
|
+
if conds:
|
|
442
|
+
# Exclusive branches: the first matching condition wins.
|
|
443
|
+
branches: list[str] = []
|
|
444
|
+
seen_predicates: list[str] = []
|
|
445
|
+
for predicate, target in conds:
|
|
446
|
+
guard = " && ".join([f"!({p})" for p in seen_predicates])
|
|
447
|
+
expression = f"{predicate} && {guard}" if guard else predicate
|
|
448
|
+
seen_predicates.append(predicate)
|
|
449
|
+
branches.append(
|
|
450
|
+
f" [async () => {expression}, {step_exports[target]}]"
|
|
451
|
+
)
|
|
452
|
+
added.add(target)
|
|
453
|
+
if uncond:
|
|
454
|
+
fallback = uncond[0]
|
|
455
|
+
guard = " && ".join([f"!({p})" for p in seen_predicates])
|
|
456
|
+
expression = guard if guard else "true"
|
|
457
|
+
branches.append(f" [async () => {expression}, {step_exports[fallback]}]")
|
|
458
|
+
added.add(fallback)
|
|
459
|
+
entries.append(" .branch([\n" + ",\n".join(branches) + "\n ])")
|
|
460
|
+
elif len(uncond) > 1:
|
|
461
|
+
group = ", ".join(step_exports[t] for t in uncond)
|
|
462
|
+
entries.append(f" .parallel([{group}])")
|
|
463
|
+
for target in uncond:
|
|
464
|
+
added.add(target)
|
|
465
|
+
elif uncond:
|
|
466
|
+
target = uncond[0]
|
|
467
|
+
if target not in added:
|
|
468
|
+
entries.append(f" .then({step_exports[target]})")
|
|
469
|
+
added.add(target)
|
|
470
|
+
|
|
471
|
+
if cycle_step is not None:
|
|
472
|
+
var = step_exports[cycle_step]
|
|
473
|
+
entries.append(
|
|
474
|
+
" .dowhile(\n"
|
|
475
|
+
f" {var},\n"
|
|
476
|
+
" async ({ iterationCount }) => iterationCount < WORKFLOW_MAX_ITERATIONS,\n"
|
|
477
|
+
" )"
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
steps_chain = "\n".join(entries)
|
|
481
|
+
|
|
482
|
+
c = f"""/**
|
|
483
|
+
* Mastra Workflow for {plan.project_name}.
|
|
484
|
+
*
|
|
485
|
+
* The workflow follows the AgentsML workflow edges: .then() for the default
|
|
486
|
+
* successor, .branch() for conditional edges, .parallel() for a fan-out and
|
|
487
|
+
* .dowhile() for a cycle.
|
|
488
|
+
*/
|
|
489
|
+
import {{ createWorkflow, createStep }} from '@mastra/core/workflows';
|
|
490
|
+
import {{ z }} from 'zod';
|
|
491
|
+
import {{ {', '.join(agent_exports[ak] for ak in ir.agents.keys())} }} from './agent.js';
|
|
492
|
+
|
|
493
|
+
/** Upper bound for a generated loop; AgentsML cycles carry no budget. */
|
|
494
|
+
export const WORKFLOW_MAX_ITERATIONS = 10;
|
|
495
|
+
|
|
496
|
+
/** The context the compiled edge conditions read. */
|
|
497
|
+
export const workflowContext: {{
|
|
498
|
+
input: Record<string, unknown>;
|
|
499
|
+
state: Record<string, unknown>;
|
|
500
|
+
steps: Record<string, {{ output: unknown }}>;
|
|
501
|
+
}} = {{ input: {{}}, state: {{}}, steps: {{}} }};
|
|
502
|
+
|
|
503
|
+
/** Alias the compiled edge conditions read. */
|
|
504
|
+
const ctx = workflowContext;
|
|
505
|
+
|
|
506
|
+
const OPERATORS: Record<string, (a: unknown, b: unknown) => boolean> = {{
|
|
507
|
+
'==': (a, b) => a == b,
|
|
508
|
+
'!=': (a, b) => a != b,
|
|
509
|
+
'<': (a, b) => a < b,
|
|
510
|
+
'<=': (a, b) => a <= b,
|
|
511
|
+
'>': (a, b) => a > b,
|
|
512
|
+
'>=': (a, b) => a >= b,
|
|
513
|
+
}};
|
|
514
|
+
|
|
515
|
+
export function compare(left: unknown, op: string, right: unknown): boolean {{
|
|
516
|
+
try {{
|
|
517
|
+
return Boolean(OPERATORS[op](left, right));
|
|
518
|
+
}} catch {{
|
|
519
|
+
return false;
|
|
520
|
+
}}
|
|
521
|
+
}}
|
|
522
|
+
|
|
523
|
+
export function lookup(ctx: Record<string, unknown>, path: string): unknown {{
|
|
524
|
+
let value: unknown = ctx;
|
|
525
|
+
for (const part of path.split('.')) {{
|
|
526
|
+
if (value && typeof value === 'object' && part in (value as object)) {{
|
|
527
|
+
value = (value as Record<string, unknown>)[part];
|
|
528
|
+
}} else if (Array.isArray(value) && /^\\d+$/.test(part) && Number(part) < value.length) {{
|
|
529
|
+
value = value[Number(part)];
|
|
530
|
+
}} else {{
|
|
531
|
+
return undefined;
|
|
532
|
+
}}
|
|
533
|
+
}}
|
|
534
|
+
return value;
|
|
535
|
+
}}
|
|
536
|
+
|
|
537
|
+
// ── Steps ────────────────────────────────────────────────────────────────────
|
|
538
|
+
|
|
539
|
+
{chr(10).join(step_blocks)}
|
|
540
|
+
|
|
541
|
+
// ── Workflow ─────────────────────────────────────────────────────────────────
|
|
542
|
+
|
|
543
|
+
export const {workflow_export} = createWorkflow({{
|
|
544
|
+
inputSchema: z.object({{ question: z.string().optional() }}).passthrough(),
|
|
545
|
+
outputSchema: z.object({{ output: z.string().optional() }}).passthrough(),
|
|
546
|
+
}})
|
|
547
|
+
{steps_chain}
|
|
548
|
+
.commit();
|
|
549
|
+
"""
|
|
550
|
+
rel = "src/workflow.ts"
|
|
551
|
+
write_file(out_dir, rel, c)
|
|
552
|
+
return [rel]
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _write_index(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, is_multi: bool) -> list[str]:
|
|
556
|
+
network_export = _mastra_export_name(plan, "Network")
|
|
557
|
+
workflow_export = _mastra_export_name(plan, "Workflow")
|
|
558
|
+
network_import = f"import {{ {network_export} }} from './network.js';" if is_multi else ""
|
|
559
|
+
workflow_import = f"import {{ {workflow_export} }} from './workflow.js';" if ir.workflows else ""
|
|
560
|
+
|
|
561
|
+
network_reg = f"\n networks: {{ {network_export} }}," if is_multi else ""
|
|
562
|
+
workflow_reg = f"\n workflows: {{ {workflow_export} }}," if ir.workflows else ""
|
|
563
|
+
network_run = (
|
|
564
|
+
f"const networkResult = await {network_export}.generate(q);\n"
|
|
565
|
+
" console.log('Network result:', networkResult.text);"
|
|
566
|
+
if is_multi else ""
|
|
567
|
+
)
|
|
568
|
+
single_agent_run = "" if is_multi else """const agentKeys = Object.keys(agents);
|
|
569
|
+
if (agentKeys.length > 0) {
|
|
570
|
+
const agent = (agents as any)[agentKeys[0]];
|
|
571
|
+
const res = await agent.generate(q);
|
|
572
|
+
console.log(res.text);
|
|
573
|
+
}"""
|
|
574
|
+
|
|
575
|
+
c = f'''\
|
|
576
|
+
import {{ Mastra }} from '@mastra/core';
|
|
577
|
+
import * as agents from './agent.js';
|
|
578
|
+
{network_import}
|
|
579
|
+
{workflow_import}
|
|
580
|
+
|
|
581
|
+
export const mastra = new Mastra({{
|
|
582
|
+
agents: {{ ...agents }},{network_reg}{workflow_reg}
|
|
583
|
+
}});
|
|
584
|
+
|
|
585
|
+
async function main() {{
|
|
586
|
+
const q = process.argv.slice(2).join(" ") || "Hello!";
|
|
587
|
+
|
|
588
|
+
// Multi-agent network execution
|
|
589
|
+
{network_run}
|
|
590
|
+
|
|
591
|
+
// Single agent fallback
|
|
592
|
+
{single_agent_run}
|
|
593
|
+
}}
|
|
594
|
+
|
|
595
|
+
if (process.argv[1] === import.meta.filename) {{
|
|
596
|
+
main().catch(console.error);
|
|
597
|
+
}}
|
|
598
|
+
'''
|
|
599
|
+
rel = "src/index.ts"
|
|
600
|
+
write_file(out_dir, rel, c)
|
|
601
|
+
return [rel]
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _write_readme(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path, is_multi: bool) -> list[str]:
|
|
605
|
+
network_note = ""
|
|
606
|
+
if is_multi:
|
|
607
|
+
network_export = _mastra_export_name(plan, "Network")
|
|
608
|
+
network_note = f"""
|
|
609
|
+
## Multi-agent Network (`createNetwork`)
|
|
610
|
+
|
|
611
|
+
`{network_export}` coordinates {len(ir.agents)} agents.
|
|
612
|
+
The network router decides which agent handles each message.
|
|
613
|
+
Customize with a `router` function in `src/network.ts`.
|
|
614
|
+
|
|
615
|
+
```typescript
|
|
616
|
+
import {{ {network_export} }} from './src/network.js';
|
|
617
|
+
const result = await {network_export}.generate("your question");
|
|
618
|
+
```
|
|
619
|
+
"""
|
|
620
|
+
|
|
621
|
+
c = f"""\
|
|
622
|
+
# {plan.project_name} — Mastra
|
|
623
|
+
{network_note}
|
|
624
|
+
> Auto-generated by `agentsml-impl`.
|
|
625
|
+
|
|
626
|
+
## Quickstart
|
|
627
|
+
```bash
|
|
628
|
+
npm install
|
|
629
|
+
npm run dev "Your question here"
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
> See `diagnostics.yaml` for portability warnings.
|
|
633
|
+
"""
|
|
634
|
+
write_file(out_dir, "README.md", c)
|
|
635
|
+
return ["README.md"]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
target: mastra
|
|
2
|
+
kind: code
|
|
3
|
+
language: typescript
|
|
4
|
+
status: implemented
|
|
5
|
+
level: 1
|
|
6
|
+
version_tested: "1.83.0"
|
|
7
|
+
supports:
|
|
8
|
+
agents: native
|
|
9
|
+
tools: native
|
|
10
|
+
workflows: native
|
|
11
|
+
graph_edges: native
|
|
12
|
+
graph_conditions: native
|
|
13
|
+
cycles: native
|
|
14
|
+
parallel: native
|
|
15
|
+
human_approval: adapter
|
|
16
|
+
mcp: adapter
|
|
17
|
+
a2a: manual
|
|
18
|
+
ag_ui: adapter
|
|
19
|
+
structured_output: manual
|
|
20
|
+
observability: native
|
|
21
|
+
artifacts:
|
|
22
|
+
- node_project
|
|
23
|
+
- diagnostics
|
|
24
|
+
- readme
|
|
25
|
+
notes: >
|
|
26
|
+
Mastra maps AgentsML to TypeScript @mastra/core Agent and Workflow.
|
|
27
|
+
The generated workflow uses the modern @mastra/core API (createWorkflow and
|
|
28
|
+
createStep): the workflow edges become .then() entries, conditional edges
|
|
29
|
+
become .branch() entries with mutually exclusive predicates, a fan-out
|
|
30
|
+
becomes .parallel() and a cycle becomes a bounded .dowhile() loop. A step
|
|
31
|
+
that joins several branches is reported as lossy because the generated
|
|
32
|
+
workflow does not wait for all of them. Structured output is not generated.
|
|
File without changes
|