# SPEC-009 — Channel Gateway ## Scope O Channel Gateway normaliza payloads of canais external for GatewayRequest and traduz ChannelResponse for the formato of Response of the canal. ## Modos of Operations | Modo | Description | |---|---| | Embedded | Normalização no próprio backend for demos and cenários simples. | | External | service dedicado for canais corporativos. | ## GatewayRequest ```json { "channel": "whatsapp", "tenant_id": "default", "agent_id": "telecom_contas", "payload": { "message": "Segunda via de fatura", "session_id": "5511999999999", "user_id": "5511999999999", "message_id": "wamid.123", "business_context": { "customer_key": "5511999999999", "interaction_key": "wamid.123", "session_key": "5511999999999" }, "metadata": { "source_channel": "whatsapp", "source_message_type": "interactive" } } } ``` ## ChannelResponse ```json { "channel": "whatsapp", "session_id": "default:telecom_contas:5511999999999", "text": "Encontrei sua fatura...", "metadata": { "tenant_id": "default", "agent_id": "telecom_contas", "route": "billing_agent", "intent": "billing_invoice_explanation" } } ``` ## Flow External ```mermaid sequenceDiagram participant Canal participant CG as Channel Gateway participant AG as Agent Gateway participant RT as Agent Runtime Canal->>CG: payload bruto CG->>CG: autenticação, parse, dedupe CG->>AG: GatewayRequest AG->>RT: execução RT-->>AG: ChannelResponse AG-->>CG: ChannelResponse CG-->>Canal: resposta do canal ``` ## Responsibilities | Responsibility | Detalhe | |---|---| | Auth | validate assinatura, token or origem. | | Parse | Interpretar payload bruto. | | Dedup | Evitar reprocessamento por message_id. | | Normalize | create GatewayRequest. | | Business Context | Mapear chaves canônicas. | | Forward | Chamar Agent Gateway. | | Translate | Converter ChannelResponse for canal. | | Observe | emit logs, Metrics and traces. | ## Idempotência Chave: ```text tenant_id:channel:user_id:message_id ``` Comportamentos: | Situação | Ação | |---|---| | Primeira Message | Processar. | | Duplicada em andamento | return 202 or Response controlada. | | Duplicada concluída | return Response previous. | ## Versionamento Header: ```http X-Agent-Framework-Contract: gateway-request-v1 ``` field alternativo: ```json { "payload": { "metadata": { "contract_version": "gateway-request-v1" } } } ``` ## Security Validations: - assinatura of the webhook; - origem allowed; - tamanho máximo; - tipo of evento allowed; - anexos permitidos; - sanitização of texto; - remoção of tokens; - máscara of Data sensíveis; - rate limit; - deduplicação. ## Erros | Código HTTP | Uso | |---|---| | 400 | Payload invalid of the canal. | | 401 | Authentication ausente. | | 403 | Origem No autorizada. | | 422 | GatewayRequest invalid. | | 429 | Rate limit. | | 500 | Error Internal. | | 503 | Runtime unavailable. | ## Anti-patterns - Agent lendo payload bruto. - Workflow tratando `channel == whatsapp`. - MCP recebendo payload bruto. - Tokens of the canal em metadata. - Gateway External executando regra of Agent. - Frontend enviando fields outside of the Contract. ## Requirements No Funcionais | Categoria | Requirement | |---|---| | Availability | Components deployáveis expõem `/health` and `/ready`. | | Escalabilidade | Apps stateless escalam horizontalmente. State conversational fica em repositórios external. | | Security | Segredos are fornecidos por secret store or Kubernetes Secrets. | | Observability | Logs, Metrics and traces usam correlation por request_id, trace_id, session_id, tenant_id and agent_id. | | Auditabilidade | Decisions of rota, guardrail, judge, MCP and LLM are rastreáveis. | | Portabilidade | Execution suportada em local, Docker Compose and Kubernetes/OKE. | | Configuration | Comportamento variável is controlado por `.env` and YAML versionado. | ## Acceptance criteria - [ ] Payload bruto is convertido for GatewayRequest. - [ ] GatewayRequest is validado. - [ ] message_id Is used to idempotência. - [ ] business_context contains chaves canônicas. - [ ] Response of the runtime is traduzida for the canal. - [ ] Payload bruto No chega ao Agent Runtime. - [ ] Auth/rate limit/dedup are implementados. - [ ] Erros are padronizados. - [ ] Contract possui Version. - [ ] Logs/traces usam request_id and trace_id. ## Glossário | Termo | Definição | |---|---| | Agent Platform | Plataforma composta por runtime, gateways, evaluator, templates, contracts and Components operational. | | Agent Framework | Biblioteca/core reutilizável with contracts, guardrails, judges, Memory, telemetria, providers and utilitários. | | Agent Runtime | Motor of Execution of Agents based on LangGraph, State, Session, Memory, checkpoints, Routing and ciclo of vida. | | Agent Gateway | Aplicação deployável of Input, Routing and orquestração between backends/Agents. | | Channel Gateway | Aplicação or módulo of normalização of payloads of canais for GatewayRequest. | | AI Gateway | Aplicação of Governance, Routing and abstração of Calls LLM/embedding. | | MCP Gateway | Aplicação of Governance and Routing of tools MCP. | | Evaluator | layer of Evaluation online/offline, regressão and Certification. | | Business Context | Conjunto of chaves canônicas of negócio: customer_key, contract_key, interaction_key, account_key, resource_key and session_key. |