synapse

package module
v0.0.59 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 15 Imported by: 0

README

Synapse Go SDK

Client oficial em Go para a API Synapse.


Instalação

go get github.com/WonitTecnologia/synapse

Início rápido

import "github.com/WonitTecnologia/synapse"

client, err := synapse.NewClient("seu-token", nil)
if err != nil {
    log.Fatal(err)
}

Configuração

NewClient aceita um token obrigatório e um *Options opcional.

client, err := synapse.NewClient("seu-token", &synapse.Options{
    BaseURL: "https://staging.synapse.example.com", // padrão: https://synapse.wonit.net.br
    Timeout: 15 * time.Second,                      // padrão: 30s
})
Campo Tipo Descrição
BaseURL string Sobrescreve a URL base da API (staging, self-hosted…)
Host string Sobrepõe o header Host em toda requisição (HTTP e WebSocket). Para conexão interna por IP — ver abaixo
Timeout time.Duration Timeout por requisição HTTP. Padrão: 30s
Conexão interna (IP direto + Host header)

Para conectar pela rede interna sem passar pela URL pública (mesmo padrão do cliente CSA): aponte a BaseURL para o IP e informe o DNS do virtual host em Host.

client, err := synapse.NewClient("seu-token", &synapse.Options{
    BaseURL: "http://172.16.50.41",        // IP interno (porta opcional)
    Host:    "synapse-dev.wonit.cloud",    // DNS enviado no header Host
})
  • Vale para todas as requisições HTTP (inclusive upload multipart) e para o WebSocket de monitoramento (no wss o Host também é usado como SNI/ServerName).
  • Sem Host, tudo segue normalmente pela BaseURL informada (modo público).

Domínios

Campo Interface Endpoints cobertos
client.Auth AuthCase Login, logout, OTP, reset de senha, API tokens
client.User UserCase CRUD de usuários
client.Tenant TenantCase CRUD de tenants
client.Provider ProviderCase Listagem de providers do catálogo
client.Service ServiceCase Listagem de services do catálogo
client.Google GoogleCase Integração Google Vision AI (OCR)
client.OpenAI OpenAICase Chat, análise de imagem, transcrição de áudio
client.Chatvolt ChatvoltCase Query a agentes Chatvolt
client.OpenRouter OpenRouterCase Workspace OpenRouter (sync, modelos, analytics)
client.Collection CollectionCase Coleções vetoriais (Qdrant) da base de conhecimento
client.Document DocumentCase Upload e vetorização de documentos
client.Agent AgentCase CRUD de agentes de IA + chat (com RAG)
client.Mcp McpCase Integrações MCP (Model Context Protocol)
client.ExternalApi ExternalApiCase APIs externas (HTTP cruas) como tools do agente
client.Monitor MonitorCase WebSocket de monitoramento — stream de eventos do agente em tempo real (ver seção)

Auth

Login
resp, err := client.Auth.Login(ctx, synapse.LoginRequest{
    Email:    "usuario@empresa.com",
    Password: "senha123",
})

fmt.Println(resp.Token)
fmt.Println(resp.User.Name)
Healthcheck (validar token)
resp, err := client.Auth.Healthcheck(ctx)
fmt.Println(resp.User.Email)
Logout
err := client.Auth.Logout(ctx, "token-a-revogar")
Solicitar OTP
err := client.Auth.RequestOTP(ctx, synapse.OTPRequest{
    Email: "usuario@empresa.com",
})
Resetar senha com OTP
err := client.Auth.ResetPassword(ctx, synapse.OTPResetPasswordRequest{
    Email:    "usuario@empresa.com",
    OTP:      "123456",
    Password: "novaSenha@123",
})
API Tokens
// Criar
token, err := client.Auth.CreateAPIToken(ctx, synapse.ApiTokenCreateRequest{
    Name:        "Integração CI",
    Description: "Token para pipeline de deploy",
    ExpireAt:    "2026-12-31T00:00:00Z", // opcional
})
fmt.Println(token.Token)

// Listar
list, err := client.Auth.ListAPITokens(ctx, 1, 20)
for _, t := range list.APITokens {
    fmt.Println(t.Name, t.ExpireAt)
}

User

// Buscar por UUID ou email
user, err := client.User.Get(ctx, "uuid-ou-email")

// Listar
users, err := client.User.List(ctx, synapse.ListUsersParams{
    Page:             1,
    Size:             20,
    TenantIdentifier: "uuid-do-tenant", // apenas SystemAdmin
})

// Criar  (identifier = UUID ou documento do tenant)
user, err := client.User.Create(ctx, "uuid-do-tenant", synapse.CreateUserRequestDto{
    Name:     "João Silva",
    Email:    "joao@empresa.com",
    Password: "senha@123",
    Role:     synapse.UserRoleTenantUser,
})

// Atualizar
user, err := client.User.Update(ctx, "uuid-do-usuario", synapse.UpdateUserRequestDto{
    Name: "João Silva Jr.",
})

// Deletar
err := client.User.Delete(ctx, "uuid-ou-email")
Roles disponíveis
Constante Valor
synapse.UserRoleSystemAdmin SYSTEM_ADMIN
synapse.UserRoleTenantAdmin TENANT_ADMIN
synapse.UserRoleTenantUser TENANT_USER

Tenant

// Buscar por UUID ou documento (CNPJ/CPF)
tenant, err := client.Tenant.Get(ctx, "uuid", "")
tenant, err := client.Tenant.Get(ctx, "", "12345678000199")

// Listar
tenants, err := client.Tenant.List(ctx, 1, 10)

// Criar
tenant, err := client.Tenant.Create(ctx, synapse.CreateTenantRequestDto{
    Name:     "Empresa XPTO",
    Document: "12345678000199",
})

// Atualizar
live := true
tenant, err := client.Tenant.Update(ctx, "uuid-do-tenant", synapse.UpdateTenantRequestDto{
    Name: "Empresa XPTO Ltda.",
    Live: &live,
})

// Deletar
err := client.Tenant.Delete(ctx, "uuid-do-tenant", "")

// Providers
provider, err := client.Provider.Get(ctx, "uuid-do-provider")
providers, err := client.Provider.List(ctx, 1, 20)

// Services
service, err := client.Service.Get(ctx, "uuid-do-service")
services, err := client.Service.List(ctx, 1, 20)

Google Vision AI

Configurar integração
err := client.Google.Configure(ctx, synapse.ConfigureGoogleRequest{
    Credentials: synapse.VisionAICredentialsDTO{Token: "sua-api-key-google"},
    IsActive:    true,
})
OCR (extração de texto)
imageBytes, _ := os.ReadFile("nota_fiscal.jpg")

result, err := client.Google.VisionOCR(ctx, "nota_fiscal.jpg", imageBytes)
fmt.Println(result.Response)

Formatos aceitos: png, jpg, jpeg, webp.


OpenAI

Configurar integração
err := client.OpenAI.Configure(ctx, synapse.ConfigureOpenAIRequest{
    Credentials: synapse.OpenAICredentialsDTO{Token: "sk-..."},
    Settings: synapse.OpenAISettingsDTO{
        Model:       synapse.OpenAIModelGPT4o,
        Temperature: 0.7,
    },
    IsActive: true,
})
Modelos disponíveis
Constante Modelo
synapse.OpenAIModelGPT4oMini gpt-4o-mini
synapse.OpenAIModelGPT4o gpt-4o
synapse.OpenAIModelGPT4_1 gpt-4.1
synapse.OpenAIModelGPT4_1Mini gpt-4.1-mini
synapse.OpenAIModelO4Mini o4-mini
Chat Completion
reply, err := client.OpenAI.Chat(ctx, synapse.ChatCompletionRequest{
    Prompt: "Resuma este contrato em 3 pontos.",
})
fmt.Println(reply.Response)
Análise de imagem
imageBytes, _ := os.ReadFile("diagrama.png")

result, err := client.OpenAI.AnalyzeImage(ctx, "diagrama.png", imageBytes, "Descreva o que está nesta imagem.")
fmt.Println(result.Response)
Transcrição de áudio
audioBytes, _ := os.ReadFile("reuniao.mp3")

result, err := client.OpenAI.TranscribeAudio(ctx, synapse.TranscribeAudioRequest{
    FileName: "reuniao.mp3",
    Content:  audioBytes,
    Model:    "whisper-1",    // whisper-1 | gpt-4o-transcribe | gpt-4o-mini-transcribe
    Language: "pt",           // opcional
    Prompt:   "",             // opcional: contexto para melhorar a transcrição
})
fmt.Println(result.Response)

Chatvolt

Configurar integração
err := client.Chatvolt.Configure(ctx, synapse.ConfigureChatvoltRequest{
    Credentials: synapse.ChatvoltCredentialsDTO{Token: "seu-token-chatvolt"},
    IsActive:    true,
})
Query a agente
// Nova conversa
resp, err := client.Chatvolt.Query(ctx, synapse.ChatvoltAgentQueryRequest{
    AgentID: "id-do-agente",
    Query:   "Qual o status do meu pedido #1234?",
})
fmt.Println(resp.Answer)
fmt.Println(resp.ConversationID) // guarde para continuar o contexto

// Continuar conversa existente
resp, err = client.Chatvolt.Query(ctx, synapse.ChatvoltAgentQueryRequest{
    AgentID:        "id-do-agente",
    ConversationID: resp.ConversationID,
    Query:          "E qual a previsão de entrega?",
})
Enviar dados de contato
resp, err := client.Chatvolt.Query(ctx, synapse.ChatvoltAgentQueryRequest{
    AgentID: "id-do-agente",
    Query:   "Preciso de suporte.",
    Contact: &synapse.ChatvoltContact{
        Email:     "cliente@email.com",
        FirstName: "Maria",
        LastName:  "Souza",
    },
})

WebSocket de monitoramento (Monitor)

Stream em tempo real dos eventos de execução dos agentes de IA — chat, tool calls (MCP e APIs externas), RAG, erros e processamento de arquivos. Canal somente-recebimento: o SDK confirma cada entrega automaticamente (protocolo de ACK interno) e reconecta sozinho; você só consome o canal de eventos.

  • Token master (SYSTEM_ADMIN) → recebe eventos de todos os tenants.
  • Token de tenant → recebe apenas os eventos do próprio tenant.
  • Diferente do log persistido, os eventos chegam sem truncamento (parâmetros, retorno de API e resultado de tools íntegros).
Uso básico
stream, err := client.Monitor.StreamLogs(ctx, nil)
if err != nil {
    log.Fatal(err)
}
defer stream.Close()

for evt := range stream.Events() {
    fmt.Printf("[%s] %s — %s\n", evt.Category, evt.AgentName, evt.Summary)
}
// o canal fecha quando ctx é cancelado ou stream.Close() é chamado
Opções (StreamLogsOptions)
stream, err := client.Monitor.StreamLogs(ctx, &synapse.StreamLogsOptions{
    Session: "3f2a...-uuid",                 // retoma a fila do servidor após reconexão
    Buffer:  512,                            // capacidade do canal (padrão: 256)
    OnConnect: func(session string) {        // handshake ok (conexão E reconexões)
        log.Println("WS conectado, session:", session)
    },
    OnError: func(err error) {               // erros de conexão (o stream segue tentando)
        log.Println("WS erro:", err)
    },
})
Campo Tipo Descrição
Session string UUID de sessão. Reconexões com a mesma session retomam a fila de entrega pendente no servidor. Padrão: UUID aleatório mantido pela vida do stream
Buffer int Capacidade do canal de eventos. Padrão: 256
OnConnect func(session string) Disparado a cada handshake bem-sucedido — conexão inicial e cada reconexão automática
OnError func(error) Erros de conexão/handshake. Apenas observabilidade: a reconexão é automática (backoff 1s → 30s)
EventStream
Método Descrição
Events() <-chan AgentEvent Canal dos eventos recebidos (fecha no encerramento)
Session() string UUID da sessão em uso (útil para logar/persistir)
Close() Encerra o stream e fecha o canal
AgentEvent
Campo Tipo Descrição
UUID string Identidade do evento (use para dedup, se necessário)
TenantUUID string Tenant dono do evento
AgentUUID / AgentName string Agente que gerou o evento
ConversationUUID *string Conversa interna
ConversationExternalID *string ID externo (ex.: protocolo)
Level string info | warn | error
Category string EventCategoryChat | EventCategoryToolCall | EventCategoryRAG | EventCategoryError | EventCategoryFileProcess
Summary string Resumo humano do evento
Detail map[string]any Detalhe por categoria (chat: user_msg/response íntegros, reasoning…)
ToolName *string (tool_call) nome da ferramenta
ToolParams map[string]any (tool_call) parâmetros sem truncar
ToolSuccess *bool (tool_call) sucesso
ToolResult string (tool_call) resultado sem truncar
APIResponse string (tool_call de API externa) corpo da resposta sem truncar
Rag *AgentEventRag (rag) ChunksFound, Error, Chunks[]
DurationMs *int Duração da operação
Model *string Modelo que atendeu o turno
Tokens *AgentEventTokens Prompt, Completion, Total, Embedding
CreatedAt time.Time UTC

AgentEventRagChunk (cada trecho recuperado pelo RAG): Filename, ChunkIndex, Score, ScorePct (percentual de similaridade) e Text (conteúdo completo).

Semântica de reconexão e entrega
  • Reconexão automática com backoff exponencial (1s dobrando até 30s), mantendo a mesma Session — o servidor retoma a fila pendente de onde parou.
  • Entrega confirmada (at-least-once): o servidor reenvia envelopes não confirmados; em cenários raros de ACK perdido um evento pode chegar duplicado — dedup pelo evt.UUID se isso importar para o consumidor.
  • O servidor pode fechar o socket com código 1012 (refresh forçado); o SDK trata como queda normal e reconecta.
  • Conexão interna: as opções BaseURL (IP) + Host do NewClient valem também para o WebSocket (ver Conexão interna).

Documentação do lado servidor (rota, escopos, protocolo de ACK, fila Redis e política de reentrega): documentacao/websocket/README.md no repositório synapse-api.

Agente — Logs de execução (REST)

A API REST client.Agent.ListLogs / client.Agent.LogsStats retorna o histórico persistido dos eventos do agente. A partir da v0.0.41, o AgentLogItem foi pareado com o AgentEvent do WebSocket — os mesmos campos estruturados (tool_result, api_response, rag, tokens) agora estão disponíveis também na resposta REST, com os dados íntegros (sem truncamento, que continua sendo regra apenas do detail para compatibilidade).

resp, err := client.Agent.ListLogs(ctx, "agent-uuid", synapse.ListAgentLogsParams{
    ConversationUUID: "conv-uuid",
    Page:             1,
    Size:             20,
})
for _, log := range resp.Logs {
    fmt.Println(log.Category, log.Summary)
    fmt.Println("tokens:", log.Tokens.Prompt, "/", log.Tokens.Completion)
    fmt.Println("resultado tool:", log.ToolResult)
    fmt.Println("api response:", log.APIResponse)
    fmt.Println("rag chunks:", log.Rag)
}
AgentLogItem (v0.0.41+)
Campo Tipo Descrição
UUID string Identidade do log
TenantUUID string Tenant dono do evento
AgentUUID / AgentName string Agente que gerou o evento
Level string info | warn | error
Category string chat | tool_call | rag | error | file_process
Summary string Resumo humano (mesmo formato do WS)
Detail any Detalhe por categoria (previews — o truncamento é regra só deste campo)
Reasoning *string Texto de raciocínio estendido do modelo (extraído do detail)
ToolName *string (tool_call) nome da ferramenta
ToolParams any (tool_call) parâmetros
ToolSuccess *bool (tool_call) sucesso
ToolSummary *string (tool_call) resumo truncado (legado)
ToolResult string (tool_call) resultado íntegro — igual ao WS
APIResponse string (tool_call) corpo da resposta da API externa íntegro — igual ao WS
Rag any (rag) {chunks_found, error?, chunks[]} com textos completos — igual ao WS
DurationMs *int Duração da operação
Model *string Modelo que atendeu o turno
TokensUsed int Total de tokens
PromptTokens int Tokens de entrada (prompt)
CompletionTokens int Tokens de saída (completion)
EmbeddingTokens int Tokens de embedding (RAG)
Tokens *AgentEventTokens Objeto agregado {prompt, completion, total, embedding} — igual ao WS
CreatedAt string Timestamp ISO 8601

Histórico (REST) vs tempo-real (WS): ambos agora têm a mesma estrutura de campos (ToolResult, APIResponse, Rag, Tokens). A diferença é que o WS entrega os eventos no momento em que ocorrem (push), enquanto o REST é o histórico persistido (pull). Use o WS para monitoramento em tempo real e o REST para auditoria/filtro/relatórios.

AgentLogStats
stats, err := client.Agent.LogsStats(ctx, "agent-uuid", synapse.ListAgentLogsParams{
    ExternalID: "protocolo-123",
})
fmt.Println("chamadas:", stats.TotalCalls)
fmt.Println("tokens (prompt):", stats.TotalPromptTokens)
fmt.Println("tokens (completion):", stats.TotalCompletionTokens)
Campo Tipo Descrição
TotalCalls int64 Total de turnos do agente
TotalErrors int64 Erros
TotalTokens int64 Soma de todos os tokens
TotalPromptTokens int64 Tokens de entrada
TotalCompletionTokens int64 Tokens de saída
TotalEmbeddingTokens int64 Tokens de embedding
AvgDurationMs float64 Duração média dos turnos
ByModel []AgentLogModelStat Agregado por modelo
ByConversation []AgentLogConvStat Agregado por conversa

Tratamento de erros

Verificar tipo de erro com sentinels

Use errors.Is para identificar a categoria do erro sem precisar inspecionar o payload:

resp, err := client.Auth.Login(ctx, req)
if err != nil {
    switch {
    case errors.Is(err, synapse.ErrUnauthorized):
        // 401 — credenciais inválidas ou token expirado
    case errors.Is(err, synapse.ErrForbidden):
        // 403 — sem permissão para este recurso
    case errors.Is(err, synapse.ErrNotFound):
        // 404 — recurso não encontrado
    case errors.Is(err, synapse.ErrConflict):
        // 409 — duplicidade (ex: email já em uso)
    case errors.Is(err, synapse.ErrBadRequest):
        // 400 — parâmetros inválidos
    case errors.Is(err, synapse.ErrBadGateway):
        // 502 — erro no provedor externo (OpenAI, Google…)
    case errors.Is(err, synapse.ErrInternalServer):
        // 500 — erro interno da API
    default:
        // erro de rede, timeout, etc.
    }
}
Inspecionar payload completo da API

Use synapse.AsAPIError quando precisar dos detalhes (trace_id, causes):

if apiErr, ok := synapse.AsAPIError(err); ok {
    fmt.Println("HTTP status:", apiErr.StatusCode)
    fmt.Println("Trace ID:",    apiErr.TraceID)
    fmt.Println("Mensagem:",    apiErr.Message)

    for _, cause := range apiErr.Causes {
        fmt.Printf("  campo %q: %s\n", cause.Field, cause.Message)
    }
}
Sentinels disponíveis
Sentinel HTTP Quando ocorre
synapse.ErrInvalidToken Token vazio ao criar o client
synapse.ErrUnauthorized 401 Token inválido ou expirado
synapse.ErrForbidden 403 Sem permissão para o recurso
synapse.ErrNotFound 404 Recurso não encontrado
synapse.ErrConflict 409 Duplicidade (email, documento, token…)
synapse.ErrBadRequest 400 Parâmetros inválidos
synapse.ErrInternalServer 500 Erro interno da API
synapse.ErrBadGateway 502 Falha no provedor externo
synapse.ErrIntegrationNotConfigured 409 Integração não configurada para o tenant

Exemplo completo

package main

import (
    "context"
    "errors"
    "fmt"
    "log"
    "os"
    "time"

    "github.com/WonitTecnologia/synapse"
)

func main() {
    client, err := synapse.NewClient(os.Getenv("SYNAPSE_TOKEN"), &synapse.Options{
        Timeout: 20 * time.Second,
    })
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()

    // Validar token
    me, err := client.Auth.Healthcheck(ctx)
    if err != nil {
        if errors.Is(err, synapse.ErrUnauthorized) {
            log.Fatal("token inválido ou expirado")
        }
        log.Fatal(err)
    }
    fmt.Printf("Logado como: %s (%s)\n", me.User.Name, me.User.Role)

    // Transcrever um áudio
    audio, _ := os.ReadFile("reuniao.mp3")
    transcription, err := client.OpenAI.TranscribeAudio(ctx, synapse.TranscribeAudioRequest{
        FileName: "reuniao.mp3",
        Content:  audio,
        Model:    "whisper-1",
        Language: "pt",
    })
    if err != nil {
        if apiErr, ok := synapse.AsAPIError(err); ok {
            log.Fatalf("erro da API [trace=%s]: %s", apiErr.TraceID, apiErr.Message)
        }
        log.Fatal(err)
    }
    fmt.Println("Transcrição:", transcription.Response)
}

Documentation

Index

Constants

View Source
const (
	EventCategoryChat        = "chat"
	EventCategoryToolCall    = "tool_call"
	EventCategoryRAG         = "rag"
	EventCategoryError       = "error"
	EventCategoryFileProcess = "file_process"
	// EventCategoryToolAgent is one execution of an internal verification agent
	// (response judge, parameter judge, API artifact executor). Detail carries
	// tool_agent ("judge" | "param_judge" | "api_artifact"), status, findings
	// and the execution's token usage; Tokens mirrors that usage for transport.
	EventCategoryToolAgent = "tool_agent"
)

Agent event categories delivered by the monitor stream.

Variables

View Source
var (
	ErrInvalidToken             = errors.New("synapse: token cannot be empty")
	ErrUnauthorized             = errors.New("synapse: unauthorized — invalid or missing token")
	ErrForbidden                = errors.New("synapse: forbidden — insufficient permissions")
	ErrNotFound                 = errors.New("synapse: resource not found")
	ErrConflict                 = errors.New("synapse: conflict — resource already exists or duplicate")
	ErrBadRequest               = errors.New("synapse: bad request — invalid parameters")
	ErrInternalServer           = errors.New("synapse: internal server error")
	ErrBadGateway               = errors.New("synapse: bad gateway — upstream provider error")
	ErrIntegrationNotConfigured = errors.New("synapse: integration not configured for this tenant")
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status returned by the API.
	StatusCode int `json:"-"`

	// Code mirrors the numeric code in the response body.
	Code int `json:"code"`

	// Err is the short error label from the response body.
	Err string `json:"error"`

	// Message is the human-readable description from the response body.
	Message string `json:"message"`

	// TraceID is the trace identifier returned by the API for debugging.
	TraceID string `json:"trace_id"`

	// Causes holds field-level validation errors when applicable.
	Causes []RestErrCause `json:"causes"`
}

APIError represents an error response from the Synapse API. It carries the full response payload and wraps a typed sentinel error so callers can use errors.Is for control flow.

Example:

_, err := client.Auth.Login(ctx, req)
if errors.Is(err, synapse.ErrUnauthorized) { ... }

if apiErr, ok := synapse.AsAPIError(err); ok {
    fmt.Println(apiErr.TraceID, apiErr.Causes)
}

func AsAPIError

func AsAPIError(err error) (*APIError, bool)

AsAPIError unwraps err into *APIError and reports whether it succeeded. Use this to inspect the full API error payload (causes, trace_id, etc.).

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap maps the HTTP status code to the appropriate sentinel error, enabling errors.Is checks against the package-level sentinels.

type ActivityItem added in v0.0.20

type ActivityItem struct {
	Date               string  `json:"date"`
	Model              string  `json:"model"`
	ProviderName       string  `json:"provider_name"`
	Usage              float64 `json:"usage"`
	Requests           int     `json:"requests"`
	PromptTokens       int     `json:"prompt_tokens"`
	CompletionTokens   int     `json:"completion_tokens"`
	ReasoningTokens    int     `json:"reasoning_tokens"`
	ByokUsageInference float64 `json:"byok_usage_inference"`
}

type AgentCase added in v0.0.6

type AgentCase interface {
	// Create registers a new AI agent.
	// SYSTEM_ADMIN must set req.TenantUUID; other roles use the tenant from the token.
	Create(ctx context.Context, req CreateAgentRequest) (*AgentResponse, error)

	// Get returns an agent by its UUID.
	// SYSTEM_ADMIN can fetch agents from any tenant.
	Get(ctx context.Context, agentUUID string) (*AgentResponse, error)

	// List returns a paginated list of agents.
	// SYSTEM_ADMIN lists agents from all tenants; other roles are scoped to their own tenant.
	// Use page=0 and size=0 to rely on server defaults.
	List(ctx context.Context, page, size int) (*ListAgentsResponse, error)

	// Update replaces all mutable fields of an agent (PUT semantics).
	// SYSTEM_ADMIN can update agents from any tenant.
	Update(ctx context.Context, agentUUID string, req UpdateAgentRequest) (*AgentResponse, error)

	// Patch updates a single field of an agent (PATCH semantics).
	// Set exactly one field in req; the server rejects requests with 0 or more than 1 field.
	// SYSTEM_ADMIN can patch agents from any tenant.
	Patch(ctx context.Context, agentUUID string, req UpdateAgentRequest) (*AgentResponse, error)

	// Delete permanently removes an agent and all its conversations.
	// SYSTEM_ADMIN can delete agents from any tenant.
	Delete(ctx context.Context, agentUUID string) error

	// Duplicate creates a full copy of an agent under a new name: configuration,
	// collections, MCP integrations, external API links, prompt versions (with
	// the active one re-pointed) and API artifacts. The copy is created in the
	// same tenant as the source agent. Duplicated name returns 409.
	Duplicate(ctx context.Context, agentUUID string, req DuplicateAgentRequest) (*AgentResponse, error)

	// Chat sends a message to an agent and returns the response.
	// Omit req.ConversationUUID to start a new conversation; the returned
	// ChatResponse.ConversationUUID can be passed in subsequent calls to maintain context.
	// req.ConversationUUID also accepts any client-defined identifier instead of a UUID
	// (e.g. "2024123ABCabc"): the backend generates and links a UUID to it on the first
	// call, scoped by tenant + agent, and reuses the same conversation on later calls with
	// the same identifier — see ChatRequest.ConversationUUID for details.
	// SYSTEM_ADMIN can chat with agents from any tenant.
	Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error)

	// Dispatch enqueues an agent turn for asynchronous, durable processing and
	// returns immediately (202) with a job id. The heavy work (RAG + LLM + tools)
	// runs in a dedicated worker and survives restarts; the final reply is
	// delivered later via the PABX central MCP tool. Use req.WebhookID / Destino /
	// TriggerFileID to carry the delivery data. Prefer this over Chat when the
	// caller must not block on processing (e.g. PABX message flows).
	Dispatch(ctx context.Context, req DispatchRequest) (*DispatchResponse, error)

	// ListConversations returns a paginated list of conversation summaries.
	// SYSTEM_ADMIN lists conversations from all tenants; other roles are scoped to their own tenant.
	// Use params.AgentUUID to filter by a specific agent.
	ListConversations(ctx context.Context, params ListConversationsParams) (*ListConversationsResponse, error)

	// ListPrompts returns a paginated list of versioned prompts saved for an agent.
	// The IsActive field in each response indicates which prompt is currently active.
	ListPrompts(ctx context.Context, agentUUID string, page, size int) (*ListAgentPromptsResponse, error)

	// GetPrompt returns a single versioned prompt by its UUID.
	GetPrompt(ctx context.Context, agentUUID, promptUUID string) (*AgentPromptResponse, error)

	// CreatePrompt saves a new versioned prompt for an agent.
	// Multiple prompts with the same name are allowed; each is versioned by creation date.
	CreatePrompt(ctx context.Context, agentUUID string, req CreateAgentPromptRequest) (*AgentPromptResponse, error)

	// UpdatePrompt updates the name and/or content of a saved prompt.
	// If the prompt is currently active, the agent's prompt content is synced automatically.
	UpdatePrompt(ctx context.Context, agentUUID, promptUUID string, req UpdateAgentPromptRequest) (*AgentPromptResponse, error)

	// DeletePrompt permanently removes a saved prompt.
	// If the deleted prompt was the active one, the agent will have no active prompt (active_prompt_uuid = null).
	DeletePrompt(ctx context.Context, agentUUID, promptUUID string) error

	// ActivatePrompt sets a saved prompt as the active prompt for the agent.
	// The agent's prompt content is updated immediately to reflect the selected version.
	ActivatePrompt(ctx context.Context, agentUUID, promptUUID string) error

	// DeactivatePrompt removes the active prompt link from the agent (active_prompt_uuid = null).
	DeactivatePrompt(ctx context.Context, agentUUID string) error

	// ListLogs returns execution logs for an agent, filterable by conversation UUID or external ID.
	ListLogs(ctx context.Context, agentUUID string, params ListAgentLogsParams) (*ListAgentLogsResponse, error)

	// LogsStats returns aggregated token usage statistics for an agent, grouped by model and
	// conversation. Optionally filter by conversation UUID or external ID.
	LogsStats(ctx context.Context, agentUUID string, params ListAgentLogsParams) (*AgentLogStats, error)

	// SearchThoughts returns the thoughts (working memory) stored by the agent during a
	// conversation. conversationUUID is required; query filters by keyword in content/label
	// (case-insensitive, empty returns all). The thoughts are Redis-backed, per-conversation,
	// and expire after TTL (default 24h of inactivity).
	SearchThoughts(ctx context.Context, agentUUID string, params ThoughtSearchParams) (*ThoughtSearchResponse, error)

	GetCredits(ctx context.Context) (*WorkspaceCredits, error)
	GetActivity(ctx context.Context) ([]ActivityItem, error)
	GetActivityWithDate(ctx context.Context, date string) ([]ActivityItem, error)
	GetKeyInfo(ctx context.Context) (*KeyInfo, error)
}

AgentCase provides CRUD, chat and conversation operations for AI agents.

type AgentEvent added in v0.0.39

type AgentEvent struct {
	UUID                   string            `json:"uuid"`
	TenantUUID             string            `json:"tenant_uuid"`
	AgentUUID              string            `json:"agent_uuid"`
	AgentName              string            `json:"agent_name"`
	ConversationUUID       *string           `json:"conversation_uuid,omitempty"`
	ConversationExternalID *string           `json:"conversation_external_id,omitempty"`
	Level                  string            `json:"level"`
	Category               string            `json:"category"`
	Summary                string            `json:"summary"`
	Detail                 map[string]any    `json:"detail,omitempty"`
	ToolName               *string           `json:"tool_name,omitempty"`
	ToolParams             map[string]any    `json:"tool_params,omitempty"`
	ToolSuccess            *bool             `json:"tool_success,omitempty"`
	ToolResult             string            `json:"tool_result,omitempty"`
	APIResponse            string            `json:"api_response,omitempty"`
	Rag                    *AgentEventRag    `json:"rag,omitempty"`
	DurationMs             *int              `json:"duration_ms,omitempty"`
	Model                  *string           `json:"model,omitempty"`
	Tokens                 *AgentEventTokens `json:"tokens,omitempty"`
	CreatedAt              time.Time         `json:"created_at"`
}

AgentEvent is a real-time agent execution event. Unlike the persisted agent log, tool parameters, tool results and API responses are NOT truncated.

type AgentEventRag added in v0.0.39

type AgentEventRag struct {
	ChunksFound int                  `json:"chunks_found"`
	Error       string               `json:"error,omitempty"`
	Chunks      []AgentEventRagChunk `json:"chunks,omitempty"`
}

AgentEventRag aggregates the RAG stage outcome of a turn.

type AgentEventRagChunk added in v0.0.39

type AgentEventRagChunk struct {
	Filename   string  `json:"filename"`
	ChunkIndex int     `json:"chunk_index"`
	Score      float32 `json:"score"`
	ScorePct   float32 `json:"score_pct"`
	Text       string  `json:"text,omitempty"`
}

AgentEventRagChunk is one retrieved RAG chunk with its source file and similarity percentage.

type AgentEventTokens added in v0.0.39

type AgentEventTokens struct {
	Prompt     int `json:"prompt"`
	Completion int `json:"completion"`
	Total      int `json:"total"`
	Embedding  int `json:"embedding"`
}

AgentEventTokens aggregates the token usage of a turn.

type AgentLogConvStat added in v0.0.19

type AgentLogConvStat struct {
	ConversationUUID       *string `json:"conversation_uuid,omitempty"`
	ConversationExternalID *string `json:"conversation_external_id,omitempty"`
	Calls                  int64   `json:"calls"`
	TotalTokens            int64   `json:"total_tokens"`
}

AgentLogConvStat holds per-conversation token usage.

type AgentLogItem added in v0.0.17

type AgentLogItem struct {
	UUID                   string  `json:"uuid"`
	TenantUUID             string  `json:"tenant_uuid"`
	AgentUUID              string  `json:"agent_uuid"`
	AgentName              string  `json:"agent_name"`
	ConversationUUID       *string `json:"conversation_uuid,omitempty"`
	ConversationExternalID *string `json:"conversation_external_id,omitempty"`
	Level                  string  `json:"level"`
	Category               string  `json:"category"`
	Summary                string  `json:"summary"`
	Detail                 any     `json:"detail,omitempty"`
	// Reasoning is the model's extended-thinking text for a "chat" log entry,
	// when the model exposes it. Useful for analyzing why the agent answered or
	// acted a certain way. Also available inside Detail (key "reasoning").
	Reasoning        *string           `json:"reasoning,omitempty"`
	ToolName         *string           `json:"tool_name,omitempty"`
	ToolParams       any               `json:"tool_params,omitempty"`
	ToolSuccess      *bool             `json:"tool_success,omitempty"`
	ToolSummary      *string           `json:"tool_summary,omitempty"`
	ToolResult       string            `json:"tool_result,omitempty"`
	APIResponse      string            `json:"api_response,omitempty"`
	Rag              any               `json:"rag,omitempty"`
	DurationMs       *int              `json:"duration_ms,omitempty"`
	Model            *string           `json:"model,omitempty"`
	TokensUsed       int               `json:"tokens_used"`
	PromptTokens     int               `json:"prompt_tokens"`
	CompletionTokens int               `json:"completion_tokens"`
	EmbeddingTokens  int               `json:"embedding_tokens"`
	Tokens           *AgentEventTokens `json:"tokens,omitempty"`
	CreatedAt        string            `json:"created_at"`
}

AgentLogItem represents a single agent execution log entry.

type AgentLogModelStat added in v0.0.19

type AgentLogModelStat struct {
	Model               string  `json:"model"`
	Calls               int64   `json:"calls"`
	TotalTokens         int64   `json:"total_tokens"`
	AvgDurationMs       float64 `json:"avg_duration_ms"`
	AvgPromptTokens     float64 `json:"avg_prompt_tokens"`
	AvgCompletionTokens float64 `json:"avg_completion_tokens"`
	AvgEmbeddingTokens  float64 `json:"avg_embedding_tokens"`
}

AgentLogModelStat holds per-model usage statistics.

type AgentLogStats added in v0.0.19

type AgentLogStats struct {
	AgentUUID             string              `json:"agent_uuid"`
	AgentName             string              `json:"agent_name"`
	TotalCalls            int64               `json:"total_calls"`
	TotalErrors           int64               `json:"total_errors"`
	TotalTokens           int64               `json:"total_tokens"`
	TotalPromptTokens     int64               `json:"total_prompt_tokens"`
	TotalCompletionTokens int64               `json:"total_completion_tokens"`
	TotalEmbeddingTokens  int64               `json:"total_embedding_tokens"`
	AvgDurationMs         float64             `json:"avg_duration_ms"`
	ByModel               []AgentLogModelStat `json:"by_model"`
	ByConversation        []AgentLogConvStat  `json:"by_conversation"`
}

AgentLogStats holds aggregated statistics for agent usage.

type AgentPromptResponse added in v0.0.11

type AgentPromptResponse struct {
	UUID       string `json:"uuid"`
	AgentUUID  string `json:"agent_uuid"`
	TenantUUID string `json:"tenant_uuid"`
	Name       string `json:"name"`
	Prompt     string `json:"prompt"`
	// IsActive reports whether this prompt is currently set as the agent's active prompt.
	IsActive  bool   `json:"is_active"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

AgentPromptResponse describes a versioned prompt saved for an agent.

type AgentResponse added in v0.0.6

type AgentResponse struct {
	UUID                string   `json:"uuid"`
	TenantUUID          string   `json:"tenant_uuid"`
	Name                string   `json:"name"`
	Description         string   `json:"description"`
	Model               string   `json:"model"`
	Prompt              string   `json:"prompt"`
	CollectionUUIDs     []string `json:"collection_uuids"`
	QueryEmbedModel     string   `json:"query_embed_model,omitempty"`
	MaxContext          int      `json:"max_context"`
	Temperature         float64  `json:"temperature"`
	Active              bool     `json:"active"`
	McpEnabled          bool     `json:"mcp_enabled"`
	McpIntegrationUUIDs []string `json:"mcp_integration_uuids"`
	McpDisabledTools    []string `json:"mcp_disabled_tools"`
	ApiToolsEnabled     bool     `json:"api_tools_enabled"`
	ApiToolUUIDs        []string `json:"api_tool_uuids"`
	ThoughtsEnabled     bool     `json:"thoughts_enabled"`
	ApiArtifactsEnabled bool     `json:"api_artifacts_enabled"`
	ActivePromptUUID    string   `json:"active_prompt_uuid,omitempty"`
	AcceptFiles         bool     `json:"accept_files"`
	FileModel           string   `json:"file_model,omitempty"`
	TextModel           string   `json:"text_model,omitempty"`
	ImageModel          string   `json:"image_model,omitempty"`
	AudioModel          string   `json:"audio_model,omitempty"`
	TextFallbackModel   string   `json:"text_fallback_model,omitempty"`
	ImageFallbackModel  string   `json:"image_fallback_model,omitempty"`
	AudioFallbackModel  string   `json:"audio_fallback_model,omitempty"`
	CreatedAt           string   `json:"created_at"`
	UpdatedAt           string   `json:"updated_at"`
}

AgentResponse describes an AI agent.

type AnalyzeImageFromURLRequest added in v0.0.5

type AnalyzeImageFromURLRequest struct {
	FileURL string `json:"file_url"`
	Prompt  string `json:"prompt"`
}

AnalyzeImageFromURLRequest is the body for analysing an image that the server fetches from a download URL (OpenAI image analysis).

type AnalyzeImageResponse

type AnalyzeImageResponse struct {
	Response string `json:"response"`
}

AnalyzeImageResponse is returned by both OpenAI and Google Vision image endpoints.

type ApiArtifactCase added in v0.0.57

type ApiArtifactCase interface {
	// List returns all artifacts of an agent.
	List(ctx context.Context, agentUUID string) (*ApiArtifactListResponse, error)
	Create(ctx context.Context, agentUUID string, req CreateApiArtifactRequest) (*ApiArtifactResponse, error)
	Update(ctx context.Context, agentUUID, artifactUUID string, req UpdateApiArtifactRequest) (*ApiArtifactResponse, error)
	// Toggle flips the is_active state of an artifact.
	Toggle(ctx context.Context, agentUUID, artifactUUID string) (*ApiArtifactResponse, error)
	Delete(ctx context.Context, agentUUID, artifactUUID string) error
	// Cache returns the cached step results of the agent's artifacts within a
	// conversation (the executor's memory) — audit view for monitoring.
	Cache(ctx context.Context, agentUUID, conversationUUID string) (*ArtifactCacheResponse, error)
}

ApiArtifactCase manages API Artifacts — per-agent pipelines of chained external API tools. Each active artifact becomes ONE tool for the main agent (artefato_<name>), executed by an internal agent that resolves the step parameters (declarative mappings + conversation) and caches every step's return in Redis per conversation. Requires the agent flag api_artifacts_enabled; with the flag off, API tools behave exactly as before.

type ApiArtifactListResponse added in v0.0.57

type ApiArtifactListResponse struct {
	Artifacts []ApiArtifactResponse `json:"artifacts"`
	Total     int                   `json:"total"`
}

ApiArtifactListResponse lists the artifacts of an agent.

type ApiArtifactResponse added in v0.0.57

type ApiArtifactResponse struct {
	UUID        string `json:"uuid"`
	TenantUUID  string `json:"tenant_uuid"`
	AgentUUID   string `json:"agent_uuid"`
	Name        string `json:"name"`
	Description string `json:"description"`
	// Prompt instructs the internal executor agent on how to follow the flow.
	Prompt string `json:"prompt"`
	// FlowData is the graph JSON: {"nodes":[{id, api_tool_uuid, position, data:{label,
	// prompt, mappings:[{param, from:{node_id, path}}]}}], "connections":[{source, target}]}.
	FlowData  json.RawMessage `json:"flow_data"`
	IsActive  bool            `json:"is_active"`
	NodeCount int             `json:"node_count"`
	CreatedAt string          `json:"created_at"`
	UpdatedAt string          `json:"updated_at"`
}

ApiArtifactResponse describes an API Artifact: a per-agent pipeline of chained external API tools. The tenant draws a graph (nodes = the agent's API tools, connections = dependencies) with an executor prompt and a per-node prompt; in chat, each active artifact becomes ONE tool (artefato_<name>) run by an internal executor agent that caches every step's return in Redis per conversation. Requires the agent flag api_artifacts_enabled.

type ApiTokenCreateRequest

type ApiTokenCreateRequest struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	// ExpireAt is optional; if omitted the server sets a default expiry.
	ExpireAt string `json:"expire_at,omitempty"`
}

ApiTokenCreateRequest is the body for creating an API token.

type ApiTokenCreateResponse

type ApiTokenCreateResponse struct {
	UUID        string `json:"uuid"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Token       string `json:"token"`
	TenantUUID  string `json:"tenant_uuid"`
	UserUUID    string `json:"user_uuid"`
	ExpireAt    string `json:"expire_at"`
	CreatedAt   string `json:"create_at"`
}

ApiTokenCreateResponse describes a created or listed API token.

type ArtifactCacheEntry added in v0.0.57

type ArtifactCacheEntry struct {
	ArtifactUUID string         `json:"artifact_uuid"`
	NodeID       string         `json:"node_id"`
	Label        string         `json:"label"`
	ToolName     string         `json:"tool_name"`
	Params       map[string]any `json:"params"`
	Response     string         `json:"response"`
	StatusCode   int            `json:"status_code"`
	CacheHits    int            `json:"cache_hits"`
	ExecutedAt   string         `json:"executed_at"`
}

ArtifactCacheEntry is one cached step result of an artifact in a conversation (the executor's memory, kept in Redis with a 24h TTL renewed on access).

type ArtifactCacheResponse added in v0.0.57

type ArtifactCacheResponse struct {
	Entries []ArtifactCacheEntry `json:"entries"`
	Total   int                  `json:"total"`
}

ArtifactCacheResponse lists the cached artifact steps of a conversation.

type AuthCase

type AuthCase interface {
	// Login authenticates a user with email and password and returns an access token.
	Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)

	// Logout revokes the given access token.
	Logout(ctx context.Context, token string) error

	// Healthcheck validates the current token and returns the logged-in user's data.
	Healthcheck(ctx context.Context) (*LoginResponse, error)

	// RequestOTP sends a one-time password to the given email address.
	RequestOTP(ctx context.Context, req OTPRequest) error

	// ResetPassword validates the OTP and replaces the user's password.
	ResetPassword(ctx context.Context, req OTPResetPasswordRequest) error

	// ListAPITokens returns all API tokens linked to the authenticated user.
	// Use page=0 and pageSize=0 to rely on server defaults.
	ListAPITokens(ctx context.Context, page, pageSize int) (*ListApiTokensResponse, error)

	// CreateAPIToken creates a new API token for the authenticated user.
	CreateAPIToken(ctx context.Context, req ApiTokenCreateRequest) (*ApiTokenCreateResponse, error)
}

AuthCase provides all authentication-related operations against the Synapse API.

type ChatAttachment added in v0.0.27

type ChatAttachment struct {
	URL      string `json:"url"`
	Type     string `json:"type"` // "image", "audio", "document"
	MimeType string `json:"mime_type,omitempty"`
	FileName string `json:"file_name,omitempty"`
}

ChatAttachment carries a file/media to be analysed by an agent that accepts attachments.

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Prompt string `json:"prompt"`
}

ChatCompletionRequest is the body for a chat completion call.

type ChatCompletionResponse

type ChatCompletionResponse struct {
	Response string `json:"response"`
}

ChatCompletionResponse is the response from a chat completion call.

type ChatRagInfo added in v0.0.6

type ChatRagInfo struct {
	Enabled     bool   `json:"enabled"`
	ChunksFound int    `json:"chunks_found"`
	Error       string `json:"error,omitempty"`
}

ChatRagInfo reports what happened during the semantic search step.

type ChatReference added in v0.0.6

type ChatReference struct {
	Filename   string  `json:"filename"`
	ChunkIndex int     `json:"chunk_index"`
	Score      float32 `json:"score"`
	ScorePct   float32 `json:"score_pct"`
	Text       string  `json:"text"`
}

ChatReference is a document chunk retrieved from Qdrant and used in the RAG context.

type ChatRequest added in v0.0.6

type ChatRequest struct {
	AgentUUID string `json:"agent_uuid"`
	// Message is the user's text. It is OPTIONAL when Attachment is set: an image
	// or audio may arrive with no caption — in that case leave Message empty and
	// the agent processes the media alone. When the media HAS a caption, put the
	// real caption here (it is sent alongside the media). The backend requires
	// either a non-empty Message or an attachment the agent can process.
	Message string `json:"message"`
	// ConversationUUID continues an existing conversation; omit to start a new one.
	// It accepts two formats:
	//   - a conversation UUID returned by a previous Chat call: continues that conversation;
	//   - any client-defined identifier (e.g. "2024123ABCabc"): the backend generates a UUID
	//     on the first call and links that identifier to it (scoped by tenant + agent).
	//     Subsequent calls with the same identifier reuse the same conversation, and the
	//     same identifier from a different tenant resolves to a different conversation.
	ConversationUUID *string `json:"conversation_uuid,omitempty"`
	// Context carries free-text metadata from the calling system (e.g. PABX). Format is
	// implementation-defined — e.g. "tenant_uuid:x,protocol_uuid:y". When present, the agent
	// runtime injects this into MCP tool parameters.
	Context *string `json:"context,omitempty"`
	// Attachment carries a file or media URL for agents that accept attachments.
	// The Synapse downloads the file from this URL and processes it according to the type.
	Attachment *ChatAttachment `json:"attachment,omitempty"`
}

ChatRequest is the body for sending a message to an AI agent.

type ChatResponse added in v0.0.6

type ChatResponse struct {
	ConversationUUID string          `json:"conversation_uuid"`
	Message          string          `json:"message"`
	AgentName        string          `json:"agent_name,omitempty"` // nome vivo do agente que processou
	References       []ChatReference `json:"references"`
	Rag              ChatRagInfo     `json:"rag"`
}

ChatResponse is the reply from the AI agent.

type ChatvoltAgentItem added in v0.0.4

type ChatvoltAgentItem struct {
	ID          string                  `json:"id"`
	Name        string                  `json:"name"`
	IconUrl     *string                 `json:"iconUrl,omitempty"`
	Description string                  `json:"description"`
	ModelName   string                  `json:"modelName"`
	Visibility  ChatvoltAgentVisibility `json:"visibility"`
}

ChatvoltAgentItem describes a single Chatvolt agent returned by the catalog.

type ChatvoltAgentQueryRequest

type ChatvoltAgentQueryRequest struct {
	AgentID string `json:"agentId"`
	Query   string `json:"query"`
	// ConversationID keeps context across turns; omit to start a new conversation.
	ConversationID string `json:"conversationId,omitempty"`
	// Streaming should generally be false for synchronous responses.
	Streaming bool             `json:"streaming"`
	Contact   *ChatvoltContact `json:"contact,omitempty"`
}

ChatvoltAgentQueryRequest is the body for querying a Chatvolt agent.

type ChatvoltAgentQueryResponse

type ChatvoltAgentQueryResponse struct {
	Answer         string      `json:"answer"`
	ConversationID string      `json:"conversationId"`
	MessageID      string      `json:"messageId"`
	VisitorID      string      `json:"visitorId"`
	Sources        interface{} `json:"sources"`
	Metadata       interface{} `json:"metadata"`
}

ChatvoltAgentQueryResponse is the response from a Chatvolt agent query.

type ChatvoltAgentVisibility added in v0.0.4

type ChatvoltAgentVisibility string

ChatvoltAgentVisibility indicates whether a Chatvolt agent is publicly accessible.

const (
	ChatvoltAgentVisibilityPublic  ChatvoltAgentVisibility = "public"
	ChatvoltAgentVisibilityPrivate ChatvoltAgentVisibility = "private"
)

type ChatvoltCase

type ChatvoltCase interface {
	// Configure creates or updates the Chatvolt integration credentials
	// for the authenticated tenant.
	Configure(ctx context.Context, req ConfigureChatvoltRequest) error

	// Query sends a message to a Chatvolt agent and returns its response.
	// Set req.ConversationID to continue an existing conversation thread.
	Query(ctx context.Context, req ChatvoltAgentQueryRequest) (*ChatvoltAgentQueryResponse, error)

	// ListAgents returns all Chatvolt agents available for the authenticated tenant.
	ListAgents(ctx context.Context) (*ListChatvoltAgentsResponse, error)
}

ChatvoltCase provides operations for the Chatvolt agent integration.

type ChatvoltContact

type ChatvoltContact struct {
	UserID      string `json:"userId,omitempty"`
	Email       string `json:"email,omitempty"`
	FirstName   string `json:"firstName,omitempty"`
	LastName    string `json:"lastName,omitempty"`
	PhoneNumber string `json:"phoneNumber,omitempty"`
}

ChatvoltContact carries optional contact metadata attached to a Chatvolt query.

type ChatvoltCredentialsDTO

type ChatvoltCredentialsDTO struct {
	Token string `json:"token"`
}

ChatvoltCredentialsDTO holds the API key for the Chatvolt integration.

type Client

type Client struct {
	// Auth covers login, logout, OTP, password reset, and API token management.
	Auth AuthCase

	// User covers user CRUD operations.
	User UserCase

	// Tenant covers tenant CRUD operations.
	Tenant TenantCase

	// Provider covers read operations for catalog integration providers.
	Provider ProviderCase

	// Service covers read operations for catalog integration services.
	Service ServiceCase

	// Google covers the Google Vision AI integration (configure + OCR).
	Google GoogleCase

	// OpenAI covers the OpenAI integration (configure, chat, image analysis, transcription).
	OpenAI OpenAICase

	// Chatvolt covers the Chatvolt agent integration (configure, query, list agents).
	Chatvolt ChatvoltCase

	// OpenRouter covers the OpenRouter integration (workspace sync/desync, model listing, analytics).
	OpenRouter OpenRouterCase

	// Collection covers Qdrant vector collection CRUD for the knowledge base.
	Collection CollectionCase

	// Document covers document upload and vectorization for the knowledge base.
	Document DocumentCase

	// Agent covers AI agent CRUD operations and chat (including RAG).
	Agent AgentCase

	// Mcp covers MCP (Model Context Protocol) server integration management.
	Mcp McpCase

	// ExternalApi covers external API tool management (raw HTTP APIs as agent tools).
	ExternalApi ExternalApiCase

	// ApiArtifact covers API Artifacts — per-agent pipelines of chained external
	// API tools with per-step prompts and a per-conversation Redis cache.
	ApiArtifact ApiArtifactCase

	// Monitor covers the real-time agent event WebSocket (receive-only stream
	// of chat, tool_call/MCP, RAG and error events for monitoring).
	Monitor MonitorCase

	// Status covers the service status endpoint (build, pod, dependency
	// health, token validity and processing time).
	Status StatusCase

	// Dispatch covers the queue observability endpoints (worker status, pending
	// jobs, stream metrics).
	Dispatch DispatchCase
}

Client is the top-level Synapse SDK entry point. Each field exposes a domain-specific interface covering a group of API endpoints.

Usage:

client, err := synapse.NewClient("your-token", nil)

// Auth
resp, err := client.Auth.Login(ctx, synapse.LoginRequest{...})

// Tenant
tenant, err := client.Tenant.Get(ctx, "uuid", "")

// Google Vision
err = client.Google.Configure(ctx, synapse.ConfigureGoogleRequest{...})
ocr, err := client.Google.VisionOCR(ctx, "photo.jpg", imageBytes)

// OpenAI
reply, err := client.OpenAI.Chat(ctx, synapse.ChatCompletionRequest{Prompt: "Hello!"})

// Chatvolt
answer, err := client.Chatvolt.Query(ctx, synapse.ChatvoltAgentQueryRequest{...})

// OpenRouter
sync, err := client.OpenRouter.Sync(ctx, synapse.OpenRouterSyncRequest{})
models, err := client.OpenRouter.ListModels(ctx, false)

// Knowledge
col, err := client.Collection.Create(ctx, synapse.CreateCollectionRequest{Name: "docs", VectorSize: 1536})
doc, err := client.Document.Upload(ctx, synapse.UploadDocumentRequest{...})

// Agent
agent, err := client.Agent.Create(ctx, synapse.CreateAgentRequest{...})
resp, err := client.Agent.Chat(ctx, synapse.ChatRequest{AgentUUID: "...", Message: "Olá!"})

func NewClient

func NewClient(token string, opts *Options) (*Client, error)

NewClient creates and returns a fully initialised Synapse Client.

token is required and is sent as a Bearer token on every request. Pass an *Options to override the base URL or request timeout; pass nil for defaults.

client, err := synapse.NewClient("sk-...", &synapse.Options{
    BaseURL: "https://staging.synapse.example.com",
    Timeout: 15 * time.Second,
})

type CollectionCase added in v0.0.6

type CollectionCase interface {
	// Create registers a new vector collection for the authenticated tenant.
	Create(ctx context.Context, req CreateCollectionRequest) (*CollectionResponse, error)

	// Get returns a collection by its UUID.
	Get(ctx context.Context, collectionUUID string) (*CollectionResponse, error)

	// List returns a paginated list of collections for the authenticated tenant.
	// Use page=0 and size=0 to rely on server defaults.
	List(ctx context.Context, page, size int) (*CollectionsResponse, error)

	// Delete permanently removes a collection and its Qdrant data by UUID.
	Delete(ctx context.Context, collectionUUID string) error
}

CollectionCase provides CRUD operations for Qdrant vector collections.

type CollectionResponse added in v0.0.6

type CollectionResponse struct {
	UUID                 string `json:"uuid"`
	TenantUUID           string `json:"tenant_uuid"`
	Name                 string `json:"name"`
	QdrantCollectionName string `json:"qdrant_collection_name"`
	VectorSize           uint64 `json:"vector_size"`
	Distance             string `json:"distance"`
	EmbedModel           string `json:"embed_model"`
	CreatedAt            string `json:"createAt"`
	UpdatedAt            string `json:"updateAt"`
}

CollectionResponse describes a single Qdrant collection registered for a tenant.

type CollectionsResponse added in v0.0.6

type CollectionsResponse struct {
	Collections []CollectionResponse `json:"collections"`
	Page        int                  `json:"page"`
	Size        int                  `json:"size"`
}

CollectionsResponse is the paginated list of collections for a tenant.

type ConfigureChatvoltRequest

type ConfigureChatvoltRequest struct {
	Credentials ChatvoltCredentialsDTO `json:"credentials"`
	IsActive    bool                   `json:"is_active,omitempty"`
}

ConfigureChatvoltRequest is the body for creating/updating the Chatvolt integration.

type ConfigureGoogleRequest

type ConfigureGoogleRequest struct {
	Credentials VisionAICredentialsDTO `json:"credentials"`
	IsActive    bool                   `json:"is_active,omitempty"`
}

ConfigureGoogleRequest is the body for creating/updating the Google Vision integration.

type ConfigureOpenAIRequest

type ConfigureOpenAIRequest struct {
	Credentials OpenAICredentialsDTO `json:"credentials"`
	Settings    OpenAISettingsDTO    `json:"settings"`
	IsActive    bool                 `json:"is_active,omitempty"`
}

ConfigureOpenAIRequest is the body for creating/updating the OpenAI integration.

type ConversationResponse added in v0.0.7

type ConversationResponse struct {
	UUID       string `json:"uuid"`
	TenantUUID string `json:"tenant_uuid"`
	AgentUUID  string `json:"agent_uuid"`
	// ExternalID is the client-defined identifier linked to this conversation, when the
	// conversation was started by passing an arbitrary identifier in ConversationUUID
	// instead of a UUID. Nil for conversations created/continued by UUID.
	ExternalID *string `json:"external_id,omitempty"`
	// MessageCount is the total number of messages (user + assistant turns).
	MessageCount int    `json:"message_count"`
	CreatedAt    string `json:"created_at"`
	UpdatedAt    string `json:"updated_at"`
}

ConversationResponse is a summary of a stored conversation (without full message content).

type CreateAgentPromptRequest added in v0.0.11

type CreateAgentPromptRequest struct {
	Name   string `json:"name"`
	Prompt string `json:"prompt"`
}

CreateAgentPromptRequest is the body for saving a new versioned prompt for an agent.

type CreateAgentRequest added in v0.0.6

type CreateAgentRequest struct {
	// TenantUUID is required when the caller is SYSTEM_ADMIN; ignored for other roles.
	TenantUUID  *string `json:"tenant_uuid,omitempty"`
	Name        string  `json:"name"`
	Description string  `json:"description,omitempty"`
	Model       string  `json:"model"`
	Prompt      string  `json:"prompt"`
	// CollectionUUIDs enables RAG with one or more indexed collections.
	// The embedding model is resolved automatically from the first collection's documents.
	// All collections must use the same embedding model.
	CollectionUUIDs []string `json:"collection_uuids,omitempty"`
	// MaxContext accepted values: 10000, 15000, 20000 (default: 10000).
	MaxContext int `json:"max_context,omitempty"`
	// Temperature controls randomness: 0.0 (deterministic) – 0.7 (max without hallucination).
	Temperature *float64 `json:"temperature,omitempty"`
	McpEnabled  *bool    `json:"mcp_enabled,omitempty"`
	// McpIntegrationUUIDs links the agent to specific MCP server integrations.
	McpIntegrationUUIDs []string `json:"mcp_integration_uuids,omitempty"`
	// McpDisabledTools lists tool names (from the linked integrations) that this agent must not call.
	McpDisabledTools []string `json:"mcp_disabled_tools,omitempty"`
	// ApiToolsEnabled enables external API tools (HTTP) for this agent.
	ApiToolsEnabled *bool `json:"api_tools_enabled,omitempty"`
	// ApiToolUUIDs links the agent to specific external API tools.
	ApiToolUUIDs []string `json:"api_tool_uuids,omitempty"`
	// ThoughtsEnabled enables the agent's working memory ("brain"): the model can store,
	// recall, update and clear thoughts (e.g. an id returned by an API) within a conversation,
	// kept in Redis with a per-conversation TTL.
	ThoughtsEnabled *bool `json:"thoughts_enabled,omitempty"`
	// ApiArtifactsEnabled enables API Artifacts (pipelines of chained external API
	// tools) for this agent. When enabled, each active artifact becomes ONE tool
	// and the APIs that are pipeline nodes stop appearing as individual tools.
	ApiArtifactsEnabled *bool  `json:"api_artifacts_enabled,omitempty"`
	AcceptFiles         *bool  `json:"accept_files,omitempty"`
	FileModel           string `json:"file_model,omitempty"`
	// Per-content-type model overrides. Empty = fall back to Model (the main,
	// textual model). When an image/audio attachment arrives, the turn is routed
	// to the matching model; text-only turns use TextModel when set.
	TextModel  string `json:"text_model,omitempty"`
	ImageModel string `json:"image_model,omitempty"`
	AudioModel string `json:"audio_model,omitempty"`
	// Per-content-type fallback models. Empty = no fallback. Used when the
	// turn's model call fails or when the sanitizer blocks the response even
	// after the retry.
	TextFallbackModel  string `json:"text_fallback_model,omitempty"`
	ImageFallbackModel string `json:"image_fallback_model,omitempty"`
	AudioFallbackModel string `json:"audio_fallback_model,omitempty"`
}

CreateAgentRequest is the body for creating an AI agent.

type CreateApiArtifactRequest added in v0.0.57

type CreateApiArtifactRequest struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Prompt      string          `json:"prompt,omitempty"`
	FlowData    json.RawMessage `json:"flow_data"`
	// IsActive defaults to false — nothing activates on its own.
	IsActive *bool `json:"is_active,omitempty"`
}

CreateApiArtifactRequest is the body for creating an API Artifact. Name must match ^[a-zA-Z0-9_-]{1,64}$ (it becomes the tool artefato_<name>). Every node's api_tool_uuid must reference an API tool linked to the agent and active; the graph must be acyclic and mappings may only read from ancestors.

type CreateCollectionRequest added in v0.0.6

type CreateCollectionRequest struct {
	// TenantUUID is required when the caller is SYSTEM_ADMIN; ignored for other roles.
	TenantUUID *string `json:"tenant_uuid,omitempty"`
	Name       string  `json:"name"`
	// VectorSize is the dimension of the embedding vectors (e.g. 1536 for text-embedding-ada-002).
	// When zero the server uses its default (1536).
	VectorSize uint64 `json:"vector_size,omitempty"`
	// Distance is the similarity metric: "Cosine" (default), "Euclid", or "Dot".
	Distance string `json:"distance,omitempty"`
}

CreateCollectionRequest is the body for creating a Qdrant vector collection.

type CreateExternalApiRequest added in v0.0.32

type CreateExternalApiRequest struct {
	// TenantUUID is required for SYSTEM_ADMIN; omit for TENANT_ADMIN (uses JWT tenant).
	TenantUUID *string `json:"tenant_uuid,omitempty"`
	Name       string  `json:"name"`
	// Description is an internal, human-facing label.
	Description string `json:"description,omitempty"`
	// UsagePrompt is the description the AI reads to decide when to call this tool.
	UsagePrompt string `json:"usage_prompt"`
	// Method is the HTTP method (GET, POST, PUT, PATCH, DELETE).
	Method string `json:"method"`
	// URL may contain {{param}} placeholders (e.g. ".../orders/{{order_id}}").
	URL string `json:"url"`
	// Headers values may contain {{param}} placeholders. May carry secrets.
	Headers map[string]string `json:"headers,omitempty"`
	// BodyTemplate is a JSON body with {{param}} placeholders (POST/PUT/PATCH).
	BodyTemplate string                `json:"body_template,omitempty"`
	Parameters   []ExternalApiParamDef `json:"parameters,omitempty"`
	// EmbedModel condenses large responses via ephemeral RAG. Empty = no condensing.
	EmbedModel string `json:"embed_model,omitempty"`
	// EmbedThreshold is the char count above which the response is condensed (0 = default 8000).
	EmbedThreshold int `json:"embed_threshold,omitempty"`
	TimeoutSecs    int `json:"timeout_secs,omitempty"`
}

CreateExternalApiRequest is the body for registering a new external API tool.

type CreateMcpIntegrationRequest added in v0.0.13

type CreateMcpIntegrationRequest struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	BaseURL     string `json:"base_url"`
	Token       string `json:"token"`
	// ApiIP is the internal IP to reach the MCP server (optional). When set,
	// the Synapse MCP client connects via this IP and derives the Host header
	// from BaseURL.
	ApiIP string `json:"api_ip,omitempty"`
}

CreateMcpIntegrationRequest is the body for registering a new MCP server integration.

type CreateTenantRequestDto

type CreateTenantRequestDto struct {
	ID       string `json:"uuid"`
	Name     string `json:"name"`
	Document string `json:"document"`
}

CreateTenantRequestDto is the body for creating a tenant.

type CreateUserRequestDto

type CreateUserRequestDto struct {
	Name     string   `json:"name"`
	Email    string   `json:"email"`
	Password string   `json:"password"`
	Role     UserRole `json:"role"`
}

CreateUserRequestDto is the body for creating a user.

type DispatchCase added in v0.0.51

type DispatchCase interface {
	// GetQueueStats returns the state of the jobs and outputs Redis streams,
	// including active consumers (workers) and their idle times.
	GetQueueStats(ctx context.Context) (*QueueStatsResponse, error)
	// ListJobs returns pending and processing jobs. Use params.TenantUUID to
	// filter by tenant; params.Count defaults to 50 (max 200).
	ListJobs(ctx context.Context, params ListQueuedJobsParams) (*PagedJobs, error)
	// DeleteJob removes a job from the stream (XDEL). If the job is in PEL,
	// XACK is also issued. The redisID must be the Redis Stream message ID
	// (e.g. "1783450838712-0").
	DeleteJob(ctx context.Context, redisID string) error
}

DispatchCase provides access to the dispatch queue observability endpoints.

type DispatchRequest added in v0.0.50

type DispatchRequest struct {
	ChatRequest
	// WebhookID is the CSA webhook used to deliver the final message on the PABX side.
	WebhookID string `json:"webhook_id,omitempty"`
	// Destino is the destination number (the PABX also resolves it from the protocol).
	Destino string `json:"destino,omitempty"`
	// TriggerFileID sends a PABX trigger file (gatilho) as part of the answer.
	TriggerFileID string `json:"trigger_file_id,omitempty"`
	// ExternalID is a client-defined correlation id.
	ExternalID string `json:"external_id,omitempty"`
}

DispatchRequest is the body for the asynchronous, durable processing endpoint. It embeds ChatRequest (same fields) and adds the delivery data used when the final output is sent back through the PABX central MCP tool. The call returns immediately (202) with a job id; processing runs in a dedicated worker and survives restarts.

type DispatchResponse added in v0.0.50

type DispatchResponse struct {
	JobID  string `json:"job_id"`
	Status string `json:"status"` // always "queued"
}

DispatchResponse confirms the job was queued (HTTP 202).

type DocumentCase added in v0.0.6

type DocumentCase interface {
	// Upload sends a document file to the server, which parses it, generates embeddings
	// via OpenRouter, and stores the vectors in Qdrant. Processing happens in the background;
	// the returned DocumentResponse will have Status="processing" immediately.
	Upload(ctx context.Context, req UploadDocumentRequest) (*DocumentResponse, error)

	// Get returns the metadata of a document by its UUID.
	Get(ctx context.Context, documentUUID string) (*DocumentResponse, error)

	// List returns a paginated list of documents belonging to the given collection.
	List(ctx context.Context, params ListDocumentsParams) (*ListDocumentsResponse, error)

	// Delete removes a document and all its associated Qdrant vectors.
	Delete(ctx context.Context, documentUUID string) error

	// Estimate returns a cost estimate for embedding the file with the given model.
	// Pre-processes text, counts pages/images, and looks up model pricing via OpenRouter.
	Estimate(ctx context.Context, req EstimateDocumentRequest) (*EstimateDocumentResponse, error)

	// ListChunks returns a paginated list of the vectorized text chunks stored in
	// Qdrant for the given document, ordered by chunk_index (reading order).
	// Use params.Size to control how many chunks per page (max 100, default 20).
	ListChunks(ctx context.Context, documentUUID string, params ListChunksParams) (*ListChunksResponse, error)
}

DocumentCase provides operations for uploading and managing vectorized documents.

type DocumentChunkResponse added in v0.0.10

type DocumentChunkResponse struct {
	ID           string `json:"id"`
	ChunkIndex   int    `json:"chunk_index"`
	Text         string `json:"text"`
	DocumentUUID string `json:"document_uuid"`
	Filename     string `json:"filename"`
	FileType     string `json:"file_type"`
}

DocumentChunkResponse is a single vectorized text chunk stored in Qdrant.

type DocumentResponse added in v0.0.6

type DocumentResponse struct {
	UUID           string           `json:"uuid"`
	TenantUUID     string           `json:"tenant_uuid"`
	CollectionUUID string           `json:"collection_uuid"`
	Filename       string           `json:"filename"`
	FileType       string           `json:"file_type"`
	EmbedModel     string           `json:"embed_model"`
	ChunkCount     int              `json:"chunk_count"`
	VectorSize     int              `json:"vector_size"`
	TokensUsed     int64            `json:"tokens_used"`
	Status         string           `json:"status"`
	ErrorMessage   string           `json:"error_message,omitempty"`
	ProcessingInfo []ProcessingStep `json:"processing_info"`
	CreatedAt      string           `json:"created_at"`
	UpdatedAt      string           `json:"updated_at"`
}

DocumentResponse describes a document that has been uploaded and vectorized.

type DuplicateAgentRequest added in v0.0.59

type DuplicateAgentRequest struct {
	Name string `json:"name"`
}

DuplicateAgentRequest is the payload for AgentCase.Duplicate — only the name of the copy; everything else is inherited from the source agent.

type EstimateDocumentRequest added in v0.0.46

type EstimateDocumentRequest struct {
	EmbedModel string
	ChunkSize  int
	Overlap    int
	FileName   string
	Content    []byte
}

EstimateDocumentRequest groups the parameters for cost estimation.

type EstimateDocumentResponse added in v0.0.46

type EstimateDocumentResponse struct {
	Pages        int     `json:"pages"`
	TextChars    int     `json:"text_chars"`
	EstTokens    int     `json:"est_tokens"`
	PricePer1M   string  `json:"price_per_1m_usd"`
	EstCostUSD   float64 `json:"est_cost_usd"`
	SupportsImg  bool    `json:"supports_image"`
	ImgEstTokens int     `json:"img_est_tokens,omitempty"`
}

EstimateDocumentResponse is the cost estimate returned before upload.

type EventStream added in v0.0.39

type EventStream struct {
	// contains filtered or unexported fields
}

EventStream is a live subscription to the monitor WebSocket. Consume events from Events(); the channel is closed after Close() or context cancellation.

func (*EventStream) Close added in v0.0.39

func (s *EventStream) Close()

Close stops the stream and closes the events channel.

func (*EventStream) Events added in v0.0.39

func (s *EventStream) Events() <-chan AgentEvent

Events returns the channel where incoming agent events are delivered.

func (*EventStream) Session added in v0.0.39

func (s *EventStream) Session() string

Session returns the session UUID used to resume the delivery queue.

type ExternalApiCase added in v0.0.32

type ExternalApiCase interface {
	Create(ctx context.Context, req CreateExternalApiRequest) (*ExternalApiResponse, error)
	Get(ctx context.Context, uuid string) (*ExternalApiResponse, error)
	List(ctx context.Context) (*ExternalApiListResponse, error)
	Update(ctx context.Context, uuid string, req UpdateExternalApiRequest) (*ExternalApiResponse, error)
	// Toggle flips the is_active state of an external API tool.
	Toggle(ctx context.Context, uuid string) (*ExternalApiResponse, error)
	Delete(ctx context.Context, uuid string) error
}

ExternalApiCase provides CRUD operations for external API tools — raw HTTP APIs registered by a tenant that an AI agent can invoke as function-calling tools.

type ExternalApiListResponse added in v0.0.32

type ExternalApiListResponse struct {
	Items []ExternalApiResponse `json:"api_tools"`
	Page  int                   `json:"page"`
	Size  int                   `json:"size"`
	Total int                   `json:"total"`
}

ExternalApiListResponse is the list of external API tools for a tenant.

type ExternalApiParamDef added in v0.0.32

type ExternalApiParamDef struct {
	Name        string   `json:"name"`
	Type        string   `json:"type"` // string|number|integer|boolean|array|object
	Description string   `json:"description"`
	Required    bool     `json:"required"`
	Location    string   `json:"location"` // query|path|header|body
	Enum        []string `json:"enum,omitempty"`
}

ExternalApiParamDef describes one input the AI fills when calling an external API tool. It becomes a property of the tool's JSON Schema and is interpolated as {{name}} into the URL/headers/body according to Location.

type ExternalApiResponse added in v0.0.32

type ExternalApiResponse struct {
	UUID           string                `json:"uuid"`
	TenantUUID     string                `json:"tenant_uuid"`
	Name           string                `json:"name"`
	Description    string                `json:"description"`
	UsagePrompt    string                `json:"usage_prompt"`
	Method         string                `json:"method"`
	URL            string                `json:"url"`
	Headers        map[string]string     `json:"headers"`
	BodyTemplate   string                `json:"body_template"`
	Parameters     []ExternalApiParamDef `json:"parameters"`
	EmbedModel     string                `json:"embed_model"`
	EmbedThreshold int                   `json:"embed_threshold"`
	TimeoutSecs    int                   `json:"timeout_secs"`
	IsActive       bool                  `json:"is_active"`
	CreatedAt      string                `json:"created_at"`
	UpdatedAt      string                `json:"updated_at"`
}

ExternalApiResponse describes a registered external API tool.

type GoogleCase

type GoogleCase interface {
	// Configure creates or updates the Google Vision AI integration credentials
	// for the authenticated tenant.
	Configure(ctx context.Context, req ConfigureGoogleRequest) error

	// VisionOCR extracts text from an image using Google Vision TEXT_DETECTION.
	// fileName is used as the multipart filename (e.g. "photo.jpg").
	// fileContent is the raw image bytes (png, jpg, jpeg, webp).
	VisionOCR(ctx context.Context, fileName string, fileContent []byte) (*AnalyzeImageResponse, error)

	// VisionOCRFromURL extracts text from an image that the Synapse server
	// downloads from the URL in req.FileURL.
	VisionOCRFromURL(ctx context.Context, req VisionOCRFromURLRequest) (*AnalyzeImageResponse, error)
}

GoogleCase provides operations for the Google Vision AI integration.

type KeyInfo added in v0.0.20

type KeyInfo struct {
	Label          string  `json:"label"`
	Limit          float64 `json:"limit"`
	LimitRemaining float64 `json:"limit_remaining"`
	Usage          float64 `json:"usage"`
	IsFreeTier     bool    `json:"is_free_tier"`
}

type ListAgentLogsParams added in v0.0.17

type ListAgentLogsParams struct {
	ConversationUUID string
	ExternalID       string
	Page             int
	Size             int
}

ListAgentLogsParams holds optional filters when listing agent logs.

type ListAgentLogsResponse added in v0.0.17

type ListAgentLogsResponse struct {
	Logs  []AgentLogItem `json:"logs"`
	Page  int            `json:"page"`
	Size  int            `json:"size"`
	Total int64          `json:"total"`
}

ListAgentLogsResponse is the paginated response for listing agent logs.

type ListAgentPromptsResponse added in v0.0.11

type ListAgentPromptsResponse struct {
	Prompts []AgentPromptResponse `json:"prompts"`
	Page    int                   `json:"page"`
	Size    int                   `json:"size"`
}

ListAgentPromptsResponse is the paginated list of saved prompts for an agent.

type ListAgentsResponse added in v0.0.6

type ListAgentsResponse struct {
	Agents []AgentResponse `json:"agents"`
	Page   int             `json:"page"`
	Size   int             `json:"size"`
}

ListAgentsResponse is the paginated list of agents for a tenant.

type ListApiTokensResponse

type ListApiTokensResponse struct {
	UserUUID  string                   `json:"user_uuid"`
	Page      int                      `json:"page"`
	Size      int                      `json:"size"`
	APITokens []ApiTokenCreateResponse `json:"api_tokens"`
}

ListApiTokensResponse is the paginated response for the API token list.

type ListChatvoltAgentsResponse added in v0.0.4

type ListChatvoltAgentsResponse struct {
	Agents []ChatvoltAgentItem `json:"agents"`
}

ListChatvoltAgentsResponse is the response for the Chatvolt agents list endpoint.

type ListChunksParams added in v0.0.10

type ListChunksParams struct {
	Page int
	// Size is the number of chunks per page (max 100, default 20).
	Size int
}

ListChunksParams holds query parameters for the chunk list endpoint.

type ListChunksResponse added in v0.0.10

type ListChunksResponse struct {
	Chunks     []DocumentChunkResponse `json:"chunks"`
	Total      int                     `json:"total"`
	Page       int                     `json:"page"`
	Size       int                     `json:"size"`
	TotalPages int                     `json:"total_pages"`
}

ListChunksResponse is the paginated list of chunks for a document.

type ListConversationsParams added in v0.0.7

type ListConversationsParams struct {
	// AgentUUID filters conversations by a specific agent (optional).
	AgentUUID string
	// ExternalID filters by the client-provided external identifier (e.g. protocol number).
	ExternalID string
	Page       int
	Size       int
}

ListConversationsParams holds query parameters for the conversation list endpoint.

type ListConversationsResponse added in v0.0.7

type ListConversationsResponse struct {
	Conversations []ConversationResponse `json:"conversations"`
	Page          int                    `json:"page"`
	Size          int                    `json:"size"`
	Total         int64                  `json:"total"`
}

ListConversationsResponse is the paginated list of conversation summaries.

type ListDocumentsParams added in v0.0.6

type ListDocumentsParams struct {
	// CollectionUUID filters documents by collection.
	// Required for TENANT_ADMIN/TENANT_USER; optional for SYSTEM_ADMIN.
	CollectionUUID string
	Page           int
	Size           int
}

ListDocumentsParams holds query parameters for the document list endpoint.

type ListDocumentsResponse added in v0.0.6

type ListDocumentsResponse struct {
	Documents []DocumentResponse `json:"documents"`
	Page      int                `json:"page"`
	Size      int                `json:"size"`
}

ListDocumentsResponse is the paginated list of documents in a collection.

type ListQueuedJobsParams added in v0.0.51

type ListQueuedJobsParams struct {
	TenantUUID string
	Cursor     string
	Count      int64
}

ListQueuedJobsParams holds the optional filters and cursor for listing jobs.

type ListUsersParams

type ListUsersParams struct {
	Page int
	Size int
	// TenantIdentifier filters by tenant UUID or document (SystemAdmin only).
	TenantIdentifier string
}

ListUsersParams holds query parameters for the user list endpoint.

type LoginRequest

type LoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
	// RememberMe extends the token expiry to 30 days when true.
	// Omit or set false for the default short-lived session.
	RememberMe bool `json:"remember_me,omitempty"`
}

LoginRequest holds the credentials for the login endpoint.

type LoginResponse

type LoginResponse struct {
	Token         string          `json:"token"`
	Expire        string          `json:"expire"`
	SystemTimeUTC string          `json:"system_time_utc"`
	User          UserResponseDto `json:"user"`
}

LoginResponse is returned on successful login or healthcheck.

type McpCase added in v0.0.13

type McpCase interface {
	Create(ctx context.Context, req CreateMcpIntegrationRequest) (*McpIntegrationResponse, error)
	Get(ctx context.Context, uuid string) (*McpIntegrationResponse, error)
	List(ctx context.Context) (*McpIntegrationListResponse, error)
	Update(ctx context.Context, uuid string, req UpdateMcpIntegrationRequest) (*McpIntegrationResponse, error)
	Toggle(ctx context.Context, uuid string, req ToggleMcpIntegrationRequest) (*McpIntegrationResponse, error)
	Delete(ctx context.Context, uuid string) error
	// GetTools lists the tools exposed by the remote MCP server behind this integration.
	GetTools(ctx context.Context, uuid string) (*McpToolsListResponse, error)
}

McpCase provides CRUD operations for MCP (Model Context Protocol) server integrations.

type McpIntegrationListResponse added in v0.0.13

type McpIntegrationListResponse struct {
	Items []McpIntegrationResponse `json:"integrations"`
	Total int                      `json:"total"`
}

McpIntegrationListResponse is the list of MCP integrations for a tenant.

type McpIntegrationResponse added in v0.0.13

type McpIntegrationResponse struct {
	UUID        string `json:"uuid"`
	TenantUUID  string `json:"tenant_uuid"`
	Name        string `json:"name"`
	Description string `json:"description"`
	BaseURL     string `json:"base_url"`
	ApiIP       string `json:"api_ip,omitempty"`
	IsActive    bool   `json:"is_active"`
	CreatedAt   string `json:"created_at"`
	UpdatedAt   string `json:"updated_at"`
}

type McpToolDefinition added in v0.0.15

type McpToolDefinition struct {
	Name        string             `json:"name"`
	DisplayName string             `json:"display_name"`
	Description string             `json:"description"`
	Parameters  []McpToolParameter `json:"parameters"`
}

McpToolDefinition describes a tool exposed by an MCP integration's remote server.

type McpToolParameter added in v0.0.15

type McpToolParameter struct {
	Name        string   `json:"name"`
	Type        string   `json:"type"`
	Description string   `json:"description"`
	Required    bool     `json:"required"`
	Enum        []string `json:"enum,omitempty"`
}

McpToolParameter describes one parameter of a tool exposed by an MCP integration.

type McpToolsListResponse added in v0.0.15

type McpToolsListResponse struct {
	Tools []McpToolDefinition `json:"tools"`
}

McpToolsListResponse is the response of listing the tools exposed by an MCP integration.

type MonitorCase added in v0.0.39

type MonitorCase interface {
	// StreamLogs opens the monitor WebSocket and keeps it alive, reconnecting
	// automatically with the same session until ctx is cancelled or the
	// returned stream is closed. Events are delivered on EventStream.Events().
	StreamLogs(ctx context.Context, opts *StreamLogsOptions) (*EventStream, error)
}

MonitorCase provides access to the real-time agent event WebSocket.

The stream is receive-only: the server pushes agent execution events (chat, tool_call/MCP, RAG, errors, file processing and tool_agent — internal verification agents such as the grounding judge, the parameter judge and the API artifact executor) and the SDK automatically acknowledges each delivery. A master (SYSTEM_ADMIN) token receives events from every tenant; a tenant token receives only its own tenant's events.

type OTPRequest

type OTPRequest struct {
	Email string `json:"email"`
}

OTPRequest requests a one-time password to be sent to the given email.

type OTPResetPasswordRequest

type OTPResetPasswordRequest struct {
	Email    string `json:"email"`
	OTP      string `json:"otp"`
	Password string `json:"password"`
}

OTPResetPasswordRequest resets a user password using an OTP code.

type OpenAICase

type OpenAICase interface {
	// Configure creates or updates the OpenAI integration credentials and settings
	// for the authenticated tenant.
	Configure(ctx context.Context, req ConfigureOpenAIRequest) error

	// Chat executes a Chat Completion call using the tenant's configured OpenAI account.
	Chat(ctx context.Context, req ChatCompletionRequest) (*ChatCompletionResponse, error)

	// AnalyzeImage analyses an image using OpenAI vision.
	// fileName is the multipart filename (e.g. "image.png").
	// fileContent is the raw image bytes (png, jpg, jpeg, webp).
	// prompt describes what analysis to perform.
	AnalyzeImage(ctx context.Context, fileName string, fileContent []byte, prompt string) (*AnalyzeImageResponse, error)

	// AnalyzeImageFromURL analyses an image that the Synapse server downloads from
	// the provided URL (no local upload required).
	AnalyzeImageFromURL(ctx context.Context, req AnalyzeImageFromURLRequest) (*AnalyzeImageResponse, error)

	// TranscribeAudio converts an audio file to text using OpenAI Whisper or GPT-4o.
	// See TranscribeAudioRequest for the full set of options.
	TranscribeAudio(ctx context.Context, req TranscribeAudioRequest) (*TranscriptionResponse, error)

	// TranscribeAudioFromURL converts an audio file to text; the Synapse server
	// downloads the file from the URL in req.FileURL.
	TranscribeAudioFromURL(ctx context.Context, req TranscribeAudioFromURLRequest) (*TranscriptionResponse, error)
}

OpenAICase provides operations for the OpenAI integration.

type OpenAICredentialsDTO

type OpenAICredentialsDTO struct {
	Token string `json:"token"`
}

OpenAICredentialsDTO holds the API key for the OpenAI integration.

type OpenAIModel

type OpenAIModel string

OpenAIModel is the model identifier accepted by the OpenAI integration.

const (
	OpenAIModelGPT4oMini  OpenAIModel = "gpt-4o-mini"
	OpenAIModelGPT4o      OpenAIModel = "gpt-4o"
	OpenAIModelGPT4_1     OpenAIModel = "gpt-4.1"
	OpenAIModelGPT4_1Mini OpenAIModel = "gpt-4.1-mini"
	OpenAIModelO4Mini     OpenAIModel = "o4-mini"
)

type OpenAISettingsDTO

type OpenAISettingsDTO struct {
	Model OpenAIModel `json:"model"`
	// Temperature ranges 0–2; omitted when zero.
	Temperature float64 `json:"temperature,omitempty"`
}

OpenAISettingsDTO configures model and sampling behaviour.

type OpenRouterAnalyticsDimensionInfo added in v0.0.25

type OpenRouterAnalyticsDimensionInfo struct {
	Name         string `json:"name"`
	DisplayLabel string `json:"display_label"`
}

OpenRouterAnalyticsDimensionInfo describes a dimension available for analytics queries.

type OpenRouterAnalyticsFilter added in v0.0.25

type OpenRouterAnalyticsFilter struct {
	Field string `json:"field"`
	// Operator is one of: eq, neq, in, not_in, gt, gte, lt, lte.
	Operator string `json:"operator"`
	Value    any    `json:"value"`
}

OpenRouterAnalyticsFilter is an additional filter for an analytics query. The "workspace" field is rejected by the server — it is applied automatically from the authenticated tenant.

type OpenRouterAnalyticsGranularityInfo added in v0.0.25

type OpenRouterAnalyticsGranularityInfo struct {
	Name         string `json:"name"`
	DisplayLabel string `json:"display_label"`
}

OpenRouterAnalyticsGranularityInfo describes a granularity available for analytics queries.

type OpenRouterAnalyticsMeta added in v0.0.25

type OpenRouterAnalyticsMeta struct {
	Metrics       []OpenRouterAnalyticsMetricInfo      `json:"metrics"`
	Dimensions    []OpenRouterAnalyticsDimensionInfo   `json:"dimensions"`
	Operators     []OpenRouterAnalyticsOperatorInfo    `json:"operators"`
	Granularities []OpenRouterAnalyticsGranularityInfo `json:"granularities"`
}

OpenRouterAnalyticsMeta aggregates the analytics metadata of the tenant's workspace.

type OpenRouterAnalyticsMetricInfo added in v0.0.25

type OpenRouterAnalyticsMetricInfo struct {
	Name          string `json:"name"`
	DisplayLabel  string `json:"display_label"`
	IsRate        bool   `json:"is_rate"`
	DisplayFormat string `json:"display_format"`
}

OpenRouterAnalyticsMetricInfo describes a metric available for analytics queries.

type OpenRouterAnalyticsOperatorInfo added in v0.0.25

type OpenRouterAnalyticsOperatorInfo struct {
	Name      string `json:"name"`
	ValueType string `json:"value_type"`
}

OpenRouterAnalyticsOperatorInfo describes a filter operator available for analytics queries.

type OpenRouterAnalyticsQueryRequest added in v0.0.25

type OpenRouterAnalyticsQueryRequest struct {
	Metrics    []string                    `json:"metrics"`
	Dimensions []string                    `json:"dimensions,omitempty"`
	Filters    []OpenRouterAnalyticsFilter `json:"filters,omitempty"`
	// Granularity is one of: minute, hour, day (default), week, month.
	Granularity string `json:"granularity,omitempty"`
	// Limit caps the number of rows (default 1000, max 1000).
	Limit     int                          `json:"limit,omitempty"`
	TimeRange OpenRouterAnalyticsTimeRange `json:"time_range"`
}

OpenRouterAnalyticsQueryRequest is the body for an arbitrary analytics query. Metrics/dimensions outside the daily materialized view (only tokens_total, total_usage and the model dimension are MV-compatible) are limited to a 31-day time range, as are the minute and hour granularities.

type OpenRouterAnalyticsResult added in v0.0.25

type OpenRouterAnalyticsResult struct {
	WorkspaceID string           `json:"workspace_id"`
	Rows        []map[string]any `json:"rows"`
	RowCount    int              `json:"row_count"`
	Truncated   bool             `json:"truncated"`
	QueryTimeMs int              `json:"query_time_ms"`
}

OpenRouterAnalyticsResult is the result of an analytics query. Row keys are dynamic and depend on the requested metrics/dimensions/granularity (e.g. date__day, created_at__month, model, tokens_total).

type OpenRouterAnalyticsTimeRange added in v0.0.25

type OpenRouterAnalyticsTimeRange struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

OpenRouterAnalyticsTimeRange bounds an analytics query. Start and End are RFC3339 timestamps (e.g. "2026-06-01T00:00:00Z").

type OpenRouterCase added in v0.0.6

type OpenRouterCase interface {
	// Sync creates or returns an existing OpenRouter workspace for the authenticated tenant.
	// SystemAdmin callers may target a specific tenant by setting req.TenantUUID.
	Sync(ctx context.Context, req OpenRouterSyncRequest) (*OpenRouterSyncResponse, error)

	// Desync removes the OpenRouter workspace for the authenticated tenant.
	// SystemAdmin callers may target a specific tenant by setting req.TenantUUID.
	Desync(ctx context.Context, req OpenRouterSyncRequest) (*OpenRouterDesyncResponse, error)

	// ListModels returns all models available on OpenRouter.
	// Set freeOnly=true to filter for free-tier models only.
	ListModels(ctx context.Context, freeOnly bool) (*OpenRouterListModelsResponse, error)

	// ListEmbeddingModels fetches live embedding models from the OpenRouter API,
	// filtered by output modality. Each entry includes vector_size (0 = unknown) and
	// context_length so callers can configure Qdrant collections and chunk sizes correctly.
	// Set freeOnly=true to filter for free-tier models only.
	ListEmbeddingModels(ctx context.Context, freeOnly bool) (*OpenRouterListEmbeddingModelsResponse, error)

	// GetMonthlyAnalytics returns tokens_total and total_usage per model/day of a
	// month for the workspace linked to the authenticated tenant.
	GetMonthlyAnalytics(ctx context.Context, params OpenRouterMonthlyAnalyticsParams) (*OpenRouterMonthlyAnalyticsResponse, error)

	// QueryAnalytics runs an analytics query scoped to the tenant's workspace.
	// The workspace filter is applied server-side and must not be present in
	// req.Filters. Metrics/dimensions outside the daily materialized view (only
	// tokens_total, total_usage and the model dimension are MV-compatible) are
	// limited to a 31-day time range, as are the minute and hour granularities.
	QueryAnalytics(ctx context.Context, req OpenRouterAnalyticsQueryRequest) (*OpenRouterAnalyticsResult, error)

	// GetAnalyticsMeta returns the metrics, dimensions, filter operators and
	// granularities available for analytics queries on the tenant's workspace.
	GetAnalyticsMeta(ctx context.Context) (*OpenRouterAnalyticsMeta, error)
}

OpenRouterCase provides operations for the OpenRouter integration.

type OpenRouterDesyncResponse added in v0.0.6

type OpenRouterDesyncResponse struct {
	TenantUUID string `json:"tenant_uuid"`
	Removed    bool   `json:"removed"`
}

OpenRouterDesyncResponse is returned after a successful workspace removal.

type OpenRouterEmbeddingModel added in v0.0.6

type OpenRouterEmbeddingModel struct {
	ID              string   `json:"id"`
	Name            string   `json:"name"`
	Provider        string   `json:"provider"`
	VectorSize      int      `json:"vector_size"`
	ContextLength   int      `json:"context_length,omitempty"`
	Description     string   `json:"description"`
	PricePer1M      string   `json:"price_per_token_usd"`
	IsFree          bool     `json:"is_free"`
	InputModalities []string `json:"input_modalities,omitempty"`
}

OpenRouterEmbeddingModel describes a single embedding model returned live from the OpenRouter API.

type OpenRouterListEmbeddingModelsResponse added in v0.0.6

type OpenRouterListEmbeddingModelsResponse struct {
	Models []OpenRouterEmbeddingModel `json:"models"`
	Total  int                        `json:"total"`
}

OpenRouterListEmbeddingModelsResponse is the paginated list of OpenRouter embedding models.

type OpenRouterListModelsResponse added in v0.0.6

type OpenRouterListModelsResponse struct {
	Models []OpenRouterModelInfo `json:"models"`
	Total  int                   `json:"total"`
}

OpenRouterListModelsResponse is the paginated list of OpenRouter models.

type OpenRouterModelArchitecture added in v0.0.8

type OpenRouterModelArchitecture struct {
	InputModalities  []string `json:"input_modalities,omitempty"`
	OutputModalities []string `json:"output_modalities,omitempty"`
	Modality         string   `json:"modality,omitempty"`
}

OpenRouterModelArchitecture holds the supported modalities for a model.

type OpenRouterModelInfo added in v0.0.6

type OpenRouterModelInfo struct {
	ID                  string                      `json:"id"`
	Name                string                      `json:"name"`
	CanonicalSlug       string                      `json:"canonical_slug,omitempty"`
	Description         string                      `json:"description,omitempty"`
	ContextLength       int                         `json:"context_length,omitempty"`
	Created             int64                       `json:"created,omitempty"`
	KnowledgeCutoff     string                      `json:"knowledge_cutoff,omitempty"`
	Pricing             OpenRouterModelPricing      `json:"pricing"`
	Architecture        OpenRouterModelArchitecture `json:"architecture"`
	TopProvider         OpenRouterTopProvider       `json:"top_provider"`
	SupportedParameters []string                    `json:"supported_parameters,omitempty"`
	IsFree              bool                        `json:"is_free"`
}

OpenRouterModelInfo describes a single model available on OpenRouter.

type OpenRouterModelPricing added in v0.0.6

type OpenRouterModelPricing struct {
	Prompt     string `json:"prompt"`
	Completion string `json:"completion"`
	Image      string `json:"image,omitempty"`
	Request    string `json:"request,omitempty"`
}

OpenRouterModelPricing holds per-token/request pricing for an OpenRouter model.

type OpenRouterMonthlyAnalyticsParams added in v0.0.25

type OpenRouterMonthlyAnalyticsParams struct {
	// Month in "YYYY-MM" format. Empty = current month.
	Month string
	// Limit caps the number of rows (default 1000, max 1000).
	Limit int
}

OpenRouterMonthlyAnalyticsParams are the optional parameters for GetMonthlyAnalytics.

type OpenRouterMonthlyAnalyticsResponse added in v0.0.25

type OpenRouterMonthlyAnalyticsResponse struct {
	WorkspaceID string                        `json:"workspace_id"`
	Month       string                        `json:"month"`
	Items       []OpenRouterMonthlyMetricItem `json:"items"`
	Total       int                           `json:"total"`
}

OpenRouterMonthlyAnalyticsResponse is the per-model/day usage of a month.

type OpenRouterMonthlyMetricItem added in v0.0.25

type OpenRouterMonthlyMetricItem struct {
	Date        string  `json:"date"`
	Model       string  `json:"model"`
	TokensTotal int64   `json:"tokens_total"`
	TotalUsage  float64 `json:"total_usage"`
}

OpenRouterMonthlyMetricItem is the usage of one model on a single day of the month.

type OpenRouterSyncRequest added in v0.0.6

type OpenRouterSyncRequest struct {
	TenantUUID string `json:"tenant_uuid,omitempty"`
}

OpenRouterSyncRequest is the body for syncing a workspace with OpenRouter. TenantUUID is optional and only honoured when the caller is a SystemAdmin.

type OpenRouterSyncResponse added in v0.0.6

type OpenRouterSyncResponse struct {
	TenantUUID    string `json:"tenant_uuid"`
	WorkspaceID   string `json:"workspace_id"`
	KeyHash       string `json:"key_hash"`
	Active        bool   `json:"active"`
	AlreadySynced bool   `json:"already_synced"`
	SyncedAt      string `json:"synced_at"`
}

OpenRouterSyncResponse is returned after a successful workspace sync.

type OpenRouterTopProvider added in v0.0.8

type OpenRouterTopProvider struct {
	MaxCompletionTokens *int `json:"max_completion_tokens,omitempty"`
	IsModerated         bool `json:"is_moderated"`
}

OpenRouterTopProvider holds information about the primary provider of a model.

type Options

type Options struct {
	// BaseURL overrides the default API base URL (https://synapse.wonit.net.br).
	// Useful for staging environments or self-hosted deployments.
	BaseURL string

	// Host overrides the Host header sent on every request (HTTP and WebSocket).
	// Use it together with an IP-based BaseURL to reach the API through the
	// internal network while the server still resolves the right virtual host,
	// e.g. BaseURL "http://172.16.50.10" + Host "synapse-dev.wonit.cloud".
	Host string

	// Timeout sets the maximum duration for each HTTP request.
	// Defaults to 30 seconds when zero.
	Timeout time.Duration
}

Options configures the Synapse client at creation time. All fields are optional; zero values fall back to library defaults.

type PagedJobs added in v0.0.51

type PagedJobs struct {
	Total      int64       `json:"total"`
	Items      []QueuedJob `json:"items"`
	NextCursor string      `json:"next_cursor,omitempty"`
}

PagedJobs contains a paginated list of jobs plus the stream total and a cursor for the next page (opaque Redis stream ID).

type ProcessingStep added in v0.0.43

type ProcessingStep struct {
	Step   string `json:"step"`
	Detail string `json:"detail"`
	Status string `json:"status"`
	Tokens int    `json:"tokens"`
}

ProcessingStep is one step in the document processing pipeline.

type ProviderCase

type ProviderCase interface {
	// Get fetches a single provider by its UUID.
	Get(ctx context.Context, id string) (*ProviderResponseDto, error)

	// List returns a paginated list of all available providers.
	List(ctx context.Context, page, pageSize int) (*ProvidersResponseDto, error)
}

ProviderCase provides read operations for catalog integration providers.

type ProviderResponseDto

type ProviderResponseDto struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	LogoURL   string `json:"logo_url"`
	Website   string `json:"website"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

ProviderResponseDto describes a catalog integration provider (e.g. Google, OpenAI).

type ProvidersResponseDto

type ProvidersResponseDto struct {
	Page      int                   `json:"page"`
	Size      int                   `json:"size"`
	Providers []ProviderResponseDto `json:"providers"`
}

ProvidersResponseDto is the paginated response for the provider list.

type QueueActiveConsumer added in v0.0.51

type QueueActiveConsumer struct {
	Name         string `json:"name"`
	PendingCount int64  `json:"pending_count"`
	IdleMs       int64  `json:"idle_ms"`
}

QueueActiveConsumer represents an active consumer of a Redis Stream group.

type QueueStatsResponse added in v0.0.51

type QueueStatsResponse struct {
	Jobs    QueueSummary `json:"jobs"`
	Outputs QueueSummary `json:"outputs"`
}

QueueStatsResponse aggregates metrics from both dispatch streams.

type QueueSummary added in v0.0.51

type QueueSummary struct {
	Stream       string                `json:"stream"`
	Group        string                `json:"group"`
	TotalPending int64                 `json:"total_pending"`
	Consumers    []QueueActiveConsumer `json:"consumers,omitempty"`
}

QueueSummary describes the state of a stream and its consumer group.

type QueuedJob added in v0.0.51

type QueuedJob struct {
	RedisID    string `json:"redis_id"`
	JobID      string `json:"job_id"`
	TenantUUID string `json:"tenant_uuid,omitempty"`
	AgentUUID  string `json:"agent_uuid,omitempty"`
	Destino    string `json:"destino,omitempty"`
	Message    string `json:"message,omitempty"`
	ExternalID string `json:"external_id,omitempty"`
	EnqueuedAt string `json:"enqueued_at"`
	Status     string `json:"status"`
	Consumer   string `json:"consumer,omitempty"`
	RetryCount int64  `json:"retry_count"`
	IdleMs     int64  `json:"idle_ms,omitempty"`
	LastError  string `json:"last_error,omitempty"`
	RawPayload string `json:"raw,omitempty"`
}

QueuedJob is a job in the dispatch queue (pending or processing).

type RestErrCause

type RestErrCause struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

RestErrCause holds a field-level validation detail returned by the API.

type ServiceCase

type ServiceCase interface {
	// Get fetches a single integration service by its UUID.
	Get(ctx context.Context, id string) (*ServiceResponseDto, error)

	// List returns a paginated list of all available integration services.
	List(ctx context.Context, page, pageSize int) (*ServicesResponseDto, error)
}

ServiceCase provides read operations for catalog integration services.

type ServiceResponseDto

type ServiceResponseDto struct {
	ID               string `json:"id"`
	Name             string `json:"name"`
	Slug             string `json:"slug"`
	ProviderID       string `json:"provider_id"`
	BaseURL          string `json:"base_url"`
	AuthType         string `json:"auth_type"`
	DocumentationURL string `json:"documentation_url"`
}

ServiceResponseDto describes a catalog integration service.

type ServiceStatus added in v0.0.49

type ServiceStatus struct {
	Service        string      `json:"service"`
	Version        string      `json:"version"`
	Commit         string      `json:"commit,omitempty"`
	BuildTime      string      `json:"build_time,omitempty"`
	GoVersion      string      `json:"go_version"`
	Pod            string      `json:"pod"`
	UptimeSeconds  int64       `json:"uptime_seconds"`
	SystemTimeUTC  time.Time   `json:"system_time_utc"`
	Database       StatusCheck `json:"database"`
	Redis          StatusCheck `json:"redis"`
	Qdrant         StatusCheck `json:"qdrant"`
	Token          StatusToken `json:"token"`
	ResponseTimeMs int64       `json:"response_time_ms"`
}

ServiceStatus is the full status payload of the Synapse API.

type ServicesResponseDto

type ServicesResponseDto struct {
	Page     int                  `json:"page"`
	Size     int                  `json:"size"`
	Services []ServiceResponseDto `json:"services"`
}

ServicesResponseDto is the paginated response for the service list.

type StatusCase added in v0.0.49

type StatusCase interface {
	// Get returns build info, pod, dependency health (Postgres/Redis/Qdrant),
	// the validity of the token used on the request and the server-side
	// processing time.
	Get(ctx context.Context) (*ServiceStatus, error)
}

StatusCase provides access to the service status endpoint.

type StatusCheck added in v0.0.49

type StatusCheck struct {
	Status    string `json:"status"` // online | offline | disabled
	LatencyMs int64  `json:"latency_ms"`
	Error     string `json:"error,omitempty"`
}

StatusCheck is the health of a single dependency.

type StatusToken added in v0.0.49

type StatusToken struct {
	ExpiresAt        time.Time `json:"expires_at"`
	ExpiresInSeconds int64     `json:"expires_in_seconds"`
}

StatusToken describes the validity of the token used on the request.

type StreamLogsOptions added in v0.0.39

type StreamLogsOptions struct {
	// Session (UUID) resumes the same server-side delivery queue across
	// reconnections. Defaults to a random UUID kept for the stream lifetime.
	Session string

	// Buffer is the capacity of the events channel (default 256).
	Buffer int

	// OnConnect, when set, is invoked every time the WebSocket handshake
	// succeeds — on the first connection and on every automatic reconnection.
	OnConnect func(session string)

	// OnError, when set, is invoked with connection/decoding errors. The
	// stream keeps reconnecting regardless; this is for observability only.
	OnError func(error)
}

StreamLogsOptions tunes the monitor stream. All fields are optional.

type TenantCase

type TenantCase interface {
	// Get fetches a tenant by UUID or document (CNPJ/CPF).
	// At least one of uuid or document must be non-empty.
	Get(ctx context.Context, uuid, document string) (*TenantResponseDto, error)

	// List returns a paginated list of all tenants.
	List(ctx context.Context, page, pageSize int) (*TenantsResponseDto, error)

	// Create registers a new tenant.
	Create(ctx context.Context, req CreateTenantRequestDto) (*TenantResponseDto, error)

	// Update partially updates the tenant identified by uuid.
	Update(ctx context.Context, uuid string, req UpdateTenantRequestDto) (*TenantResponseDto, error)

	// Delete permanently removes a tenant by UUID or document.
	// At least one of uuid or document must be non-empty.
	Delete(ctx context.Context, uuid, document string) error
}

TenantCase provides CRUD operations for tenants within the Synapse API.

type TenantResponseDto

type TenantResponseDto struct {
	UUID      string `json:"uuid"`
	Name      string `json:"name"`
	Document  string `json:"document"`
	Live      bool   `json:"live"`
	CreatedAt string `json:"createAt"`
	UpdatedAt string `json:"updateAt"`
}

TenantResponseDto is the tenant shape returned by the API.

type TenantsResponseDto

type TenantsResponseDto struct {
	Page    int                 `json:"page"`
	Size    int                 `json:"size"`
	Tenants []TenantResponseDto `json:"tenants"`
}

TenantsResponseDto is the paginated response for the tenant list.

type ThoughtItem added in v0.0.36

type ThoughtItem struct {
	ID        string `json:"id"`
	Label     string `json:"label,omitempty"`
	Content   string `json:"content"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

ThoughtItem represents a single thought stored in the agent's working memory (Redis-backed, per conversation). Thoughts are created by the model using tools like armazenar_pensamento and retrieved via buscas.

type ThoughtSearchParams added in v0.0.36

type ThoughtSearchParams struct {
	ConversationUUID string
	Query            string
}

ThoughtSearchParams holds query parameters for searching thoughts in a conversation. ConversationUUID is required; Query filters by keyword (case-insensitive, content+label).

type ThoughtSearchResponse added in v0.0.36

type ThoughtSearchResponse struct {
	Thoughts []ThoughtItem `json:"thoughts"`
	Total    int           `json:"total"`
}

ThoughtSearchResponse is the response from the thoughts search endpoint.

type ToggleMcpIntegrationRequest added in v0.0.13

type ToggleMcpIntegrationRequest struct {
	IsActive bool `json:"is_active"`
}

ToggleMcpIntegrationRequest is the body for activating or deactivating an MCP integration.

type TranscribeAudioFromURLRequest added in v0.0.5

type TranscribeAudioFromURLRequest struct {
	// FileURL is the download link the server uses to fetch the audio file.
	FileURL string `json:"file_url"`
	// Model selects the transcription engine: whisper-1 | gpt-4o-transcribe | gpt-4o-mini-transcribe.
	Model string `json:"model,omitempty"`
	// Language hints the spoken language (e.g. "pt", "en", "es").
	Language string `json:"language,omitempty"`
	// Prompt is optional auxiliary text to improve transcription accuracy.
	Prompt string `json:"prompt,omitempty"`
}

TranscribeAudioFromURLRequest groups all parameters for the audio transcription endpoint when the audio file is fetched from a download URL by the server.

type TranscribeAudioRequest

type TranscribeAudioRequest struct {
	// FileName is used as the multipart filename (e.g. "recording.mp3").
	FileName string
	// Content is the raw audio file bytes.
	Content []byte
	// Model selects the transcription engine: whisper-1 | gpt-4o-transcribe | gpt-4o-mini-transcribe.
	Model string
	// Language hints the spoken language (e.g. "pt", "en", "es").
	Language string
	// Prompt is optional auxiliary text to improve transcription accuracy.
	Prompt string
}

TranscribeAudioRequest groups all parameters for the audio transcription endpoint.

type TranscriptionResponse

type TranscriptionResponse struct {
	Response string `json:"response"`
}

TranscriptionResponse is the response from the audio transcription endpoint.

type UpdateAgentPromptRequest added in v0.0.11

type UpdateAgentPromptRequest struct {
	Name   *string `json:"name,omitempty"`
	Prompt *string `json:"prompt,omitempty"`
}

UpdateAgentPromptRequest is the body for updating name and/or content of a saved prompt.

type UpdateAgentRequest added in v0.0.6

type UpdateAgentRequest struct {
	Name            *string   `json:"name,omitempty"`
	Description     *string   `json:"description,omitempty"`
	Model           *string   `json:"model,omitempty"`
	Prompt          *string   `json:"prompt,omitempty"`
	CollectionUUIDs *[]string `json:"collection_uuids,omitempty"`
	MaxContext      *int      `json:"max_context,omitempty"`
	Temperature     *float64  `json:"temperature,omitempty"`
	Active          *bool     `json:"active,omitempty"`
	McpEnabled      *bool     `json:"mcp_enabled,omitempty"`
	// McpIntegrationUUIDs: nil = no change, []string{} = remove all, ["uuid1"] = replace all.
	McpIntegrationUUIDs *[]string `json:"mcp_integration_uuids,omitempty"`
	// McpDisabledTools: nil = no change, []string{} = re-enable all tools, ["tool1"] = replace all.
	McpDisabledTools *[]string `json:"mcp_disabled_tools,omitempty"`
	ApiToolsEnabled  *bool     `json:"api_tools_enabled,omitempty"`
	// ApiToolUUIDs: nil = no change, []string{} = remove all, ["uuid1"] = replace all.
	ApiToolUUIDs *[]string `json:"api_tool_uuids,omitempty"`
	// ThoughtsEnabled toggles the agent's working memory ("brain") backed by Redis.
	ThoughtsEnabled *bool `json:"thoughts_enabled,omitempty"`
	// ApiArtifactsEnabled toggles API Artifacts (pipelines of chained external API tools).
	ApiArtifactsEnabled *bool   `json:"api_artifacts_enabled,omitempty"`
	AcceptFiles         *bool   `json:"accept_files,omitempty"`
	FileModel           *string `json:"file_model,omitempty"`
	// Per-content-type model overrides. nil = no change; "" = revert to Model.
	TextModel  *string `json:"text_model,omitempty"`
	ImageModel *string `json:"image_model,omitempty"`
	AudioModel *string `json:"audio_model,omitempty"`
	// Per-content-type fallback models. nil = no change; "" = remove fallback.
	TextFallbackModel  *string `json:"text_fallback_model,omitempty"`
	ImageFallbackModel *string `json:"image_fallback_model,omitempty"`
	AudioFallbackModel *string `json:"audio_fallback_model,omitempty"`
}

UpdateAgentRequest is used for both full (PUT) and partial (PATCH) agent updates. For PATCH, set exactly one field; for PUT you may set multiple. CollectionUUIDs: nil = no change, []string{} = remove all, ["uuid1","uuid2"] = replace all.

type UpdateApiArtifactRequest added in v0.0.57

type UpdateApiArtifactRequest struct {
	Name        *string          `json:"name,omitempty"`
	Description *string          `json:"description,omitempty"`
	Prompt      *string          `json:"prompt,omitempty"`
	FlowData    *json.RawMessage `json:"flow_data,omitempty"`
	IsActive    *bool            `json:"is_active,omitempty"`
}

UpdateApiArtifactRequest patches an API Artifact; nil fields are unchanged.

type UpdateExternalApiRequest added in v0.0.32

type UpdateExternalApiRequest struct {
	Name           *string                `json:"name,omitempty"`
	Description    *string                `json:"description,omitempty"`
	UsagePrompt    *string                `json:"usage_prompt,omitempty"`
	Method         *string                `json:"method,omitempty"`
	URL            *string                `json:"url,omitempty"`
	Headers        *map[string]string     `json:"headers,omitempty"`
	BodyTemplate   *string                `json:"body_template,omitempty"`
	Parameters     *[]ExternalApiParamDef `json:"parameters,omitempty"`
	EmbedModel     *string                `json:"embed_model,omitempty"`
	EmbedThreshold *int                   `json:"embed_threshold,omitempty"`
	TimeoutSecs    *int                   `json:"timeout_secs,omitempty"`
	IsActive       *bool                  `json:"is_active,omitempty"`
}

UpdateExternalApiRequest is the body for partially updating an external API tool.

type UpdateMcpIntegrationRequest added in v0.0.13

type UpdateMcpIntegrationRequest struct {
	Name        *string `json:"name,omitempty"`
	Description *string `json:"description,omitempty"`
	BaseURL     *string `json:"base_url,omitempty"`
	Token       *string `json:"token,omitempty"`
	ApiIP       *string `json:"api_ip,omitempty"`
}

type UpdateTenantRequestDto

type UpdateTenantRequestDto struct {
	Name     string `json:"name,omitempty"`
	Document string `json:"document,omitempty"`
	// Live uses a pointer so false can be distinguished from omitted.
	Live *bool `json:"live,omitempty"`
}

UpdateTenantRequestDto is the body for partially updating a tenant.

type UpdateUserRequestDto

type UpdateUserRequestDto struct {
	Name     string   `json:"name,omitempty"`
	Email    string   `json:"email,omitempty"`
	Password string   `json:"password,omitempty"`
	Role     UserRole `json:"role,omitempty"`
}

UpdateUserRequestDto is the body for partially updating a user.

type UploadDocumentRequest added in v0.0.6

type UploadDocumentRequest struct {
	// TenantUUID is required when the caller is SYSTEM_ADMIN; ignored for other roles.
	TenantUUID *string
	// CollectionUUID is the UUID of the target Qdrant collection.
	CollectionUUID string
	// EmbedModel is the OpenRouter embedding model ID (e.g. "openai/text-embedding-ada-002").
	EmbedModel string
	// ChunkSize is the chunk size in characters (default: 1000 when zero).
	ChunkSize int
	// ChunkOverlap is the overlap between chunks in characters (default: 200 when zero).
	ChunkOverlap int
	// FileName is the multipart filename (e.g. "report.pdf").
	FileName string
	// Content is the raw file bytes (PDF, HTML, DOCX, XLSX, CSV).
	Content []byte
}

UploadDocumentRequest groups all parameters for the document upload endpoint.

type UserCase

type UserCase interface {
	// Get returns a single user by UUID or email.
	// Pass the authenticated user's own identifier to fetch their profile.
	Get(ctx context.Context, identifier string) (*UserResponseDto, error)

	// List returns a paginated list of users.
	// SystemAdmin can filter by tenant using params.TenantIdentifier.
	List(ctx context.Context, params ListUsersParams) ([]UserResponseDto, error)

	// Create registers a new user under the given tenant identifier (UUID or document).
	Create(ctx context.Context, tenantIdentifier string, req CreateUserRequestDto) (*UserResponseDto, error)

	// Update partially updates a user identified by UUID or email.
	Update(ctx context.Context, identifier string, req UpdateUserRequestDto) (*UserResponseDto, error)

	// Delete permanently removes a user identified by UUID or email.
	Delete(ctx context.Context, identifier string) error
}

UserCase provides CRUD operations for users within the Synapse API.

type UserResponseDto

type UserResponseDto struct {
	UUID       string   `json:"uuid"`
	Name       string   `json:"name"`
	Email      string   `json:"email"`
	Role       UserRole `json:"role"`
	TenantUUID string   `json:"tenant_uuid"`
	Live       bool     `json:"live"`
	CreatedAt  string   `json:"create_at"`
	UpdatedAt  string   `json:"update_at"`
}

UserResponseDto is the user shape returned by the API.

type UserRole

type UserRole string

UserRole represents the access level of a user within the system.

const (
	UserRoleSystemAdmin UserRole = "SYSTEM_ADMIN"
	UserRoleTenantAdmin UserRole = "TENANT_ADMIN"
	UserRoleTenantUser  UserRole = "TENANT_USER"
)

type VisionAICredentialsDTO

type VisionAICredentialsDTO struct {
	Token string `json:"token"`
}

VisionAICredentialsDTO holds the API key for the Google Vision integration.

type VisionOCRFromURLRequest added in v0.0.5

type VisionOCRFromURLRequest struct {
	FileURL string `json:"file_url"`
}

VisionOCRFromURLRequest is the body for the Google Vision OCR endpoint when the image is fetched by the server from a download URL.

type WorkspaceCredits added in v0.0.20

type WorkspaceCredits struct {
	TotalCredits float64 `json:"total_credits"`
	TotalUsage   float64 `json:"total_usage"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL