koda-agent-runtime 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.
- koda_agent_runtime/__init__.py +76 -0
- koda_agent_runtime/app.py +150 -0
- koda_agent_runtime/config.py +139 -0
- koda_agent_runtime/context.py +43 -0
- koda_agent_runtime/headers.py +42 -0
- koda_agent_runtime/middleware.py +51 -0
- koda_agent_runtime/registry.py +185 -0
- koda_agent_runtime/tools.py +154 -0
- koda_agent_runtime-0.1.0.dist-info/METADATA +158 -0
- koda_agent_runtime-0.1.0.dist-info/RECORD +12 -0
- koda_agent_runtime-0.1.0.dist-info/WHEEL +4 -0
- koda_agent_runtime-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Runtime común para agentes Koda expuestos por A2A sobre Amazon Bedrock AgentCore.
|
|
2
|
+
|
|
3
|
+
Cinco piezas reutilizables, todas activables a la carta desde el
|
|
4
|
+
``pyproject.toml`` del agente vía ``extras``:
|
|
5
|
+
|
|
6
|
+
* ``headers`` — constantes de custom headers ``Koda-*`` (fuente única).
|
|
7
|
+
* ``context`` — module-level state donde el middleware guarda bearer+request_id.
|
|
8
|
+
* ``middleware`` — factory FastAPI que captura los headers y salta ``/ping``.
|
|
9
|
+
* ``registry`` — helpers HTTP para descubrir agentes/skills, fetch bundle e
|
|
10
|
+
invocar peers vía el registry (el broker firma SigV4).
|
|
11
|
+
* ``config`` — loader/validador de ``agent.yaml``.
|
|
12
|
+
* ``tools`` — decoradores ``@strands.tools.tool`` que envuelven los helpers.
|
|
13
|
+
* ``app`` — ``build_agent_app(cfg)`` que ensambla el ASGI completo (Strands+A2A).
|
|
14
|
+
|
|
15
|
+
Un agente minimalista consume el ``runtime`` extra y llama a las piezas
|
|
16
|
+
individuales; un agente completo consume el ``bootstrap`` extra y su
|
|
17
|
+
``src/agent.py`` baja a ~10 líneas.
|
|
18
|
+
|
|
19
|
+
Ver ``KODA_AGENT_RUNTIME_ARCHITECTURE.md`` en el monorepo koda-platform
|
|
20
|
+
para el diseño completo y el plan de release.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from .config import AgentConfig, load_a2a_skills_from_card, load_agent_config
|
|
24
|
+
from .context import get_bearer, get_request_id, set_context
|
|
25
|
+
from .headers import (
|
|
26
|
+
AGENTCORE_HEADER_PREFIX,
|
|
27
|
+
ALLOWLISTED_HEADERS,
|
|
28
|
+
KODA_AGENT_PATH_HEADER,
|
|
29
|
+
KODA_AUTHZ_HEADER,
|
|
30
|
+
KODA_CALLER_TYPE_HEADER,
|
|
31
|
+
KODA_CHAIN_DEPTH_HEADER,
|
|
32
|
+
KODA_EMAIL_HEADER,
|
|
33
|
+
KODA_REQUEST_ID_HEADER,
|
|
34
|
+
KODA_ROLES_HEADER,
|
|
35
|
+
KODA_SUB_HEADER,
|
|
36
|
+
)
|
|
37
|
+
from .middleware import koda_headers_middleware
|
|
38
|
+
from .registry import (
|
|
39
|
+
RegistryError,
|
|
40
|
+
discover_agents,
|
|
41
|
+
discover_skills,
|
|
42
|
+
fetch_skill_bundle,
|
|
43
|
+
invoke_peer,
|
|
44
|
+
)
|
|
45
|
+
from .tools import build_tools
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"AGENTCORE_HEADER_PREFIX",
|
|
49
|
+
"ALLOWLISTED_HEADERS",
|
|
50
|
+
"AgentConfig",
|
|
51
|
+
"KODA_AGENT_PATH_HEADER",
|
|
52
|
+
"KODA_AUTHZ_HEADER",
|
|
53
|
+
"KODA_CALLER_TYPE_HEADER",
|
|
54
|
+
"KODA_CHAIN_DEPTH_HEADER",
|
|
55
|
+
"KODA_EMAIL_HEADER",
|
|
56
|
+
"KODA_REQUEST_ID_HEADER",
|
|
57
|
+
"KODA_ROLES_HEADER",
|
|
58
|
+
"KODA_SUB_HEADER",
|
|
59
|
+
"RegistryError",
|
|
60
|
+
"build_tools",
|
|
61
|
+
"discover_agents",
|
|
62
|
+
"discover_skills",
|
|
63
|
+
"fetch_skill_bundle",
|
|
64
|
+
"get_bearer",
|
|
65
|
+
"get_request_id",
|
|
66
|
+
"invoke_peer",
|
|
67
|
+
"koda_headers_middleware",
|
|
68
|
+
"load_a2a_skills_from_card",
|
|
69
|
+
"load_agent_config",
|
|
70
|
+
"set_context",
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
# `build_agent_app` NO se exporta desde el top-level porque su import
|
|
74
|
+
# desencadena `strands` + `bedrock` (dependencias pesadas del extra
|
|
75
|
+
# `bootstrap`, no del core). Los consumidores lo importan explícito:
|
|
76
|
+
# from koda_agent_runtime.app import build_agent_app
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Bootstrap: construye una app FastAPI + Strands A2A a partir de ``AgentConfig``.
|
|
2
|
+
|
|
3
|
+
Reduce el `src/agent.py` típico de un agente Koda a ~10 líneas. Ver
|
|
4
|
+
``AGENT_SPEC.md`` en koda-platform y §4.3 de
|
|
5
|
+
``KODA_AGENT_RUNTIME_ARCHITECTURE.md`` para la motivación.
|
|
6
|
+
|
|
7
|
+
Ejemplo:
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from koda_agent_runtime.config import load_agent_config
|
|
11
|
+
from koda_agent_runtime.app import build_agent_app
|
|
12
|
+
|
|
13
|
+
_BASE = Path(__file__).resolve().parent.parent
|
|
14
|
+
app = build_agent_app(load_agent_config(_BASE / "agent.yaml"), base_dir=_BASE)
|
|
15
|
+
|
|
16
|
+
Agentes que quieran inyectar tools locales pueden pasarlas con
|
|
17
|
+
``extra_tools=[...]``; agentes con requerimientos más raros pueden
|
|
18
|
+
saltarse este helper y usar directo ``koda_agent_runtime.middleware`` y
|
|
19
|
+
``koda_agent_runtime.tools``.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import logging
|
|
25
|
+
import os
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from fastapi import FastAPI
|
|
30
|
+
|
|
31
|
+
from .config import AgentConfig, load_a2a_skills_from_card
|
|
32
|
+
from .middleware import koda_headers_middleware
|
|
33
|
+
from .tools import build_tools
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def build_agent_app(
|
|
39
|
+
cfg: AgentConfig,
|
|
40
|
+
*,
|
|
41
|
+
base_dir: Path,
|
|
42
|
+
extra_tools: list[Any] | None = None,
|
|
43
|
+
) -> FastAPI:
|
|
44
|
+
"""Ensambla un ASGI app completo para un agente Koda.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
cfg: Config parseada del ``agent.yaml``.
|
|
48
|
+
base_dir: Directorio raíz del agente (donde viven ``prompts/`` y
|
|
49
|
+
``a2a/``). Normalmente ``Path(__file__).resolve().parent.parent``
|
|
50
|
+
desde ``src/agent.py``.
|
|
51
|
+
extra_tools: Herramientas locales del agente que no están en el
|
|
52
|
+
catálogo compartido. Se anexan a las declaradas en
|
|
53
|
+
``agent.yaml.tools``.
|
|
54
|
+
"""
|
|
55
|
+
# Imports lazy: Strands/Bedrock son pesados y no todos los consumidores
|
|
56
|
+
# del paquete necesitan el bootstrap (algunos usan solo runtime/config).
|
|
57
|
+
from strands import Agent
|
|
58
|
+
from strands.models import BedrockModel
|
|
59
|
+
from strands.multiagent.a2a import A2AServer
|
|
60
|
+
|
|
61
|
+
prompt_path = base_dir / "prompts" / "system.md"
|
|
62
|
+
card_path = base_dir / "a2a" / "agent-card.json"
|
|
63
|
+
for p in (prompt_path, card_path):
|
|
64
|
+
if not p.exists():
|
|
65
|
+
raise FileNotFoundError(f"agent bootstrap missing required file: {p}")
|
|
66
|
+
|
|
67
|
+
prompt = prompt_path.read_text(encoding="utf-8")
|
|
68
|
+
|
|
69
|
+
# Origen de las skills (flag KODA_SKILLS_SOURCE, ver load_skills_for_agent):
|
|
70
|
+
# - "offline" (default, dev): lee skills/<name>/SKILL.md del disco y las
|
|
71
|
+
# inyecta al system prompt en arranque. No depende del registry.
|
|
72
|
+
# - "registry": NO inyecta en arranque; el agente resuelve skills en runtime
|
|
73
|
+
# con la tool `fetch_registry_skill` (necesita el JWT por-request).
|
|
74
|
+
skills_text = load_skills_for_agent(base_dir)
|
|
75
|
+
if skills_text:
|
|
76
|
+
prompt = f"{prompt}\n\n{skills_text}"
|
|
77
|
+
logger.info("skills offline cargadas en el prompt (%d chars)", len(skills_text))
|
|
78
|
+
|
|
79
|
+
tools = build_tools(cfg) + list(extra_tools or [])
|
|
80
|
+
|
|
81
|
+
agent = Agent(
|
|
82
|
+
model=BedrockModel(**cfg.model_kwargs()),
|
|
83
|
+
system_prompt=prompt,
|
|
84
|
+
tools=tools,
|
|
85
|
+
name=cfg.name,
|
|
86
|
+
description=cfg.description,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
a2a_server = A2AServer(
|
|
90
|
+
agent=agent,
|
|
91
|
+
http_url=cfg.runtime_url(),
|
|
92
|
+
serve_at_root=True,
|
|
93
|
+
version=cfg.version,
|
|
94
|
+
skills=load_a2a_skills_from_card(card_path),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
app = FastAPI()
|
|
98
|
+
koda_headers_middleware(app)
|
|
99
|
+
app.mount("/", a2a_server.to_fastapi_app())
|
|
100
|
+
|
|
101
|
+
logger.info(
|
|
102
|
+
"agent app built: name=%s version=%s tools=%d peers=%d",
|
|
103
|
+
cfg.name,
|
|
104
|
+
cfg.version,
|
|
105
|
+
len(tools),
|
|
106
|
+
len(cfg.peers),
|
|
107
|
+
)
|
|
108
|
+
return app
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def load_skills_for_agent(base_dir: Path) -> str:
|
|
112
|
+
"""Resuelve las skills del agente según el flag ``KODA_SKILLS_SOURCE``.
|
|
113
|
+
|
|
114
|
+
- ``offline`` (default): lee ``skills/<name>/SKILL.md`` del disco y devuelve
|
|
115
|
+
un bloque para anexar al system prompt. Ideal para desarrollo — sin
|
|
116
|
+
registry, sin bearer.
|
|
117
|
+
- ``registry``: devuelve cadena vacía; en este modo las skills se resuelven
|
|
118
|
+
en runtime con la tool ``fetch_registry_skill`` (que necesita el JWT del
|
|
119
|
+
caller por-request). No se inyectan en el arranque.
|
|
120
|
+
|
|
121
|
+
Nombres de skill: ``koda-skill-<fase>-<target>``.
|
|
122
|
+
"""
|
|
123
|
+
source = os.environ.get("KODA_SKILLS_SOURCE", "offline").strip().lower()
|
|
124
|
+
if source == "registry":
|
|
125
|
+
logger.info("KODA_SKILLS_SOURCE=registry: skills vía fetch_registry_skill en runtime")
|
|
126
|
+
return ""
|
|
127
|
+
if source != "offline":
|
|
128
|
+
logger.warning("KODA_SKILLS_SOURCE=%r no reconocido; usando 'offline'", source)
|
|
129
|
+
|
|
130
|
+
skills_dir = base_dir / "skills"
|
|
131
|
+
if not skills_dir.is_dir():
|
|
132
|
+
return ""
|
|
133
|
+
parts: list[str] = []
|
|
134
|
+
for skill_md in sorted(skills_dir.glob("*/SKILL.md")):
|
|
135
|
+
try:
|
|
136
|
+
content = skill_md.read_text(encoding="utf-8").strip()
|
|
137
|
+
except OSError as exc:
|
|
138
|
+
logger.warning("no pude leer skill %s: %s", skill_md, exc)
|
|
139
|
+
continue
|
|
140
|
+
if content:
|
|
141
|
+
parts.append(content)
|
|
142
|
+
if not parts:
|
|
143
|
+
return ""
|
|
144
|
+
joined = "\n\n---\n\n".join(parts)
|
|
145
|
+
return (
|
|
146
|
+
"# Skill(s) aplicables (cargadas localmente, modo offline)\n\n"
|
|
147
|
+
"Sigue estas guías al pie de la letra para tu fase. No necesitas "
|
|
148
|
+
"buscar skills en el registry: ya están aquí.\n\n"
|
|
149
|
+
f"{joined}"
|
|
150
|
+
)
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Carga y valida ``agent.yaml`` — la declaración de identidad y capacidades del agente.
|
|
2
|
+
|
|
3
|
+
`agent.yaml` es la fuente de verdad para: nombre, versión, modelo Bedrock,
|
|
4
|
+
tools a activar, peers permitidos, URL del registry, y datos de deploy.
|
|
5
|
+
Ver ``AGENT_SPEC.md`` en la raíz del monorepo para el shape completo.
|
|
6
|
+
|
|
7
|
+
El schema se valida "a mano" con checks simples en vez de depender de
|
|
8
|
+
pydantic — mantenerlo sin dependencias extra facilita reusarlo en scripts
|
|
9
|
+
de deploy fuera del container.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import yaml
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Peer:
|
|
24
|
+
path: str
|
|
25
|
+
role: str
|
|
26
|
+
description: str = ""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class ModelConfig:
|
|
31
|
+
provider: str = "bedrock"
|
|
32
|
+
model_id: str = "us.amazon.nova-lite-v1:0"
|
|
33
|
+
temperature: float = 0.4
|
|
34
|
+
max_tokens: int = 4000
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class AgentConfig:
|
|
39
|
+
name: str
|
|
40
|
+
version: str
|
|
41
|
+
description: str
|
|
42
|
+
model: ModelConfig
|
|
43
|
+
tools: list[str] = field(default_factory=list)
|
|
44
|
+
peers: list[Peer] = field(default_factory=list)
|
|
45
|
+
registry_url: str = ""
|
|
46
|
+
deploy_region: str = ""
|
|
47
|
+
deploy_account: str | None = None
|
|
48
|
+
runtime_name: str = ""
|
|
49
|
+
|
|
50
|
+
def model_kwargs(self) -> dict[str, Any]:
|
|
51
|
+
"""Args para pasar a ``strands.models.BedrockModel(**...)``."""
|
|
52
|
+
return {
|
|
53
|
+
"model_id": self.model.model_id,
|
|
54
|
+
"temperature": self.model.temperature,
|
|
55
|
+
"max_tokens": self.model.max_tokens,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
def runtime_url(self) -> str:
|
|
59
|
+
"""URL A2A local — AgentCore le pasa este valor al AgentCard cuando corre."""
|
|
60
|
+
# AgentCore inyecta AGENTCORE_RUNTIME_URL en producción; el default cubre
|
|
61
|
+
# el uvicorn local para pruebas.
|
|
62
|
+
return os.environ.get("AGENTCORE_RUNTIME_URL", "http://127.0.0.1:9000/")
|
|
63
|
+
|
|
64
|
+
def a2a_skills(self) -> list[Any]:
|
|
65
|
+
"""AgentSkill A2A objects construidos desde ``a2a/agent-card.json``.
|
|
66
|
+
|
|
67
|
+
`agent.yaml` intencionalmente no duplica lo que ya está en el
|
|
68
|
+
AgentCard (los skills declarados al registry). Los agentes que
|
|
69
|
+
quieran exponer skills A2A a nivel del runtime pueden leerlos
|
|
70
|
+
desde ``a2a/agent-card.json`` (ver ``load_a2a_skills_from_card``
|
|
71
|
+
más abajo). Devolvemos lista vacía por defecto para agentes sin
|
|
72
|
+
skills A2A declaradas.
|
|
73
|
+
"""
|
|
74
|
+
return []
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def load_agent_config(yaml_path: Path) -> AgentConfig:
|
|
78
|
+
"""Lee ``agent.yaml`` y devuelve un ``AgentConfig`` validado."""
|
|
79
|
+
if not yaml_path.exists():
|
|
80
|
+
raise FileNotFoundError(f"agent.yaml not found at {yaml_path}")
|
|
81
|
+
data = yaml.safe_load(yaml_path.read_text(encoding="utf-8")) or {}
|
|
82
|
+
|
|
83
|
+
for k in ("name", "version", "description"):
|
|
84
|
+
if not data.get(k):
|
|
85
|
+
raise ValueError(f"agent.yaml missing required field: {k!r}")
|
|
86
|
+
|
|
87
|
+
model_data = data.get("model") or {}
|
|
88
|
+
model = ModelConfig(
|
|
89
|
+
provider=model_data.get("provider", "bedrock"),
|
|
90
|
+
model_id=model_data.get("model_id", ModelConfig.model_id),
|
|
91
|
+
temperature=float(model_data.get("temperature", ModelConfig.temperature)),
|
|
92
|
+
max_tokens=int(model_data.get("max_tokens", ModelConfig.max_tokens)),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
peers = [
|
|
96
|
+
Peer(path=p["path"], role=p.get("role", ""), description=p.get("description", ""))
|
|
97
|
+
for p in (data.get("peers") or [])
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
reg = data.get("registry") or {}
|
|
101
|
+
dep = data.get("deploy") or {}
|
|
102
|
+
# Config de entorno: env var tiene precedencia sobre el yaml (que queda solo
|
|
103
|
+
# por retrocompat). Nada quemado en el código — sin env ni yaml, queda vacío.
|
|
104
|
+
registry_url = os.environ.get("KODA_REGISTRY_URL") or reg.get("url", "")
|
|
105
|
+
deploy_region = (
|
|
106
|
+
os.environ.get("KODA_TARGET_DEPLOY_REGION")
|
|
107
|
+
or os.environ.get("AWS_REGION")
|
|
108
|
+
or dep.get("region", "")
|
|
109
|
+
)
|
|
110
|
+
return AgentConfig(
|
|
111
|
+
name=data["name"],
|
|
112
|
+
version=str(data["version"]),
|
|
113
|
+
description=data["description"].strip(),
|
|
114
|
+
model=model,
|
|
115
|
+
tools=list(data.get("tools") or []),
|
|
116
|
+
peers=peers,
|
|
117
|
+
registry_url=registry_url,
|
|
118
|
+
deploy_region=deploy_region,
|
|
119
|
+
deploy_account=os.environ.get("KODA_AWS_ACCOUNT") or dep.get("account"),
|
|
120
|
+
runtime_name=dep.get("runtime_name", data["name"].replace("-", "_")),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def load_a2a_skills_from_card(card_path: Path) -> list[Any]:
|
|
125
|
+
"""Deriva ``AgentSkill`` A2A objects desde ``a2a/agent-card.json``."""
|
|
126
|
+
import json
|
|
127
|
+
|
|
128
|
+
from a2a.types import AgentSkill
|
|
129
|
+
|
|
130
|
+
card = json.loads(card_path.read_text(encoding="utf-8"))
|
|
131
|
+
return [
|
|
132
|
+
AgentSkill(
|
|
133
|
+
id=s["id"],
|
|
134
|
+
name=s["name"],
|
|
135
|
+
description=s["description"],
|
|
136
|
+
tags=s.get("tags", []),
|
|
137
|
+
)
|
|
138
|
+
for s in card.get("skills", [])
|
|
139
|
+
]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Module-level state que preserva la identidad Koda entre middleware y tools.
|
|
2
|
+
|
|
3
|
+
**Por qué no ContextVar:** Strands ejecuta callbacks de tools en un thread
|
|
4
|
+
pool distinto al que atendió la request HTTP. `contextvars.ContextVar`
|
|
5
|
+
NO se propaga entre threads; el bearer aparece vacío cuando la tool corre.
|
|
6
|
+
Un dict de módulo (mutación protegida por el GIL) es la solución más
|
|
7
|
+
simple que sí cruza threads.
|
|
8
|
+
|
|
9
|
+
**Por qué no es un problema de concurrencia:** AgentCore levanta UN
|
|
10
|
+
proceso por container y multiplexa requests con FastAPI/asyncio. Un
|
|
11
|
+
único cliente activo por request cabe en el modelo actual (payloads
|
|
12
|
+
JSON-RPC serializados por Strands). Si en el futuro se sirven varias
|
|
13
|
+
sesiones concurrentes en el mismo container habrá que mover a
|
|
14
|
+
``threading.local`` o pasar el bearer explícito por argumento — pero
|
|
15
|
+
para el patrón "AgentCore invoca → agente responde → sale" del broker
|
|
16
|
+
async esto es suficiente y mantiene el código legible.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import logging
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
_state: dict[str, str] = {"bearer": "", "request_id": ""}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def set_context(bearer: str, request_id: str = "") -> None:
|
|
29
|
+
_state["bearer"] = bearer or ""
|
|
30
|
+
_state["request_id"] = request_id or ""
|
|
31
|
+
logger.info(
|
|
32
|
+
"koda context set: bearer_len=%d request_id=%s",
|
|
33
|
+
len(_state["bearer"]),
|
|
34
|
+
_state["request_id"] or "<none>",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get_bearer() -> str:
|
|
39
|
+
return _state.get("bearer", "")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get_request_id() -> str:
|
|
43
|
+
return _state.get("request_id", "")
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Custom headers Koda-* inyectados por koda-proxy al invocar un runtime.
|
|
2
|
+
|
|
3
|
+
AgentCore Runtime SOLO forwardea request headers cuyo nombre empieza con
|
|
4
|
+
``X-Amzn-Bedrock-AgentCore-Runtime-Custom-``. koda-proxy inyecta ocho headers
|
|
5
|
+
bajo ese prefijo con la información de identidad del usuario original, el
|
|
6
|
+
service-token vigente (Okta o self-signed 8h) y datos de trace/loop-detect.
|
|
7
|
+
|
|
8
|
+
Las constantes viven aquí para que exista **una sola fuente de verdad** entre
|
|
9
|
+
el paquete común y cualquier agente que quiera leerlas directamente. En la
|
|
10
|
+
mayoría de los casos, el middleware de este paquete y el `_state` dict del
|
|
11
|
+
módulo ``context`` cubren todo el uso; los agentes rara vez importan estas
|
|
12
|
+
constantes de forma directa.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
# AgentCore prefix, ya en lowercase — todos los headers entrantes se
|
|
18
|
+
# normalizan a lowercase en el middleware antes de compararse.
|
|
19
|
+
AGENTCORE_HEADER_PREFIX = "x-amzn-bedrock-agentcore-runtime-custom-"
|
|
20
|
+
|
|
21
|
+
KODA_AUTHZ_HEADER = AGENTCORE_HEADER_PREFIX + "koda-authorization"
|
|
22
|
+
KODA_REQUEST_ID_HEADER = AGENTCORE_HEADER_PREFIX + "koda-request-id"
|
|
23
|
+
KODA_SUB_HEADER = AGENTCORE_HEADER_PREFIX + "koda-sub"
|
|
24
|
+
KODA_EMAIL_HEADER = AGENTCORE_HEADER_PREFIX + "koda-email"
|
|
25
|
+
KODA_ROLES_HEADER = AGENTCORE_HEADER_PREFIX + "koda-roles"
|
|
26
|
+
KODA_CHAIN_DEPTH_HEADER = AGENTCORE_HEADER_PREFIX + "koda-chain-depth"
|
|
27
|
+
KODA_AGENT_PATH_HEADER = AGENTCORE_HEADER_PREFIX + "koda-agent-path"
|
|
28
|
+
KODA_CALLER_TYPE_HEADER = AGENTCORE_HEADER_PREFIX + "koda-caller-type"
|
|
29
|
+
|
|
30
|
+
# Lista literal que se copia en el `request_header_configuration` del CDK
|
|
31
|
+
# stack del agente (o en `agentcore configure --allowlisted-headers-file`).
|
|
32
|
+
# Un allowlist incompleto = identidad vacía en el agente destino.
|
|
33
|
+
ALLOWLISTED_HEADERS: tuple[str, ...] = (
|
|
34
|
+
"X-Amzn-Bedrock-AgentCore-Runtime-Custom-Koda-Authorization",
|
|
35
|
+
"X-Amzn-Bedrock-AgentCore-Runtime-Custom-Koda-Sub",
|
|
36
|
+
"X-Amzn-Bedrock-AgentCore-Runtime-Custom-Koda-Email",
|
|
37
|
+
"X-Amzn-Bedrock-AgentCore-Runtime-Custom-Koda-Roles",
|
|
38
|
+
"X-Amzn-Bedrock-AgentCore-Runtime-Custom-Koda-Chain-Depth",
|
|
39
|
+
"X-Amzn-Bedrock-AgentCore-Runtime-Custom-Koda-Request-Id",
|
|
40
|
+
"X-Amzn-Bedrock-AgentCore-Runtime-Custom-Koda-Agent-Path",
|
|
41
|
+
"X-Amzn-Bedrock-AgentCore-Runtime-Custom-Koda-Caller-Type",
|
|
42
|
+
)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Middleware FastAPI que captura los headers Koda-* en el state del módulo.
|
|
2
|
+
|
|
3
|
+
Uso desde `src/agent.py`:
|
|
4
|
+
|
|
5
|
+
from fastapi import FastAPI
|
|
6
|
+
from koda_agent_runtime.middleware import koda_headers_middleware
|
|
7
|
+
|
|
8
|
+
app = FastAPI()
|
|
9
|
+
koda_headers_middleware(app)
|
|
10
|
+
app.mount("/", a2a_server.to_fastapi_app())
|
|
11
|
+
|
|
12
|
+
**Regla crítica — no sobreescribir con vacío.** AgentCore golpea ``/ping``
|
|
13
|
+
cada ~2s para health checks; esos requests no traen ``Koda-Authorization``.
|
|
14
|
+
Si el middleware llamara ``set_context("", "")`` en cada request, borraría
|
|
15
|
+
el bearer que otra invocación tenía guardado (los tools de Strands corren
|
|
16
|
+
async, DESPUÉS de que el middleware retorna, así que un ping intermedio
|
|
17
|
+
resetea el state que la tool iba a usar). Solución: sólo llamar
|
|
18
|
+
``set_context()`` cuando hay bearer en la request.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import logging
|
|
24
|
+
|
|
25
|
+
from fastapi import FastAPI, Request
|
|
26
|
+
|
|
27
|
+
from .context import set_context
|
|
28
|
+
from .headers import KODA_AUTHZ_HEADER, KODA_REQUEST_ID_HEADER
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger(__name__)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def koda_headers_middleware(app: FastAPI) -> None:
|
|
34
|
+
"""Registra el middleware que captura headers Koda-* del custom prefix AgentCore.
|
|
35
|
+
|
|
36
|
+
Registrar SOLO una vez por app. No es idempotente entre llamadas.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
@app.middleware("http")
|
|
40
|
+
async def _capture(request: Request, call_next):
|
|
41
|
+
headers = {k.lower(): v for k, v in request.headers.items()}
|
|
42
|
+
bearer = headers.get(KODA_AUTHZ_HEADER, "")
|
|
43
|
+
rid = headers.get(KODA_REQUEST_ID_HEADER, "")
|
|
44
|
+
if bearer:
|
|
45
|
+
logger.info(
|
|
46
|
+
"middleware saw request: path=%s koda-authz-present=True request-id=%s",
|
|
47
|
+
request.url.path,
|
|
48
|
+
rid or "<none>",
|
|
49
|
+
)
|
|
50
|
+
set_context(bearer=bearer, request_id=rid)
|
|
51
|
+
return await call_next(request)
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Cliente HTTP hacia el mcp-gateway-registry.
|
|
2
|
+
|
|
3
|
+
Cuatro funciones que el agente típico consume:
|
|
4
|
+
|
|
5
|
+
* ``discover_agents(query)`` — búsqueda semántica de peers registrados.
|
|
6
|
+
* ``discover_skills(query)`` — búsqueda semántica de skills registradas.
|
|
7
|
+
* ``fetch_skill_bundle(skill_path)`` — descarga el markdown de una skill.
|
|
8
|
+
* ``invoke_peer(agent_path, message)`` — delega a un agente peer vía el
|
|
9
|
+
registry (que firma SigV4 y aplica identity headers).
|
|
10
|
+
|
|
11
|
+
Todos leen el bearer del module state (`context._state`), que el
|
|
12
|
+
middleware guardó al recibir la request de AgentCore. Ninguno recibe el
|
|
13
|
+
bearer por argumento — evita que el prompt del modelo tenga que
|
|
14
|
+
razonar sobre tokens.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
import os
|
|
22
|
+
import urllib.error
|
|
23
|
+
import urllib.request
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from .context import get_bearer, get_request_id
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
# Sin default quemado: la URL del registry viene por env (KODA_REGISTRY_URL).
|
|
31
|
+
# Si no está seteada, las llamadas al registry fallan con un error claro en vez
|
|
32
|
+
# de apuntar silenciosamente a una URL hardcodeada.
|
|
33
|
+
_REGISTRY_URL = os.environ.get("KODA_REGISTRY_URL", "")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class RegistryError(Exception):
|
|
37
|
+
"""Cualquier fallo hablando con el registry."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _bearer_headers() -> dict[str, str]:
|
|
41
|
+
bearer = get_bearer()
|
|
42
|
+
if not bearer:
|
|
43
|
+
raise RegistryError("no bearer in context — agent was invoked without Koda-Authorization")
|
|
44
|
+
h = {"Authorization": f"Bearer {bearer}"}
|
|
45
|
+
rid = get_request_id()
|
|
46
|
+
if rid:
|
|
47
|
+
h["X-Koda-Request-Id"] = rid
|
|
48
|
+
return h
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def discover_agents(query: str, max_results: int = 5) -> list[dict[str, Any]]:
|
|
52
|
+
"""Búsqueda semántica de peers A2A. Devuelve lista de dicts con name/path/url/score."""
|
|
53
|
+
headers = _bearer_headers()
|
|
54
|
+
headers["Content-Type"] = "application/json"
|
|
55
|
+
body = json.dumps({"query": query, "max_results": max_results}).encode("utf-8")
|
|
56
|
+
url = (
|
|
57
|
+
f"{_REGISTRY_URL.rstrip('/')}/api/agents/discover/semantic"
|
|
58
|
+
f"?query={urllib.request.quote(query)}&max_results={max_results}"
|
|
59
|
+
)
|
|
60
|
+
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
61
|
+
try:
|
|
62
|
+
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
63
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
64
|
+
except urllib.error.HTTPError as exc:
|
|
65
|
+
body_txt = exc.read().decode("utf-8", errors="replace")[:200]
|
|
66
|
+
logger.warning("discover_agents failed: %s %s", exc.code, body_txt)
|
|
67
|
+
return []
|
|
68
|
+
except Exception as exc:
|
|
69
|
+
logger.warning("discover_agents unreachable: %s", exc)
|
|
70
|
+
return []
|
|
71
|
+
return data.get("agents", []) if isinstance(data, dict) else []
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def discover_skills(query: str, max_results: int = 5) -> list[dict[str, Any]]:
|
|
75
|
+
"""Búsqueda semántica de skills.
|
|
76
|
+
|
|
77
|
+
Preferido sobre adivinar nombres. La clave ``path`` que devuelve es
|
|
78
|
+
el mismo string que ``fetch_skill_bundle`` acepta (con o sin
|
|
79
|
+
``/skills/`` prefix).
|
|
80
|
+
"""
|
|
81
|
+
headers = _bearer_headers()
|
|
82
|
+
headers["Content-Type"] = "application/json"
|
|
83
|
+
body = json.dumps(
|
|
84
|
+
{"query": query, "entity_types": ["skill"], "max_results": max_results}
|
|
85
|
+
).encode("utf-8")
|
|
86
|
+
url = f"{_REGISTRY_URL.rstrip('/')}/api/search/semantic"
|
|
87
|
+
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
88
|
+
try:
|
|
89
|
+
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
90
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
91
|
+
except urllib.error.HTTPError as exc:
|
|
92
|
+
body_txt = exc.read().decode("utf-8", errors="replace")[:200]
|
|
93
|
+
logger.warning("discover_skills failed: %s %s", exc.code, body_txt)
|
|
94
|
+
return []
|
|
95
|
+
except Exception as exc:
|
|
96
|
+
logger.warning("discover_skills unreachable: %s", exc)
|
|
97
|
+
return []
|
|
98
|
+
return data.get("skills", []) if isinstance(data, dict) else []
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def fetch_skill_bundle(skill_path: str) -> dict[str, Any]:
|
|
102
|
+
"""GET /api/skills/<name>/bundle.
|
|
103
|
+
|
|
104
|
+
Acepta tanto ``playbook-x`` como ``/skills/playbook-x`` — el prefix
|
|
105
|
+
se normaliza aquí porque el endpoint del registry sólo entiende el
|
|
106
|
+
nombre bare.
|
|
107
|
+
"""
|
|
108
|
+
normalized = skill_path.lstrip("/")
|
|
109
|
+
if normalized.startswith("skills/"):
|
|
110
|
+
normalized = normalized[len("skills/") :]
|
|
111
|
+
url = f"{_REGISTRY_URL.rstrip('/')}/api/skills/{normalized}/bundle"
|
|
112
|
+
req = urllib.request.Request(url, headers=_bearer_headers(), method="GET")
|
|
113
|
+
try:
|
|
114
|
+
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
115
|
+
payload = json.loads(resp.read().decode("utf-8"))
|
|
116
|
+
except urllib.error.HTTPError as exc:
|
|
117
|
+
body = exc.read().decode("utf-8", errors="replace")[:200]
|
|
118
|
+
logger.warning(
|
|
119
|
+
"skill bundle fetch failed: skill=%s status=%s body=%s",
|
|
120
|
+
skill_path,
|
|
121
|
+
exc.code,
|
|
122
|
+
body,
|
|
123
|
+
)
|
|
124
|
+
raise RegistryError(f"registry returned {exc.code}: {body}") from exc
|
|
125
|
+
except Exception as exc:
|
|
126
|
+
raise RegistryError(f"registry unreachable: {exc}") from exc
|
|
127
|
+
return payload
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def invoke_peer(agent_path: str, message: str) -> str:
|
|
131
|
+
"""POST /agents/<path>/invoke — delega a un peer A2A vía el registry.
|
|
132
|
+
|
|
133
|
+
El registry firma SigV4 hacia AgentCore, mint (o reuse) el
|
|
134
|
+
service-token y forwardea la identidad. El agente destino recibe
|
|
135
|
+
los mismos ``Koda-Sub/Email/Roles`` que llegaron a este agente,
|
|
136
|
+
con ``Koda-Chain-Depth`` incrementado.
|
|
137
|
+
"""
|
|
138
|
+
bearer = get_bearer()
|
|
139
|
+
if not bearer:
|
|
140
|
+
raise RegistryError("no bearer in context — agent was invoked without a caller JWT")
|
|
141
|
+
if not agent_path.startswith("/"):
|
|
142
|
+
agent_path = "/" + agent_path
|
|
143
|
+
|
|
144
|
+
rid = get_request_id()
|
|
145
|
+
envelope = {
|
|
146
|
+
"jsonrpc": "2.0",
|
|
147
|
+
"id": "1",
|
|
148
|
+
"method": "message/send",
|
|
149
|
+
"params": {
|
|
150
|
+
"message": {
|
|
151
|
+
"role": "user",
|
|
152
|
+
"kind": "message",
|
|
153
|
+
"messageId": rid or "m1",
|
|
154
|
+
"parts": [{"kind": "text", "text": message}],
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
}
|
|
158
|
+
body = json.dumps(envelope).encode("utf-8")
|
|
159
|
+
url = f"{_REGISTRY_URL.rstrip('/')}/agents{agent_path}/invoke"
|
|
160
|
+
headers = {
|
|
161
|
+
"Authorization": f"Bearer {bearer}",
|
|
162
|
+
"Content-Type": "application/json",
|
|
163
|
+
}
|
|
164
|
+
if rid:
|
|
165
|
+
headers["X-Koda-Request-Id"] = rid
|
|
166
|
+
|
|
167
|
+
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
168
|
+
try:
|
|
169
|
+
with urllib.request.urlopen(req, timeout=120) as resp:
|
|
170
|
+
payload = json.loads(resp.read().decode("utf-8"))
|
|
171
|
+
except urllib.error.HTTPError as exc:
|
|
172
|
+
detail = exc.read().decode("utf-8", errors="replace")[:200]
|
|
173
|
+
raise RegistryError(f"registry returned {exc.code}: {detail}") from exc
|
|
174
|
+
except Exception as exc:
|
|
175
|
+
raise RegistryError(f"registry unreachable: {exc}") from exc
|
|
176
|
+
|
|
177
|
+
result = payload.get("result") or {}
|
|
178
|
+
artifacts = result.get("artifacts") or []
|
|
179
|
+
text_parts = [
|
|
180
|
+
p.get("text", "")
|
|
181
|
+
for art in artifacts
|
|
182
|
+
for p in (art.get("parts") or [])
|
|
183
|
+
if p.get("kind") == "text"
|
|
184
|
+
]
|
|
185
|
+
return "\n".join(text_parts).strip() or json.dumps(payload)
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Adaptadores ``@strands.tools.tool`` sobre los helpers de ``registry.py``.
|
|
2
|
+
|
|
3
|
+
Cada helper HTTP se expone al modelo como una tool con docstring en
|
|
4
|
+
español (Strands las usa como descripción). ``build_tools(cfg)`` devuelve
|
|
5
|
+
la lista de tools que el agente eligió en ``agent.yaml.tools``.
|
|
6
|
+
|
|
7
|
+
Esto centraliza los prompts de tools — todos los agentes ven la misma
|
|
8
|
+
descripción de ``fetch_registry_skill``, ``invoke_agent``, etc., en vez
|
|
9
|
+
de que cada uno duplique la suya.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from typing import TYPE_CHECKING, Any
|
|
18
|
+
|
|
19
|
+
from strands.tools import tool
|
|
20
|
+
|
|
21
|
+
from .registry import (
|
|
22
|
+
RegistryError,
|
|
23
|
+
fetch_skill_bundle,
|
|
24
|
+
invoke_peer,
|
|
25
|
+
)
|
|
26
|
+
from .registry import (
|
|
27
|
+
discover_agents as _discover_agents,
|
|
28
|
+
)
|
|
29
|
+
from .registry import (
|
|
30
|
+
discover_skills as _discover_skills,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
from .config import AgentConfig
|
|
35
|
+
|
|
36
|
+
logger = logging.getLogger(__name__)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@tool
|
|
40
|
+
def discover_agents(query: str) -> str:
|
|
41
|
+
"""Descubre agentes registrados en el registry por descripción semántica.
|
|
42
|
+
|
|
43
|
+
Úsalo cuando necesites encontrar un peer al que delegar y no sepas su
|
|
44
|
+
``path`` exacto. Devuelve JSON con lista de candidatos ordenados por
|
|
45
|
+
relevancia (``name``, ``path``, ``description``, ``relevance_score``).
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
query: Lenguaje natural describiendo la capacidad buscada.
|
|
49
|
+
"""
|
|
50
|
+
try:
|
|
51
|
+
agents = _discover_agents(query, max_results=5)
|
|
52
|
+
except Exception as exc: # noqa: BLE001
|
|
53
|
+
logger.warning("discover_agents error: %s", exc)
|
|
54
|
+
return "(no fue posible consultar el registro de agentes)"
|
|
55
|
+
|
|
56
|
+
if not agents:
|
|
57
|
+
return "(sin candidatos en el registro)"
|
|
58
|
+
|
|
59
|
+
summary = [
|
|
60
|
+
{
|
|
61
|
+
"name": a.get("name"),
|
|
62
|
+
"path": a.get("path"),
|
|
63
|
+
"url": a.get("url"),
|
|
64
|
+
"description": (a.get("description") or "")[:200],
|
|
65
|
+
"relevance_score": a.get("relevance_score"),
|
|
66
|
+
}
|
|
67
|
+
for a in agents
|
|
68
|
+
]
|
|
69
|
+
return json.dumps(summary, ensure_ascii=False)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@tool
|
|
73
|
+
def discover_skills(query: str) -> str:
|
|
74
|
+
"""Busca skills (playbooks) por descripción semántica en el registry.
|
|
75
|
+
|
|
76
|
+
Úsalo ANTES de ``fetch_registry_skill`` para encontrar el ``path``
|
|
77
|
+
correcto — no adivines nombres.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
query: Lenguaje natural — qué playbook o guía necesitas.
|
|
81
|
+
"""
|
|
82
|
+
try:
|
|
83
|
+
skills = _discover_skills(query, max_results=5)
|
|
84
|
+
except Exception as exc: # noqa: BLE001
|
|
85
|
+
logger.warning("discover_skills error: %s", exc)
|
|
86
|
+
return "(no fue posible consultar el registro de skills)"
|
|
87
|
+
|
|
88
|
+
if not skills:
|
|
89
|
+
return "(sin candidatos en el registro)"
|
|
90
|
+
|
|
91
|
+
summary = [
|
|
92
|
+
{
|
|
93
|
+
"name": s.get("name"),
|
|
94
|
+
"path": s.get("path"),
|
|
95
|
+
"description": (s.get("description") or "")[:200],
|
|
96
|
+
"relevance_score": s.get("relevance_score"),
|
|
97
|
+
}
|
|
98
|
+
for s in skills
|
|
99
|
+
]
|
|
100
|
+
return json.dumps(summary, ensure_ascii=False)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@tool
|
|
104
|
+
def fetch_registry_skill(skill_path: str) -> str:
|
|
105
|
+
"""Descarga el markdown completo de una skill (playbook) del registry.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
skill_path: ``path`` de la skill tal como lo devolvió
|
|
109
|
+
``discover_skills`` (con o sin prefix ``/skills/``).
|
|
110
|
+
"""
|
|
111
|
+
try:
|
|
112
|
+
bundle = fetch_skill_bundle(skill_path)
|
|
113
|
+
return bundle.get("content") or "(skill encontrada pero sin contenido)"
|
|
114
|
+
except RegistryError as exc:
|
|
115
|
+
logger.warning("fetch_registry_skill failed: %s", exc)
|
|
116
|
+
return f"(skill no disponible: {exc})"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@tool
|
|
120
|
+
def invoke_agent(agent_path: str, message: str) -> str:
|
|
121
|
+
"""Delega la ejecución a un agente peer registrado vía el registry.
|
|
122
|
+
|
|
123
|
+
El registry firma SigV4 hacia el runtime del peer y forwardea la
|
|
124
|
+
identidad del usuario original. Úsalo después de ``discover_agents``
|
|
125
|
+
o cuando tu ``agent.yaml`` ya defina el path del peer.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
agent_path: Path del peer en el registry (e.g. ``/agent-developer``).
|
|
129
|
+
message: Texto a enviar al peer.
|
|
130
|
+
"""
|
|
131
|
+
try:
|
|
132
|
+
return invoke_peer(agent_path, message)
|
|
133
|
+
except RegistryError as exc:
|
|
134
|
+
logger.warning("invoke_agent failed: %s", exc)
|
|
135
|
+
return f"(no fue posible invocar al agente: {exc})"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
_TOOL_REGISTRY: dict[str, Callable[..., Any]] = {
|
|
139
|
+
"discover_agents": discover_agents,
|
|
140
|
+
"discover_skills": discover_skills,
|
|
141
|
+
"fetch_registry_skill": fetch_registry_skill,
|
|
142
|
+
"invoke_agent": invoke_agent,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def build_tools(cfg: AgentConfig) -> list[Any]:
|
|
147
|
+
"""Selecciona del registro las tools que el agente declaró en ``agent.yaml``."""
|
|
148
|
+
unknown = [t for t in cfg.tools if t not in _TOOL_REGISTRY]
|
|
149
|
+
if unknown:
|
|
150
|
+
raise ValueError(
|
|
151
|
+
f"agent.yaml declares unknown tools: {unknown}. "
|
|
152
|
+
f"Available: {sorted(_TOOL_REGISTRY.keys())}"
|
|
153
|
+
)
|
|
154
|
+
return [_TOOL_REGISTRY[name] for name in cfg.tools]
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: koda-agent-runtime
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Reusable runtime, config loader and bootstrap for KODA-ecosystem A2A agents on Amazon Bedrock AgentCore.
|
|
5
|
+
Project-URL: Homepage, https://bitbucket.org/kushki/koda-agent-runtime
|
|
6
|
+
Project-URL: Repository, https://bitbucket.org/kushki/koda-agent-runtime
|
|
7
|
+
Author: Kushki
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: a2a,agent,agentcore,bedrock,koda,strands
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: fastapi>=0.110.0
|
|
22
|
+
Requires-Dist: pyyaml>=6.0
|
|
23
|
+
Provides-Extra: bootstrap
|
|
24
|
+
Requires-Dist: bedrock-agentcore>=0.1.0; extra == 'bootstrap'
|
|
25
|
+
Requires-Dist: boto3>=1.35.0; extra == 'bootstrap'
|
|
26
|
+
Requires-Dist: strands-agents[a2a]>=0.1.0; extra == 'bootstrap'
|
|
27
|
+
Requires-Dist: uvicorn>=0.30.0; extra == 'bootstrap'
|
|
28
|
+
Provides-Extra: cdk
|
|
29
|
+
Requires-Dist: aws-cdk-aws-bedrock-agentcore-alpha; extra == 'cdk'
|
|
30
|
+
Requires-Dist: aws-cdk-lib>=2.150.0; extra == 'cdk'
|
|
31
|
+
Requires-Dist: constructs>=10.0.0; extra == 'cdk'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# koda-agent-runtime
|
|
35
|
+
|
|
36
|
+
Runtime compartido para agentes Koda A2A sobre Amazon Bedrock AgentCore.
|
|
37
|
+
Extrae en un solo paquete versionado las piezas que cada `koda-agent-*`
|
|
38
|
+
repite: constantes de custom headers, middleware FastAPI, cliente HTTP
|
|
39
|
+
hacia el registry, decoradores de tools, loader del `agent.yaml`, y un
|
|
40
|
+
bootstrap `build_agent_app(cfg)` que ensambla Strands + A2A + FastAPI
|
|
41
|
+
en una llamada.
|
|
42
|
+
|
|
43
|
+
Ver `KODA_AGENT_RUNTIME_ARCHITECTURE.md` en el monorepo `koda-platform`
|
|
44
|
+
para el diseño completo, precedente (`koda-mcp-access`), roadmap y
|
|
45
|
+
compatibilidad.
|
|
46
|
+
|
|
47
|
+
## Instalación
|
|
48
|
+
|
|
49
|
+
Elige el `extra` según lo que consuma el agente:
|
|
50
|
+
|
|
51
|
+
```toml
|
|
52
|
+
# El mínimo — headers, middleware, registry client, config loader.
|
|
53
|
+
"koda-agent-runtime>=0.1.0a0"
|
|
54
|
+
|
|
55
|
+
# El agente típico — ademas Strands + A2A + Bedrock para build_agent_app.
|
|
56
|
+
"koda-agent-runtime[bootstrap]>=0.1.0a0"
|
|
57
|
+
|
|
58
|
+
# El stack CDK del agente — Construct KodaAgentRuntime.
|
|
59
|
+
"koda-agent-runtime[cdk]>=0.1.0a0"
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Uso — un agente en 10 líneas
|
|
63
|
+
|
|
64
|
+
`src/agent.py`:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from pathlib import Path
|
|
68
|
+
import uvicorn
|
|
69
|
+
from koda_agent_runtime.config import load_agent_config
|
|
70
|
+
from koda_agent_runtime.app import build_agent_app
|
|
71
|
+
|
|
72
|
+
_BASE = Path(__file__).resolve().parent.parent
|
|
73
|
+
app = build_agent_app(load_agent_config(_BASE / "agent.yaml"), base_dir=_BASE)
|
|
74
|
+
|
|
75
|
+
if __name__ == "__main__":
|
|
76
|
+
uvicorn.run(app, host="0.0.0.0", port=9000)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`agent.yaml`:
|
|
80
|
+
|
|
81
|
+
```yaml
|
|
82
|
+
name: koda-agent-example
|
|
83
|
+
version: 0.1.0
|
|
84
|
+
description: |
|
|
85
|
+
Un agente de ejemplo.
|
|
86
|
+
|
|
87
|
+
model:
|
|
88
|
+
provider: bedrock
|
|
89
|
+
model_id: us.amazon.nova-lite-v1:0
|
|
90
|
+
temperature: 0.3
|
|
91
|
+
max_tokens: 4000
|
|
92
|
+
|
|
93
|
+
tools:
|
|
94
|
+
- discover_skills
|
|
95
|
+
- fetch_registry_skill
|
|
96
|
+
- invoke_agent
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Módulos
|
|
100
|
+
|
|
101
|
+
| Módulo | Responsabilidad |
|
|
102
|
+
|---|---|
|
|
103
|
+
| `koda_agent_runtime.headers` | Constantes `KODA_*_HEADER` + `ALLOWLISTED_HEADERS` (para `agentcore configure --request-header-allowlist`). |
|
|
104
|
+
| `koda_agent_runtime.context` | Module-level `_state` con `bearer` y `request_id`; `set_context`, `get_bearer`, `get_request_id`. |
|
|
105
|
+
| `koda_agent_runtime.middleware` | `koda_headers_middleware(app)` — captura los headers Koda-* que koda-proxy inyecta al invocar el runtime. Salta `/ping` para no borrar el state con health probes. |
|
|
106
|
+
| `koda_agent_runtime.registry` | `discover_agents`, `discover_skills`, `fetch_skill_bundle`, `invoke_peer` — hablan con el registry usando el bearer del state. |
|
|
107
|
+
| `koda_agent_runtime.tools` | Decoradores `@strands.tools.tool` sobre los helpers de `registry`. `build_tools(cfg)` filtra por lo declarado en `agent.yaml.tools`. |
|
|
108
|
+
| `koda_agent_runtime.config` | `load_agent_config(path)` → dataclass tipado `AgentConfig`. |
|
|
109
|
+
| `koda_agent_runtime.app` | `build_agent_app(cfg, base_dir)` → `FastAPI` con Strands `Agent` + `A2AServer` + middleware montados. Requiere `[bootstrap]` extra. |
|
|
110
|
+
|
|
111
|
+
## Contrato de headers Koda-*
|
|
112
|
+
|
|
113
|
+
koda-proxy (broker del registry) inyecta 8 custom headers al invocar
|
|
114
|
+
tu runtime. AgentCore solo forwardea headers con prefix
|
|
115
|
+
`X-Amzn-Bedrock-AgentCore-Runtime-Custom-`.
|
|
116
|
+
|
|
117
|
+
| Header | Contenido | Estable en cadenas A→B→C |
|
|
118
|
+
|---|---|---|
|
|
119
|
+
| `Koda-Authorization` | Bearer JWT vigente (Okta o self-signed 8h). | No — se refresca cuando expira. |
|
|
120
|
+
| `Koda-Sub` | Usuario humano original. | Sí. |
|
|
121
|
+
| `Koda-Email` | Email del usuario. | Sí. |
|
|
122
|
+
| `Koda-Roles` | Groups Okta del usuario. | Sí. |
|
|
123
|
+
| `Koda-Chain-Depth` | Hops desde el usuario. | +1 por hop. |
|
|
124
|
+
| `Koda-Request-Id` | uuid para trace end-to-end. | Sí. |
|
|
125
|
+
| `Koda-Agent-Path` | Path del agente que recibe. | N/A. |
|
|
126
|
+
| `Koda-Caller-Type` | `user` \| `agent`. | Depende del hop. |
|
|
127
|
+
|
|
128
|
+
Todos los strings viven en `koda_agent_runtime.headers` como constantes.
|
|
129
|
+
Nunca los repitas en tu código.
|
|
130
|
+
|
|
131
|
+
## Anti-patrones
|
|
132
|
+
|
|
133
|
+
- **No** uses `contextvars.ContextVar` para propagar el bearer entre
|
|
134
|
+
middleware y tools: Strands corre tools en threads distintos al
|
|
135
|
+
request handler; el ContextVar aparece vacío. Usa `set_context()`.
|
|
136
|
+
- **No** firmes SigV4 desde el agente para invocar peers. Delega via
|
|
137
|
+
`invoke_peer(<path>, <msg>)` — el registry firma por ti.
|
|
138
|
+
- **No** llames `set_context()` en el middleware si no hay bearer. Los
|
|
139
|
+
`/ping` de AgentCore te borrarían el state que otra request iba a
|
|
140
|
+
usar.
|
|
141
|
+
|
|
142
|
+
## Desarrollo
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
uv sync --dev
|
|
146
|
+
uv run pytest
|
|
147
|
+
uv run ruff check src/
|
|
148
|
+
uv build
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Release: bump `pyproject.toml`, tag `vX.Y.Z`, push tag.
|
|
152
|
+
|
|
153
|
+
## Versionado
|
|
154
|
+
|
|
155
|
+
- **v0.x** — alpha, breaking changes tolerados. Todos los agentes en
|
|
156
|
+
migración inicial.
|
|
157
|
+
- **v1.0.0** — cuando la API sea estable y >=3 agentes la consuman en
|
|
158
|
+
producción. A partir de acá, SemVer estricto.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
koda_agent_runtime/__init__.py,sha256=aKoEupSpEhW7jw271Abae0-XuZzLXrQGE7h7xiW0IVY,2645
|
|
2
|
+
koda_agent_runtime/app.py,sha256=O9LAkqetgIwvQEr5RIpRZGPwxMhoZT9vMHJABysjwRU,5316
|
|
3
|
+
koda_agent_runtime/config.py,sha256=zRKpaGoB6-eB8CWyyGEuX4Hck2sypfcE7YkIYtDst08,4743
|
|
4
|
+
koda_agent_runtime/context.py,sha256=oMXwh7hrCP16-maqGigLDeLMYMTQrbIX_Q5lqbpNFhE,1531
|
|
5
|
+
koda_agent_runtime/headers.py,sha256=ikk46_aKG_aRRFKv8InhXF0RTlZGR_of8TJCw_OkO0w,2232
|
|
6
|
+
koda_agent_runtime/middleware.py,sha256=y__HWH-o9f_sBrFoADd4taBVAAO_6q-0QBP225_MCw8,1822
|
|
7
|
+
koda_agent_runtime/registry.py,sha256=G1Hy5jB0j9qRLxzLJ0v4V_LKP-hQNKLzBMrOYCPqwDA,7066
|
|
8
|
+
koda_agent_runtime/tools.py,sha256=BTetRhyjfzA6hsxeHqjG_42qTEeBW4LONg8lsB_tnKM,4862
|
|
9
|
+
koda_agent_runtime-0.1.0.dist-info/METADATA,sha256=SvfgrK-fDp-hKbxBmog5i8deQTTg1bFzRIdxxyBquog,5956
|
|
10
|
+
koda_agent_runtime-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
11
|
+
koda_agent_runtime-0.1.0.dist-info/licenses/LICENSE,sha256=-zqSdvirucW7JLKAsKp4egqVDzNOE7tt9TRaUpHR5PA,1063
|
|
12
|
+
koda_agent_runtime-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kushki
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|