feat: v1 — boilerplate WxO + web
Boilerplate completo para construir soluciones agénticas sobre IBM watsonx Orchestrate (ADK 2.x) con una capa web encima. Destilado de cotemar-poc-n1 y dun-casos-prueba. Incluye: - 11 docs (best practices, architecture patterns, ADK cheatsheet, observability, tool authoring, deployment, RUNBOOK, DEPLOY_TO_NEW_WOX, known-issues con 16 errores reales y fix, eval strategy, INDEX) - 13 templates WxO (orchestrator/specialist/single-meta agents, 3 connections, KB + runbook, observable_tool decorator, coercion helpers, Python tools, OpenAPI spec, backend filter endpoint, webhook validator HMAC, MCP connection) - 6 scripts (deploy idempotente con fallback ADK, undeploy, reset, check-adk-version, new-specialist scaffold, eval-agents runner) - 4 eval pieces (linter de best practices, runner, smoke-test, direct backend probe) + scenario templates - 8 subagentes Claude (.claude/agents/) — wxo-architect, wxo-agent-author, wxo-tool-author, runbook-author, mock-builder, backend-tool-builder, eval-author, web-layer-builder - Skill bundle fit-wxo-bootstrap/ (SKILL.md + 3 templates) listo para copiar a ~/.claude/skills/ - Web layer default FastAPI+HTMX con vista timeline observable + endpoint receptor de trazas - Docker compose Coolify-ready (healthcheck wget -qO-, sin labels Traefik, network split internal:true) - CI Gitea workflow con lint + smoke Best practices enforced por evals/lint_wxo_yaml.py: - A1: máx 10 tools por agente - A3: orchestrator sin tools de remediación - A6: agente sin propósito (react sin tools ni KB) - T1: @observable_tool obligatorio, no @tool directo - T3: _compat shim inline en tools.py - D1: docker-compose sin wget --spider - I-005: OpenAPI con description per-operation - I-009: sin labels Traefik manuales Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
108
wxo/tools/openapi/_backend_filter_endpoint.py
Normal file
108
wxo/tools/openapi/_backend_filter_endpoint.py
Normal file
@@ -0,0 +1,108 @@
|
||||
"""Template — endpoint en tu backend que expone un OpenAPI filtrado a WxO.
|
||||
|
||||
Patrón Dun: el backend FastAPI expone TODOS sus endpoints, pero solo
|
||||
algunos son "tools" que WxO puede invocar. Este endpoint filtra el
|
||||
openapi.json a una allowlist `PUBLIC_TOOLS`, fuerza description +
|
||||
security per-operation, y resuelve $ref transitivamente.
|
||||
|
||||
WxO lo importa con:
|
||||
orchestrate tools import -k openapi \
|
||||
-f <(curl -s $BACKEND_URL/api/v1/orchestrate-tools-spec.json) \
|
||||
--app-id mi_backend
|
||||
|
||||
(O bien `deploy-wxo.sh` baja el spec y lo patche localmente.)
|
||||
|
||||
Cómo integrar:
|
||||
from .orchestrate_spec import build_public_spec
|
||||
app = FastAPI(...)
|
||||
|
||||
@app.get("/api/v1/orchestrate-tools-spec.json")
|
||||
def orchestrate_tools_spec():
|
||||
return build_public_spec(app)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
|
||||
# ───────────────────────────────────────────────────────────────────────────
|
||||
# ALLOWLIST — qué operaciones expone tu backend a WxO.
|
||||
# Formato: "METHOD /path/exacto"
|
||||
# ───────────────────────────────────────────────────────────────────────────
|
||||
PUBLIC_TOOLS = {
|
||||
"POST /api/v1/cases/run",
|
||||
"GET /api/v1/cases/{case_id}",
|
||||
"POST /api/v1/cases/{case_id}/approve",
|
||||
}
|
||||
|
||||
|
||||
def build_public_spec(app: Any) -> dict[str, Any]:
|
||||
"""Genera el spec filtrado para WxO.
|
||||
|
||||
Args:
|
||||
app: la instancia FastAPI (u objeto con .openapi()).
|
||||
|
||||
Returns:
|
||||
dict con el OpenAPI spec listo para importar.
|
||||
"""
|
||||
full = deepcopy(app.openapi())
|
||||
|
||||
spec: dict[str, Any] = {
|
||||
"openapi": full.get("openapi", "3.0.0"),
|
||||
"info": {**full["info"], "title": full["info"]["title"] + " (orchestrate)"},
|
||||
"servers": full.get("servers", [{"url": "https://CHANGEME/api/v1"}]),
|
||||
"paths": {},
|
||||
"components": {"schemas": {}, "securitySchemes": full.get("components", {}).get("securitySchemes", {})},
|
||||
"security": full.get("security", []),
|
||||
}
|
||||
|
||||
# ── 1. Filtrar paths a la allowlist
|
||||
for path, item in full.get("paths", {}).items():
|
||||
kept_methods: dict[str, Any] = {}
|
||||
for method, op in item.items():
|
||||
if method.upper() not in ("GET", "POST", "PATCH", "PUT", "DELETE"):
|
||||
continue
|
||||
key = f"{method.upper()} {path}"
|
||||
if key not in PUBLIC_TOOLS:
|
||||
continue
|
||||
# Fix issue I-005: description obligatorio per-op
|
||||
op["description"] = op.get("description") or op.get("summary") or f"{method} {path}"
|
||||
# Fix issue I-006: security per-op (no se hereda)
|
||||
op["security"] = spec["security"]
|
||||
kept_methods[method] = op
|
||||
if kept_methods:
|
||||
spec["paths"][path] = kept_methods
|
||||
|
||||
# ── 2. Resolver $ref transitivamente — solo schemas usados
|
||||
all_schemas = full.get("components", {}).get("schemas", {})
|
||||
needed: set[str] = set()
|
||||
|
||||
def _walk(o: Any) -> None:
|
||||
if isinstance(o, dict):
|
||||
for k, v in o.items():
|
||||
if k == "$ref" and isinstance(v, str) and v.startswith("#/components/schemas/"):
|
||||
needed.add(v.split("/")[-1])
|
||||
else:
|
||||
_walk(v)
|
||||
elif isinstance(o, list):
|
||||
for x in o:
|
||||
_walk(x)
|
||||
|
||||
_walk(spec["paths"])
|
||||
|
||||
# Closure transitiva
|
||||
pending = list(needed)
|
||||
while pending:
|
||||
s = pending.pop()
|
||||
if s in spec["components"]["schemas"]:
|
||||
continue
|
||||
if s not in all_schemas:
|
||||
continue
|
||||
spec["components"]["schemas"][s] = all_schemas[s]
|
||||
before = set(needed)
|
||||
_walk(all_schemas[s])
|
||||
for new in needed - before:
|
||||
pending.append(new)
|
||||
|
||||
return spec
|
||||
80
wxo/tools/openapi/_template_openapi_spec.yaml
Normal file
80
wxo/tools/openapi/_template_openapi_spec.yaml
Normal file
@@ -0,0 +1,80 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Template — OpenAPI 3.1 spec para WxO
|
||||
#
|
||||
# Importar con:
|
||||
# orchestrate tools import -k openapi -f este_archivo.yaml --app-id mi_app
|
||||
#
|
||||
# REQUISITOS (paga con dolor):
|
||||
# - description per-operation (issue I-005)
|
||||
# - security per-operation, NO solo global (issue I-006)
|
||||
# - servers[0].url parcheado en deploy time según env
|
||||
# - Si el backend usa FastAPI, mejor exponer un endpoint /orchestrate-tools-spec.json
|
||||
# que filtra dinámicamente. Ver _backend_filter_endpoint.py.
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: "REPLACE Service API (orchestrate-exposed subset)"
|
||||
version: "1.0.0"
|
||||
description: "Subset filtrado de la API expuesto a WxO."
|
||||
|
||||
servers:
|
||||
# PATCH ME en deploy time:
|
||||
# jq --arg url "$BACKEND_URL" '.servers = [{"url": $url}]'
|
||||
- url: "https://CHANGEME/api/v1"
|
||||
|
||||
# Security definitions (NO heredan a las ops — issue I-006)
|
||||
components:
|
||||
securitySchemes:
|
||||
OrchestrateToken:
|
||||
type: apiKey
|
||||
in: header
|
||||
name: X-Orchestrate-Token # custom header, NO Bearer (regla C2)
|
||||
|
||||
schemas:
|
||||
RunCaseInput:
|
||||
type: object
|
||||
required: [case_id, target_id]
|
||||
properties:
|
||||
case_id:
|
||||
type: string
|
||||
description: "ID del caso a procesar."
|
||||
target_id:
|
||||
type: integer
|
||||
description: "ID del recurso objetivo."
|
||||
options:
|
||||
type: array
|
||||
items: { type: string }
|
||||
description: "Opciones adicionales."
|
||||
|
||||
RunCaseResult:
|
||||
type: object
|
||||
properties:
|
||||
ok: { type: boolean }
|
||||
ticket_id: { type: string }
|
||||
package_url: { type: string }
|
||||
error: { type: string, nullable: true }
|
||||
|
||||
paths:
|
||||
/cases/run:
|
||||
post:
|
||||
operationId: run_full_case
|
||||
summary: "Run a case end-to-end"
|
||||
# description OBLIGATORIO — issue I-005
|
||||
description: |
|
||||
Procesa un caso completo invocando los substeps en el backend.
|
||||
Devuelve ok=true + ticket_id + package_url, o ok=false + error.
|
||||
Cada substep emite write_audit con case_id.
|
||||
security: # per-operation — issue I-006
|
||||
- OrchestrateToken: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/RunCaseInput" }
|
||||
responses:
|
||||
"200":
|
||||
description: "Resultado del procesamiento."
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/RunCaseResult" }
|
||||
100
wxo/tools/openapi/_webhook_validator.py
Normal file
100
wxo/tools/openapi/_webhook_validator.py
Normal file
@@ -0,0 +1,100 @@
|
||||
"""Template — validador HMAC-SHA256 para webhooks de Orchestrate.
|
||||
|
||||
Cuando WxO te manda un webhook (run lifecycle, completion, etc.), valida
|
||||
la firma para descartar requests no autorizados.
|
||||
|
||||
Headers que WxO envía:
|
||||
X-Orchestrate-Timestamp (unix ts, ms)
|
||||
X-Orchestrate-Nonce (string aleatorio)
|
||||
X-Orchestrate-Signature (hex de HMAC-SHA256)
|
||||
|
||||
La firma se calcula sobre:
|
||||
HMAC-SHA256(secret, f"{timestamp}.{nonce}.{body}")
|
||||
|
||||
Reglas:
|
||||
- Tolerar skew de timestamp de 300s (HTTP 408 si stale)
|
||||
- Rechazar nonces repetidos (replay protection — guardar últimos 10k)
|
||||
- HTTP 401 si firma no matchea
|
||||
|
||||
Origen: Dun `backend/app/orchestrate/webhook_validator.py`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
from collections import deque
|
||||
from threading import Lock
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class WebhookValidator:
|
||||
def __init__(self, secret: str, skew_seconds: int = 300, nonce_cache_size: int = 10_000):
|
||||
self._secret = secret.encode("utf-8")
|
||||
self._skew = skew_seconds
|
||||
self._nonces: deque[str] = deque(maxlen=nonce_cache_size)
|
||||
self._nonces_set: set[str] = set()
|
||||
self._lock = Lock()
|
||||
|
||||
def validate(self, timestamp: str, nonce: str, signature: str, body: bytes) -> Optional[str]:
|
||||
"""Returns None if valid, else an error code: 'stale' | 'replay' | 'badsig'."""
|
||||
# ── 1. Timestamp freshness
|
||||
try:
|
||||
ts_ms = int(timestamp)
|
||||
except ValueError:
|
||||
return "badsig"
|
||||
now_ms = int(time.time() * 1000)
|
||||
if abs(now_ms - ts_ms) > self._skew * 1000:
|
||||
return "stale"
|
||||
|
||||
# ── 2. Nonce replay
|
||||
with self._lock:
|
||||
if nonce in self._nonces_set:
|
||||
return "replay"
|
||||
|
||||
# ── 3. Signature
|
||||
msg = f"{timestamp}.{nonce}.".encode("utf-8") + body
|
||||
expected = hmac.new(self._secret, msg, hashlib.sha256).hexdigest()
|
||||
if not hmac.compare_digest(expected, signature):
|
||||
return "badsig"
|
||||
|
||||
# Valid — register nonce
|
||||
with self._lock:
|
||||
if len(self._nonces) >= self._nonces.maxlen:
|
||||
# deque is bounded; rotate set in sync
|
||||
expired = self._nonces[0]
|
||||
self._nonces_set.discard(expired)
|
||||
self._nonces.append(nonce)
|
||||
self._nonces_set.add(nonce)
|
||||
return None
|
||||
|
||||
|
||||
# Ejemplo de uso en FastAPI:
|
||||
#
|
||||
# from fastapi import APIRouter, Request, Header, HTTPException
|
||||
# from .webhook_validator import WebhookValidator
|
||||
#
|
||||
# router = APIRouter()
|
||||
# _validator = WebhookValidator(secret=os.environ["WEBHOOK_SECRET"])
|
||||
#
|
||||
# @router.post("/webhooks/orchestrate")
|
||||
# async def orch_webhook(
|
||||
# request: Request,
|
||||
# x_orchestrate_timestamp: str = Header(...),
|
||||
# x_orchestrate_nonce: str = Header(...),
|
||||
# x_orchestrate_signature: str = Header(...),
|
||||
# ):
|
||||
# body = await request.body()
|
||||
# err = _validator.validate(
|
||||
# x_orchestrate_timestamp,
|
||||
# x_orchestrate_nonce,
|
||||
# x_orchestrate_signature,
|
||||
# body,
|
||||
# )
|
||||
# if err == "stale":
|
||||
# raise HTTPException(status_code=408, detail="timestamp skew")
|
||||
# if err == "replay":
|
||||
# raise HTTPException(status_code=409, detail="nonce reused")
|
||||
# if err == "badsig":
|
||||
# raise HTTPException(status_code=401, detail="bad signature")
|
||||
# # ... handle payload
|
||||
Reference in New Issue
Block a user