agents-for-everything 0.1.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.
- agents_for_everything/__init__.py +67 -0
- agents_for_everything/_compat.py +403 -0
- agents_for_everything/exporters.py +163 -0
- agents_for_everything/manifest.py +342 -0
- agents_for_everything/mcp.py +269 -0
- agents_for_everything/migrate.py +159 -0
- agents_for_everything/models.py +157 -0
- agents_for_everything/providers/__init__.py +22 -0
- agents_for_everything/providers/_http.py +54 -0
- agents_for_everything/providers/anthropic_provider.py +56 -0
- agents_for_everything/providers/base.py +54 -0
- agents_for_everything/providers/factory.py +71 -0
- agents_for_everything/providers/gemini_provider.py +56 -0
- agents_for_everything/providers/mock.py +60 -0
- agents_for_everything/providers/ollama_provider.py +50 -0
- agents_for_everything/providers/openai_compat.py +54 -0
- agents_for_everything/runner.py +269 -0
- agents_for_everything/safety.py +122 -0
- agents_for_everything/team_runner.py +181 -0
- agents_for_everything/tracing.py +67 -0
- agents_for_everything/verify.py +157 -0
- agents_for_everything-0.1.0.dist-info/METADATA +27 -0
- agents_for_everything-0.1.0.dist-info/RECORD +25 -0
- agents_for_everything-0.1.0.dist-info/WHEEL +5 -0
- agents_for_everything-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Core runtime for Agents for Everything (afe/v1)."""
|
|
2
|
+
|
|
3
|
+
from .exporters import export_agent
|
|
4
|
+
from .manifest import (
|
|
5
|
+
check_schema_compatibility,
|
|
6
|
+
discover_agents,
|
|
7
|
+
discover_mcp_servers,
|
|
8
|
+
discover_recipes,
|
|
9
|
+
discover_teams,
|
|
10
|
+
find_repo_root,
|
|
11
|
+
load_agent_manifest,
|
|
12
|
+
load_recipe_manifest,
|
|
13
|
+
load_team_manifest,
|
|
14
|
+
validate_agent_dir,
|
|
15
|
+
)
|
|
16
|
+
from .mcp import LocalMCPRegistry
|
|
17
|
+
from .migrate import dump_yaml, migrate_agent_dir, upgrade_manifest_v1_to_v2
|
|
18
|
+
from .models import (
|
|
19
|
+
AgentManifest,
|
|
20
|
+
MCPServerManifest,
|
|
21
|
+
RecipeManifest,
|
|
22
|
+
RunContext,
|
|
23
|
+
RunResult,
|
|
24
|
+
TeamManifest,
|
|
25
|
+
)
|
|
26
|
+
from .providers.factory import resolve_provider
|
|
27
|
+
from .runner import AgentRunner, BaseAgentImplementation
|
|
28
|
+
from .safety import ApprovalRequiredError, BudgetExceededError, SafetyPolicy
|
|
29
|
+
from .team_runner import TeamRunner
|
|
30
|
+
from .tracing import TraceCollector
|
|
31
|
+
from .verify import VerificationRecord, compute_contract_digest, verify_agent_dir, verify_repository_agents
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"AgentManifest",
|
|
35
|
+
"AgentRunner",
|
|
36
|
+
"ApprovalRequiredError",
|
|
37
|
+
"BaseAgentImplementation",
|
|
38
|
+
"BudgetExceededError",
|
|
39
|
+
"LocalMCPRegistry",
|
|
40
|
+
"MCPServerManifest",
|
|
41
|
+
"RecipeManifest",
|
|
42
|
+
"RunContext",
|
|
43
|
+
"RunResult",
|
|
44
|
+
"SafetyPolicy",
|
|
45
|
+
"TeamManifest",
|
|
46
|
+
"TeamRunner",
|
|
47
|
+
"TraceCollector",
|
|
48
|
+
"VerificationRecord",
|
|
49
|
+
"check_schema_compatibility",
|
|
50
|
+
"compute_contract_digest",
|
|
51
|
+
"discover_agents",
|
|
52
|
+
"discover_mcp_servers",
|
|
53
|
+
"discover_recipes",
|
|
54
|
+
"discover_teams",
|
|
55
|
+
"dump_yaml",
|
|
56
|
+
"export_agent",
|
|
57
|
+
"find_repo_root",
|
|
58
|
+
"load_agent_manifest",
|
|
59
|
+
"load_recipe_manifest",
|
|
60
|
+
"load_team_manifest",
|
|
61
|
+
"migrate_agent_dir",
|
|
62
|
+
"resolve_provider",
|
|
63
|
+
"upgrade_manifest_v1_to_v2",
|
|
64
|
+
"validate_agent_dir",
|
|
65
|
+
"verify_agent_dir",
|
|
66
|
+
"verify_repository_agents",
|
|
67
|
+
]
|
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""Compatibility helpers: YAML parsing and JSON Schema 2020-12 validation.
|
|
2
|
+
|
|
3
|
+
Uses PyYAML / jsonschema when installed, and falls back to clean stdlib
|
|
4
|
+
implementations so core-python runs with zero external dependencies.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
import yaml as _pyyaml # type: ignore
|
|
16
|
+
except ImportError: # pragma: no cover
|
|
17
|
+
_pyyaml = None
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
import jsonschema as _jsonschema # type: ignore
|
|
21
|
+
except ImportError: # pragma: no cover
|
|
22
|
+
_jsonschema = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class YAMLParseError(ValueError):
|
|
26
|
+
"""Raised when YAML parsing fails."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class SchemaValidationError(ValueError):
|
|
30
|
+
"""Raised when JSON Schema validation fails."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _strip_comment(line: str) -> str:
|
|
34
|
+
in_single = False
|
|
35
|
+
in_double = False
|
|
36
|
+
escaped = False
|
|
37
|
+
for idx, ch in enumerate(line):
|
|
38
|
+
if escaped:
|
|
39
|
+
escaped = False
|
|
40
|
+
continue
|
|
41
|
+
if ch == "\\" and in_double:
|
|
42
|
+
escaped = True
|
|
43
|
+
continue
|
|
44
|
+
if ch == "'" and not in_double:
|
|
45
|
+
in_single = not in_single
|
|
46
|
+
elif ch == '"' and not in_single:
|
|
47
|
+
in_double = not in_double
|
|
48
|
+
elif ch == "#" and not in_single and not in_double:
|
|
49
|
+
if idx == 0 or line[idx - 1].isspace():
|
|
50
|
+
return line[:idx].rstrip()
|
|
51
|
+
return line.rstrip()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _split_top_level(text: str, sep: str = ",") -> list[str]:
|
|
55
|
+
parts: list[str] = []
|
|
56
|
+
buf: list[str] = []
|
|
57
|
+
depth = 0
|
|
58
|
+
in_single = False
|
|
59
|
+
in_double = False
|
|
60
|
+
escaped = False
|
|
61
|
+
for ch in text:
|
|
62
|
+
if escaped:
|
|
63
|
+
buf.append(ch)
|
|
64
|
+
escaped = False
|
|
65
|
+
continue
|
|
66
|
+
if ch == "\\" and in_double:
|
|
67
|
+
buf.append(ch)
|
|
68
|
+
escaped = True
|
|
69
|
+
continue
|
|
70
|
+
if ch == "'" and not in_double:
|
|
71
|
+
in_single = not in_single
|
|
72
|
+
elif ch == '"' and not in_single:
|
|
73
|
+
in_double = not in_double
|
|
74
|
+
elif not in_single and not in_double:
|
|
75
|
+
if ch in "{[":
|
|
76
|
+
depth += 1
|
|
77
|
+
elif ch in "}]":
|
|
78
|
+
depth -= 1
|
|
79
|
+
elif ch == sep and depth == 0:
|
|
80
|
+
part = "".join(buf).strip()
|
|
81
|
+
if part:
|
|
82
|
+
parts.append(part)
|
|
83
|
+
buf = []
|
|
84
|
+
continue
|
|
85
|
+
buf.append(ch)
|
|
86
|
+
tail = "".join(buf).strip()
|
|
87
|
+
if tail:
|
|
88
|
+
parts.append(tail)
|
|
89
|
+
return parts
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _parse_scalar(raw: str) -> Any:
|
|
93
|
+
val = raw.strip()
|
|
94
|
+
if val == "" or val in {"null", "Null", "NULL", "~"}:
|
|
95
|
+
return None
|
|
96
|
+
if val in {"true", "True", "TRUE"}:
|
|
97
|
+
return True
|
|
98
|
+
if val in {"false", "False", "FALSE"}:
|
|
99
|
+
return False
|
|
100
|
+
if val.startswith('"') and val.endswith('"') and len(val) >= 2:
|
|
101
|
+
try:
|
|
102
|
+
return json.loads(val)
|
|
103
|
+
except json.JSONDecodeError:
|
|
104
|
+
return val[1:-1]
|
|
105
|
+
if val.startswith("'") and val.endswith("'") and len(val) >= 2:
|
|
106
|
+
return val[1:-1].replace("''", "'")
|
|
107
|
+
if val.startswith("[") and val.endswith("]"):
|
|
108
|
+
inner = val[1:-1].strip()
|
|
109
|
+
if not inner:
|
|
110
|
+
return []
|
|
111
|
+
return [_parse_scalar(item) for item in _split_top_level(inner)]
|
|
112
|
+
if val.startswith("{") and val.endswith("}"):
|
|
113
|
+
inner = val[1:-1].strip()
|
|
114
|
+
if not inner:
|
|
115
|
+
return {}
|
|
116
|
+
out: dict[str, Any] = {}
|
|
117
|
+
for item in _split_top_level(inner):
|
|
118
|
+
if ":" not in item:
|
|
119
|
+
raise YAMLParseError(f"Invalid inline mapping entry: {item}")
|
|
120
|
+
k, v = item.split(":", 1)
|
|
121
|
+
out[str(_parse_scalar(k.strip()))] = _parse_scalar(v.strip())
|
|
122
|
+
return out
|
|
123
|
+
if re.fullmatch(r"-?[0-9]+", val):
|
|
124
|
+
return int(val)
|
|
125
|
+
if re.fullmatch(r"-?[0-9]+\.[0-9]+", val):
|
|
126
|
+
return float(val)
|
|
127
|
+
return val
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _find_mapping_colon(text: str) -> int:
|
|
131
|
+
in_single = False
|
|
132
|
+
in_double = False
|
|
133
|
+
escaped = False
|
|
134
|
+
for idx, ch in enumerate(text):
|
|
135
|
+
if escaped:
|
|
136
|
+
escaped = False
|
|
137
|
+
continue
|
|
138
|
+
if ch == "\\" and in_double:
|
|
139
|
+
escaped = True
|
|
140
|
+
continue
|
|
141
|
+
if ch == "'" and not in_double:
|
|
142
|
+
in_single = not in_single
|
|
143
|
+
elif ch == '"' and not in_single:
|
|
144
|
+
in_double = not in_double
|
|
145
|
+
elif ch == ":" and not in_single and not in_double:
|
|
146
|
+
if idx + 1 == len(text) or text[idx + 1].isspace():
|
|
147
|
+
return idx
|
|
148
|
+
return -1
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _parse_yaml_lite(text: str) -> Any:
|
|
152
|
+
raw_lines = text.splitlines()
|
|
153
|
+
tokens: list[tuple[int, str]] = []
|
|
154
|
+
idx = 0
|
|
155
|
+
while idx < len(raw_lines):
|
|
156
|
+
raw = raw_lines[idx]
|
|
157
|
+
if raw.strip() in {"---", "..."}:
|
|
158
|
+
idx += 1
|
|
159
|
+
continue
|
|
160
|
+
cleaned = _strip_comment(raw)
|
|
161
|
+
if not cleaned.strip():
|
|
162
|
+
idx += 1
|
|
163
|
+
continue
|
|
164
|
+
indent = len(cleaned) - len(cleaned.lstrip(" "))
|
|
165
|
+
tokens.append((indent, cleaned.lstrip(" ")))
|
|
166
|
+
idx += 1
|
|
167
|
+
|
|
168
|
+
if not tokens:
|
|
169
|
+
return {}
|
|
170
|
+
|
|
171
|
+
def parse_block_scalar(start_i: int, parent_indent: int, style: str) -> tuple[str, int]:
|
|
172
|
+
# Re-scan raw_lines preserving literal newlines after block header.
|
|
173
|
+
lines: list[str] = []
|
|
174
|
+
base_indent: int | None = None
|
|
175
|
+
i = start_i
|
|
176
|
+
while i < len(tokens):
|
|
177
|
+
ind, content = tokens[i]
|
|
178
|
+
if ind <= parent_indent:
|
|
179
|
+
break
|
|
180
|
+
if base_indent is None:
|
|
181
|
+
base_indent = ind
|
|
182
|
+
pad = " " * max(0, ind - base_indent)
|
|
183
|
+
lines.append(f"{pad}{content}")
|
|
184
|
+
i += 1
|
|
185
|
+
if style == ">":
|
|
186
|
+
return " ".join(part.strip() for part in lines), i
|
|
187
|
+
return "\n".join(lines), i
|
|
188
|
+
|
|
189
|
+
def parse_node(pos: int, min_indent: int) -> tuple[Any, int]:
|
|
190
|
+
indent, content = tokens[pos]
|
|
191
|
+
if content.startswith("- ") or content == "-":
|
|
192
|
+
return parse_seq(pos, indent)
|
|
193
|
+
return parse_map(pos, indent)
|
|
194
|
+
|
|
195
|
+
def parse_seq(pos: int, seq_indent: int) -> tuple[list[Any], int]:
|
|
196
|
+
items: list[Any] = []
|
|
197
|
+
while pos < len(tokens):
|
|
198
|
+
indent, content = tokens[pos]
|
|
199
|
+
if indent < seq_indent:
|
|
200
|
+
break
|
|
201
|
+
if indent > seq_indent or not (content.startswith("- ") or content == "-"):
|
|
202
|
+
break
|
|
203
|
+
rest = content[1:].strip()
|
|
204
|
+
if not rest:
|
|
205
|
+
if pos + 1 < len(tokens) and tokens[pos + 1][0] > indent:
|
|
206
|
+
val, pos = parse_node(pos + 1, indent + 1)
|
|
207
|
+
items.append(val)
|
|
208
|
+
else:
|
|
209
|
+
items.append(None)
|
|
210
|
+
pos += 1
|
|
211
|
+
continue
|
|
212
|
+
|
|
213
|
+
colon_idx = _find_mapping_colon(rest)
|
|
214
|
+
if colon_idx != -1 and not rest.startswith("{") and not rest.startswith("["):
|
|
215
|
+
# Sequence item starts a mapping on the same line: "- key: val"
|
|
216
|
+
first_key = str(_parse_scalar(rest[:colon_idx].strip()))
|
|
217
|
+
first_val_raw = rest[colon_idx + 1 :].strip()
|
|
218
|
+
item_indent = indent + 2
|
|
219
|
+
item_map: dict[str, Any] = {}
|
|
220
|
+
if first_val_raw in {">", "|", ">-", "|-"}:
|
|
221
|
+
val, pos = parse_block_scalar(pos + 1, item_indent, first_val_raw[0])
|
|
222
|
+
item_map[first_key] = val
|
|
223
|
+
elif first_val_raw == "":
|
|
224
|
+
if pos + 1 < len(tokens) and tokens[pos + 1][0] > item_indent:
|
|
225
|
+
val, pos = parse_node(pos + 1, item_indent + 1)
|
|
226
|
+
else:
|
|
227
|
+
val = None
|
|
228
|
+
pos += 1
|
|
229
|
+
item_map[first_key] = val
|
|
230
|
+
else:
|
|
231
|
+
item_map[first_key] = _parse_scalar(first_val_raw)
|
|
232
|
+
pos += 1
|
|
233
|
+
# Parse remaining sibling keys indented >= item_indent
|
|
234
|
+
if pos < len(tokens) and tokens[pos][0] >= item_indent:
|
|
235
|
+
if not (tokens[pos][1].startswith("- ") or tokens[pos][1] == "-"):
|
|
236
|
+
more, pos = parse_map(pos, tokens[pos][0])
|
|
237
|
+
item_map.update(more)
|
|
238
|
+
items.append(item_map)
|
|
239
|
+
else:
|
|
240
|
+
items.append(_parse_scalar(rest))
|
|
241
|
+
pos += 1
|
|
242
|
+
return items, pos
|
|
243
|
+
|
|
244
|
+
def parse_map(pos: int, map_indent: int) -> tuple[dict[str, Any], int]:
|
|
245
|
+
mapping: dict[str, Any] = {}
|
|
246
|
+
while pos < len(tokens):
|
|
247
|
+
indent, content = tokens[pos]
|
|
248
|
+
if indent < map_indent or indent > map_indent:
|
|
249
|
+
break
|
|
250
|
+
if content.startswith("- ") or content == "-":
|
|
251
|
+
break
|
|
252
|
+
colon_idx = _find_mapping_colon(content)
|
|
253
|
+
if colon_idx == -1:
|
|
254
|
+
raise YAMLParseError(f"Expected 'key: value' near: {content}")
|
|
255
|
+
key = str(_parse_scalar(content[:colon_idx].strip()))
|
|
256
|
+
val_raw = content[colon_idx + 1 :].strip()
|
|
257
|
+
if val_raw in {">", "|", ">-", "|-"}:
|
|
258
|
+
val, pos = parse_block_scalar(pos + 1, indent, val_raw[0])
|
|
259
|
+
mapping[key] = val
|
|
260
|
+
elif val_raw == "":
|
|
261
|
+
if pos + 1 < len(tokens) and tokens[pos + 1][0] > indent:
|
|
262
|
+
val, pos = parse_node(pos + 1, indent + 1)
|
|
263
|
+
elif pos + 1 < len(tokens) and tokens[pos + 1][0] == indent and (
|
|
264
|
+
tokens[pos + 1][1].startswith("- ") or tokens[pos + 1][1] == "-"
|
|
265
|
+
):
|
|
266
|
+
val, pos = parse_seq(pos + 1, indent)
|
|
267
|
+
else:
|
|
268
|
+
val = None
|
|
269
|
+
pos += 1
|
|
270
|
+
mapping[key] = val
|
|
271
|
+
else:
|
|
272
|
+
mapping[key] = _parse_scalar(val_raw)
|
|
273
|
+
pos += 1
|
|
274
|
+
return mapping, pos
|
|
275
|
+
|
|
276
|
+
parsed, _ = parse_node(0, tokens[0][0])
|
|
277
|
+
return parsed
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def load_yaml(text: str) -> Any:
|
|
281
|
+
"""Parse YAML text into Python objects."""
|
|
282
|
+
if _pyyaml is not None:
|
|
283
|
+
return _pyyaml.safe_load(text)
|
|
284
|
+
return _parse_yaml_lite(text)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def load_yaml_file(path: Path) -> Any:
|
|
288
|
+
"""Read and parse a YAML file."""
|
|
289
|
+
return load_yaml(path.read_text(encoding="utf-8"))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _resolve_ref(ref: str, types_dir: Path | None, root_schema: dict[str, Any]) -> dict[str, Any]:
|
|
293
|
+
if ref.startswith("afe://types/") and types_dir is not None:
|
|
294
|
+
name = ref.removeprefix("afe://types/")
|
|
295
|
+
if not name.endswith(".schema.json"):
|
|
296
|
+
name = f"{name}.schema.json"
|
|
297
|
+
target = types_dir / name
|
|
298
|
+
if target.exists():
|
|
299
|
+
return json.loads(target.read_text(encoding="utf-8"))
|
|
300
|
+
if ref.startswith("#/$defs/"):
|
|
301
|
+
key = ref.removeprefix("#/$defs/")
|
|
302
|
+
defs = root_schema.get("$defs", {})
|
|
303
|
+
if key in defs:
|
|
304
|
+
return defs[key]
|
|
305
|
+
return {}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _type_matches(value: Any, expected: str | list[str]) -> bool:
|
|
309
|
+
if isinstance(expected, list):
|
|
310
|
+
return any(_type_matches(value, t) for t in expected)
|
|
311
|
+
if expected == "object":
|
|
312
|
+
return isinstance(value, dict)
|
|
313
|
+
if expected == "array":
|
|
314
|
+
return isinstance(value, list)
|
|
315
|
+
if expected == "string":
|
|
316
|
+
return isinstance(value, str)
|
|
317
|
+
if expected == "integer":
|
|
318
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
319
|
+
if expected == "number":
|
|
320
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
321
|
+
if expected == "boolean":
|
|
322
|
+
return isinstance(value, bool)
|
|
323
|
+
if expected == "null":
|
|
324
|
+
return value is None
|
|
325
|
+
return True
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _validate_lite(
|
|
329
|
+
instance: Any,
|
|
330
|
+
schema: dict[str, Any],
|
|
331
|
+
types_dir: Path | None,
|
|
332
|
+
root_schema: dict[str, Any],
|
|
333
|
+
path: str,
|
|
334
|
+
errors: list[str],
|
|
335
|
+
) -> None:
|
|
336
|
+
if "$ref" in schema:
|
|
337
|
+
resolved = _resolve_ref(schema["$ref"], types_dir, root_schema)
|
|
338
|
+
if resolved:
|
|
339
|
+
_validate_lite(instance, resolved, types_dir, resolved, path, errors)
|
|
340
|
+
return
|
|
341
|
+
|
|
342
|
+
if "const" in schema and instance != schema["const"]:
|
|
343
|
+
errors.append(f"{path}: expected constant {schema['const']!r}, got {instance!r}")
|
|
344
|
+
return
|
|
345
|
+
|
|
346
|
+
if "enum" in schema and instance not in schema["enum"]:
|
|
347
|
+
errors.append(f"{path}: value {instance!r} not in allowed enum {schema['enum']}")
|
|
348
|
+
return
|
|
349
|
+
|
|
350
|
+
if "type" in schema and not _type_matches(instance, schema["type"]):
|
|
351
|
+
errors.append(f"{path}: expected type {schema['type']}, got {type(instance).__name__}")
|
|
352
|
+
return
|
|
353
|
+
|
|
354
|
+
if isinstance(instance, str):
|
|
355
|
+
if "minLength" in schema and len(instance) < schema["minLength"]:
|
|
356
|
+
errors.append(f"{path}: length {len(instance)} < minLength {schema['minLength']}")
|
|
357
|
+
if "maxLength" in schema and len(instance) > schema["maxLength"]:
|
|
358
|
+
errors.append(f"{path}: length {len(instance)} > maxLength {schema['maxLength']}")
|
|
359
|
+
if "pattern" in schema and re.search(schema["pattern"], instance) is None:
|
|
360
|
+
errors.append(f"{path}: {instance!r} does not match pattern {schema['pattern']!r}")
|
|
361
|
+
|
|
362
|
+
if isinstance(instance, (int, float)) and not isinstance(instance, bool):
|
|
363
|
+
if "minimum" in schema and instance < schema["minimum"]:
|
|
364
|
+
errors.append(f"{path}: {instance} < minimum {schema['minimum']}")
|
|
365
|
+
if "maximum" in schema and instance > schema["maximum"]:
|
|
366
|
+
errors.append(f"{path}: {instance} > maximum {schema['maximum']}")
|
|
367
|
+
|
|
368
|
+
if isinstance(instance, list):
|
|
369
|
+
if "minItems" in schema and len(instance) < schema["minItems"]:
|
|
370
|
+
errors.append(f"{path}: item count {len(instance)} < minItems {schema['minItems']}")
|
|
371
|
+
item_schema = schema.get("items")
|
|
372
|
+
if isinstance(item_schema, dict):
|
|
373
|
+
for idx, item in enumerate(instance):
|
|
374
|
+
_validate_lite(item, item_schema, types_dir, root_schema, f"{path}[{idx}]", errors)
|
|
375
|
+
|
|
376
|
+
if isinstance(instance, dict):
|
|
377
|
+
props = schema.get("properties", {})
|
|
378
|
+
for req in schema.get("required", []):
|
|
379
|
+
if req not in instance:
|
|
380
|
+
errors.append(f"{path}: missing required property {req!r}")
|
|
381
|
+
add_props = schema.get("additionalProperties", True)
|
|
382
|
+
for key, val in instance.items():
|
|
383
|
+
if key in props:
|
|
384
|
+
_validate_lite(val, props[key], types_dir, root_schema, f"{path}.{key}", errors)
|
|
385
|
+
elif add_props is False:
|
|
386
|
+
errors.append(f"{path}: unexpected property {key!r}")
|
|
387
|
+
elif isinstance(add_props, dict):
|
|
388
|
+
_validate_lite(val, add_props, types_dir, root_schema, f"{path}.{key}", errors)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def validate_json_schema(
|
|
392
|
+
instance: Any,
|
|
393
|
+
schema: dict[str, Any],
|
|
394
|
+
types_dir: Path | None = None,
|
|
395
|
+
) -> list[str]:
|
|
396
|
+
"""Validate an instance against a JSON Schema, returning error messages."""
|
|
397
|
+
if _jsonschema is not None and types_dir is None:
|
|
398
|
+
validator = _jsonschema.Draft202012Validator(schema)
|
|
399
|
+
return [err.message for err in validator.iter_errors(instance)]
|
|
400
|
+
|
|
401
|
+
errors: list[str] = []
|
|
402
|
+
_validate_lite(instance, schema, types_dir, schema, "$", errors)
|
|
403
|
+
return errors
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Portable exporters for A2A Agent Cards, Agent Skills, MCP servers, subagents, and LangGraph."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .manifest import load_agent_manifest
|
|
10
|
+
from .models import AgentManifest
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build_a2a_card(manifest: AgentManifest, input_schema: dict[str, Any], output_schema: dict[str, Any]) -> dict[str, Any]:
|
|
14
|
+
"""Generate an A2A-compliant Agent Card dictionary."""
|
|
15
|
+
return {
|
|
16
|
+
"name": manifest.name,
|
|
17
|
+
"id": manifest.id,
|
|
18
|
+
"version": manifest.version,
|
|
19
|
+
"description": manifest.summary,
|
|
20
|
+
"capabilities": {
|
|
21
|
+
"streaming": manifest.pattern in {"react", "plan-and-execute"},
|
|
22
|
+
"stateTransitionHistory": manifest.memory != "none",
|
|
23
|
+
},
|
|
24
|
+
"skills": [
|
|
25
|
+
{
|
|
26
|
+
"id": manifest.id,
|
|
27
|
+
"name": manifest.name,
|
|
28
|
+
"description": manifest.purpose,
|
|
29
|
+
"tags": manifest.tags,
|
|
30
|
+
"inputSchema": input_schema,
|
|
31
|
+
"outputSchema": output_schema,
|
|
32
|
+
}
|
|
33
|
+
],
|
|
34
|
+
"metadata": {
|
|
35
|
+
"safetyLevel": manifest.safety_level,
|
|
36
|
+
"autonomyLevel": manifest.autonomy,
|
|
37
|
+
"maturity": manifest.maturity,
|
|
38
|
+
"license": manifest.license,
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def build_agent_skill_md(manifest: AgentManifest, system_prompt: str) -> str:
|
|
44
|
+
"""Generate an open Agent Skills (`SKILL.md`) file."""
|
|
45
|
+
slug = manifest.id.split("/", 1)[-1]
|
|
46
|
+
return (
|
|
47
|
+
"---\n"
|
|
48
|
+
f"name: {slug}\n"
|
|
49
|
+
f"description: {manifest.summary}\n"
|
|
50
|
+
"---\n\n"
|
|
51
|
+
f"# {manifest.name} (`{manifest.id}`)\n\n"
|
|
52
|
+
f"{manifest.purpose}\n\n"
|
|
53
|
+
"## Instructions\n\n"
|
|
54
|
+
f"{system_prompt.strip()}\n"
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def build_mcp_wrapper_py(manifest: AgentManifest) -> str:
|
|
59
|
+
"""Generate a standalone runnable MCP stdio wrapper for an agent."""
|
|
60
|
+
return f'''"""Generated MCP wrapper for {manifest.id}."""
|
|
61
|
+
import json
|
|
62
|
+
import sys
|
|
63
|
+
from agents_for_everything import AgentRunner
|
|
64
|
+
|
|
65
|
+
def main() -> None:
|
|
66
|
+
runner = AgentRunner()
|
|
67
|
+
for line in sys.stdin:
|
|
68
|
+
if not line.strip():
|
|
69
|
+
continue
|
|
70
|
+
req = json.loads(line)
|
|
71
|
+
params = req.get("params", {{}})
|
|
72
|
+
result = runner.run("{manifest.id}", params)
|
|
73
|
+
sys.stdout.write(json.dumps({{"id": req.get("id"), "result": result.output}}) + "\\n")
|
|
74
|
+
sys.stdout.flush()
|
|
75
|
+
|
|
76
|
+
if __name__ == "__main__":
|
|
77
|
+
main()
|
|
78
|
+
'''
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def build_subagent_md(manifest: AgentManifest, system_prompt: str) -> str:
|
|
82
|
+
"""Generate a Claude Code / Antigravity compatible subagent Markdown file."""
|
|
83
|
+
slug = manifest.id.split("/", 1)[-1]
|
|
84
|
+
tools_line = ", ".join(manifest.required_tools) if manifest.required_tools else "none"
|
|
85
|
+
return (
|
|
86
|
+
"---\n"
|
|
87
|
+
f"name: {slug}\n"
|
|
88
|
+
f"description: {manifest.summary}\n"
|
|
89
|
+
f"tools: {tools_line}\n"
|
|
90
|
+
"---\n\n"
|
|
91
|
+
f"{system_prompt.strip()}\n"
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def build_codex_subagent_toml(manifest: AgentManifest, system_prompt: str) -> str:
|
|
96
|
+
"""Generate a Codex-compatible `.toml` subagent definition."""
|
|
97
|
+
slug = manifest.id.split("/", 1)[-1]
|
|
98
|
+
escaped_prompt = system_prompt.strip().replace('"""', '\\"\\"\\"')
|
|
99
|
+
return (
|
|
100
|
+
f'name = "{slug}"\n'
|
|
101
|
+
f'id = "{manifest.id}"\n'
|
|
102
|
+
f'description = {json.dumps(manifest.summary)}\n'
|
|
103
|
+
f'safety_level = "{manifest.safety_level}"\n'
|
|
104
|
+
f'instructions = """\n{escaped_prompt}\n"""\n'
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def build_langgraph_stub_py(manifest: AgentManifest) -> str:
|
|
109
|
+
"""Generate a LangGraph node wrapper calling `agents_for_everything.AgentRunner`."""
|
|
110
|
+
fn_name = manifest.id.replace("/", "_").replace("-", "_")
|
|
111
|
+
return f'''"""LangGraph node wrapper for {manifest.id}."""
|
|
112
|
+
from typing import Any
|
|
113
|
+
from agents_for_everything import AgentRunner
|
|
114
|
+
|
|
115
|
+
_runner = AgentRunner()
|
|
116
|
+
|
|
117
|
+
def {fn_name}_node(state: dict[str, Any]) -> dict[str, Any]:
|
|
118
|
+
res = _runner.run("{manifest.id}", state)
|
|
119
|
+
return {{**state, **res.output}}
|
|
120
|
+
'''
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def export_agent(agent_dir: Path, target: str, out_dir: Path) -> list[Path]:
|
|
124
|
+
"""Export an agent folder into `a2a`, `skill`, `mcp-server`, `subagent`, or `langgraph`."""
|
|
125
|
+
manifest = load_agent_manifest(agent_dir)
|
|
126
|
+
slug = manifest.id.split("/", 1)[-1]
|
|
127
|
+
system_prompt = (agent_dir / "prompts" / "system.md").read_text(encoding="utf-8")
|
|
128
|
+
input_schema = json.loads((agent_dir / manifest.input_schema_path).read_text(encoding="utf-8"))
|
|
129
|
+
output_schema = json.loads((agent_dir / manifest.output_schema_path).read_text(encoding="utf-8"))
|
|
130
|
+
|
|
131
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
132
|
+
written: list[Path] = []
|
|
133
|
+
normalized = target.lower()
|
|
134
|
+
|
|
135
|
+
if normalized in {"a2a", "a2a-card"}:
|
|
136
|
+
dest = out_dir / f"{slug}.agent-card.json"
|
|
137
|
+
dest.write_text(json.dumps(build_a2a_card(manifest, input_schema, output_schema), indent=2), encoding="utf-8")
|
|
138
|
+
written.append(dest)
|
|
139
|
+
elif normalized in {"skill", "agent-skill"}:
|
|
140
|
+
skill_dir = out_dir / slug
|
|
141
|
+
skill_dir.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
dest = skill_dir / "SKILL.md"
|
|
143
|
+
dest.write_text(build_agent_skill_md(manifest, system_prompt), encoding="utf-8")
|
|
144
|
+
written.append(dest)
|
|
145
|
+
elif normalized == "mcp-server":
|
|
146
|
+
dest = out_dir / f"{slug}_mcp_server.py"
|
|
147
|
+
dest.write_text(build_mcp_wrapper_py(manifest), encoding="utf-8")
|
|
148
|
+
written.append(dest)
|
|
149
|
+
elif normalized == "subagent":
|
|
150
|
+
dest = out_dir / f"{slug}.md"
|
|
151
|
+
dest.write_text(build_subagent_md(manifest, system_prompt), encoding="utf-8")
|
|
152
|
+
written.append(dest)
|
|
153
|
+
toml_dest = out_dir / f"{slug}.toml"
|
|
154
|
+
toml_dest.write_text(build_codex_subagent_toml(manifest, system_prompt), encoding="utf-8")
|
|
155
|
+
written.append(toml_dest)
|
|
156
|
+
elif normalized == "langgraph":
|
|
157
|
+
dest = out_dir / f"{slug}_langgraph.py"
|
|
158
|
+
dest.write_text(build_langgraph_stub_py(manifest), encoding="utf-8")
|
|
159
|
+
written.append(dest)
|
|
160
|
+
else:
|
|
161
|
+
raise ValueError(f"Unknown export target: {target!r}")
|
|
162
|
+
|
|
163
|
+
return written
|