Help us shape the future of Go! Take the 2026 Go Developer Survey

transport

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 18 Imported by: 0

README

LuckyAgent API

An independent Go module owning LuckyAgent's wire protocols and reusable server transport. Application operations are supplied by the embedding host.

github.com/yurika0211/luckyagent-api

The root package is named transport and provides:

  • HTTP defaults, a typed route-handler catalog and server construction.
  • Header-based API-key authentication, local-only behavior when no key is configured, an optional host-owned pairing-key validator, CORS, rate limiting, panic recovery and request logging.
  • JSON/error responses and SSE error framing with flushing support.
  • websocket: wire messages, clients, session broadcast, keepalive, connection management, durable run storage and reconnect replay. The host executes runs.
  • resources: task/tree/feedback, approvals, cron, autonomy, Skill installation and collaboration controllers, using injected public orchestration/tool ports. Cron list stays GET /api/v1/cron. Create is POST /api/v1/cron; pause, resume, get and delete use /api/v1/cron/{id}. Writes call the host CronJobWriter port so this module never builds the runnable task itself.
  • health: health check registration and reports.
  • grpc: protobuf messages, client, service contract and gateway registration.
  • workflow: optional Gin handlers over the public tool-module DAG engine; the DAG implementation does not depend on Gin or the API module.

See WebSocket run recovery for startup scanning, lazy event loading and recovery compatibility.

It never imports the LuckyAgent runtime. The luckyagent-gateway/turn package supplies shared neutral event/usage DTOs; importing it does not compile every platform adapter.

Embed transport in a Go application

package main

import (
    "net/http"

    transport "github.com/yurika0211/luckyagent-api"
)

func main() {
    cfg := transport.DefaultConfig()
    limiter := transport.NewLimiter(cfg.RateLimit)
    defer limiter.Stop()
    policy := transport.NewMiddleware(cfg, limiter, nil, nil)
    mux := http.NewServeMux()
    mux.HandleFunc("/api/v1/health/live", func(w http.ResponseWriter, r *http.Request) {
        transport.SendJSON(w, http.StatusOK, map[string]string{"status": "ok"})
    })
    handler := policy.Log(policy.Protect(mux))
    if err := transport.NewHTTPServer(cfg.Addr, handler).ListenAndServe(); err != nil {
        panic(err)
    }
}

Hosts exposing the complete LuckyAgent API use RegisterRoutes with the typed Handlers structure. Each supplied callback implements an application operation. resources.New accepts a Runtime composed of task, approval, cron, autonomy and Skill ports, plus optional collaboration managers and host policy hooks. Its methods can be passed directly to the corresponding route fields. JSON/error writers default to this module's standard responses. The host owns storage opening, Agent execution, configuration checks and orchestrator session provisioning. NewHTTPServer does not start a goroutine: the host owns listening, resource cleanup and graceful shutdown.

Task, collaboration and autonomy engines now come from the independent luckyagent-orchestrator module. HTTP contracts stay here. See orchestration resource adapters for migration details and the v0.1.0 engine dependency.

Compatibility and tests

Use Middleware.Protect for the complete admission, authentication, credential quota and request-body policy. Logging and optional CORS wrap that handler. The lower-level middleware methods remain available for existing embedders. See HTTP and realtime reliability for local authentication, body limits, atomic request acceptance, event replay and journal compatibility.

workflow.NewServerHandlers accepts a luckyagent-tools/workflow.WorkflowEngine whose executor is configured by the host. RegisterRoutes preserves the /workflows and /workflow-instances paths, methods and JSON fields. The root transport package does not import Gin. The host retains action registration, authentication, listening and shutdown ownership.

This adapter uses execution packages introduced after tools v0.2.2. For joint changes, publish the orchestrator first, then tools and API, and pin their merged commits or releases before upgrading the host. The committed module requirement includes the workflow package and contains no local filesystem replacement. A workspace is optional for joint development.

HTTP paths, JSON field names, WebSocket event names, protobuf field numbers and the gRPC wire service name luckyagent.LuckyAgentService are preserved. Generated Go clients and descriptors use this module's import path. Protocol sources and their generator are in proto/; regenerate and version them here, rather than keeping a second schema in the embedding application.

go test ./...

Tests cover authentication, CORS, SSE flushing, recovery, rate limiting, WebSocket keepalive/disconnect behavior, protobuf identity, and the absence of LuckyAgent runtime imports. Application-level API tests live in the luckyagent-app module's apiapp and channelapp/websocket packages.

During local extraction, use an untracked go.work with all module roots (adjust these paths to the actual checkout locations):

go work init . ../luckyagent-gateway ../luckyagent-tools ../luckyagent-orchestrator

The committed go.mod pins published dependency versions and contains no local replacement. Downstream builds use GOWORK=off; workspaces are only needed for local changes. The extraction retains the MIT license and attribution from LuckyAgent.

Documentation

Overview

Package transport owns the HTTP, SSE, WebSocket and gRPC wire boundary. Application operations are supplied by the embedding runtime.

Index

Constants

View Source
const (
	// DefaultJSONBodyLimit applies to client JSON, including inline attachments.
	DefaultJSONBodyLimit int64 = 2 << 20
	// Multipart upload handlers may enforce a smaller limit of their own.
	DefaultUploadBodyLimit int64 = 64 << 20
)

Variables

This section is empty.

Functions

func CredentialBucketKey added in v0.2.3

func CredentialBucketKey(credential string) string

CredentialBucketKey groups requests by credential without retaining the credential itself in limiter maps. A shared key intentionally shares quota.

func DecodeJSON added in v0.2.3

func DecodeJSON(w http.ResponseWriter, r *http.Request, dst any, maxBytes int64) error

DecodeJSON reads exactly one JSON value within maxBytes. Empty bodies return io.EOF so optional-body endpoints can retain their existing behavior.

func DispatchMethod

func DispatchMethod(w http.ResponseWriter, r *http.Request, handlers map[string]func()) bool

func NewHTTPServer

func NewHTTPServer(addr string, handler http.Handler) *http.Server

NewHTTPServer preserves the existing streaming-friendly listener timeouts.

func PublicServerURL

func PublicServerURL(addr string) string

PublicServerURL turns a bound listener address into a URL a person can open. Wildcard binds stay on localhost instead of printing "localhost127.0.0.1:9090".

func RegisterRoutes

func RegisterRoutes(mux *http.ServeMux, h Handlers)

func RemoteIP

func RemoteIP(remoteAddr string) string

RemoteIP strips the transport port from RemoteAddr and handles both bracketed and unbracketed IPv6 addresses.

func SendError

func SendError(w http.ResponseWriter, message string, code int, details string)

func SendJSON

func SendJSON(w http.ResponseWriter, status int, data any)

func SendRequestError added in v0.2.3

func SendRequestError(w http.ResponseWriter, err error)

SendRequestError maps decoding failures into the common JSON error envelope.

func SendSSEError

func SendSSEError(w io.Writer, flusher http.Flusher, message string)

Types

type Config

type Config struct {
	Addr        string   `yaml:"addr,omitempty"`         // 监听地址,默认 :9090
	APIKeys     []string `yaml:"api_keys,omitempty"`     // API Key 白名单(空=仅允许经过校验的本机请求)
	EnableCORS  bool     `yaml:"enable_cors,omitempty"`  // 启用 CORS,默认 false
	CORSOrigins []string `yaml:"cors_origins,omitempty"` // CORS 允许的源
	RateLimit   int      `yaml:"rate_limit,omitempty"`   // 每分钟请求限制,默认 60
	MetricsAddr string   `yaml:"metrics_addr,omitempty"` // Prometheus metrics 独立端口(空=复用主端口)
	LogLevel    string   `yaml:"log_level,omitempty"`    // 日志级别: debug, info, warn, error
	LogFormat   string   `yaml:"log_format,omitempty"`   // 日志格式: json, text
}

Config API Server 配置

func DefaultConfig

func DefaultConfig() Config

DefaultConfig 返回默认配置

type ErrorResponse

type ErrorResponse struct {
	Error     string `json:"error"`
	Code      int    `json:"code"`
	Details   string `json:"details,omitempty"`
	ErrorCode string `json:"error_code,omitempty"`
	RequestID string `json:"request_id,omitempty"`
}

ErrorResponse 错误响应

type Handlers

type Handlers struct {
	HealthLiveness       http.HandlerFunc
	HealthReadiness      http.HandlerFunc
	HealthDetail         http.HandlerFunc
	Metrics              http.HandlerFunc
	ConfigReload         http.HandlerFunc
	ConfigSchema         http.HandlerFunc
	Config               http.HandlerFunc
	Models               http.HandlerFunc
	ModelEffort          http.HandlerFunc
	ModelSwitch          http.HandlerFunc
	ModelProfiles        http.HandlerFunc
	Approvals            http.HandlerFunc
	Chat                 http.HandlerFunc
	ChatSync             http.HandlerFunc
	Sessions             http.HandlerFunc
	SessionByID          http.HandlerFunc
	Uploads              http.HandlerFunc
	Artifact             http.HandlerFunc
	Commands             http.HandlerFunc
	Cron                 http.HandlerFunc
	CronByID             http.HandlerFunc
	Tasks                http.HandlerFunc
	TaskByID             http.HandlerFunc
	AutonomyDashboard    http.HandlerFunc
	AutonomyTaskByID     http.HandlerFunc
	Memory               http.HandlerFunc
	MemoryRecall         http.HandlerFunc
	MemoryRecallTrace    http.HandlerFunc
	MemoryStats          http.HandlerFunc
	MemoryGraph          http.HandlerFunc
	ProactiveStatus      http.HandlerFunc
	Tools                http.HandlerFunc
	Skills               http.HandlerFunc
	SkillRoutes          http.HandlerFunc
	Stats                http.HandlerFunc
	Soul                 http.HandlerFunc
	Context              http.HandlerFunc
	ContextFit           http.HandlerFunc
	RAGIndex             http.HandlerFunc
	RAGSearch            http.HandlerFunc
	RAGStats             http.HandlerFunc
	RAGStore             http.HandlerFunc
	RAGStreamWatch       http.HandlerFunc
	RAGStreamScan        http.HandlerFunc
	RAGStreamStart       http.HandlerFunc
	RAGStreamStop        http.HandlerFunc
	RAGStreamStatus      http.HandlerFunc
	RAGStreamIndex       http.HandlerFunc
	RAGStreamQueue       http.HandlerFunc
	RAGStreamProcess     http.HandlerFunc
	FunctionCalling      http.HandlerFunc
	FCTools              http.HandlerFunc
	FCHistory            http.HandlerFunc
	WebSocket            http.HandlerFunc
	WSStats              http.HandlerFunc
	SoulTemplates        http.HandlerFunc
	SoulTemplateByID     http.HandlerFunc
	EmbedderList         http.HandlerFunc
	EmbedderRegister     http.HandlerFunc
	EmbedderSwitch       http.HandlerFunc
	EmbedderRoutes       http.HandlerFunc
	AgentsList           http.HandlerFunc
	AgentsRegister       http.HandlerFunc
	AgentsDeregister     http.HandlerFunc
	AgentsDelegate       http.HandlerFunc
	AgentsTask           http.HandlerFunc
	AgentsTasks          http.HandlerFunc
	AgentsCancel         http.HandlerFunc
	AgentsBlackboard     http.HandlerFunc
	AgentsMessages       http.HandlerFunc
	Workflows            http.HandlerFunc
	WorkflowByID         http.HandlerFunc
	WorkflowInstances    http.HandlerFunc
	WorkflowInstanceByID http.HandlerFunc
	GatewaysList         http.HandlerFunc
	GatewayTelegramStart http.HandlerFunc
	GatewayByName        http.HandlerFunc
	Root                 http.HandlerFunc
}

Handlers are host operations; paths and registration are owned by this module.

type Limiter

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

func NewLimiter

func NewLimiter(limit int) *Limiter

func (*Limiter) Allow

func (rl *Limiter) Allow(ip string) bool

func (*Limiter) Stop

func (rl *Limiter) Stop()

type Middleware

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

Middleware holds transport policy without depending on the host runtime.

func NewMiddleware

func NewMiddleware(config Config, limiter *Limiter, pairingKeyValid func(string) bool, onPanic func()) *Middleware

NewMiddleware accepts optional host-owned pairing and panic-accounting hooks.

func (*Middleware) Authenticate

func (s *Middleware) Authenticate(next http.Handler) http.Handler

authMiddleware API Key 认证中间件

func (*Middleware) CORS

func (s *Middleware) CORS(next http.Handler) http.Handler

corsMiddleware CORS 中间件

func (*Middleware) Log

func (s *Middleware) Log(next http.Handler) http.Handler

loggingMiddleware 日志中间件

func (*Middleware) Protect added in v0.2.3

func (s *Middleware) Protect(next http.Handler) http.Handler

Protect is the complete HTTP policy. Hosts should wrap it with logging and their optional CORS middleware, without adding Authenticate/RateLimit again. Independent, generous per-peer admission limits protect authentication; the business limit is per credential, with public probes in a separate IP bucket.

func (*Middleware) RateLimit

func (s *Middleware) RateLimit(next http.Handler) http.Handler

rateLimitMiddleware 限流中间件

func (*Middleware) Recover

func (s *Middleware) Recover(next http.Handler) http.Handler

recoveryMiddleware 恢复中间件

type RequestError added in v0.2.3

type RequestError struct {
	Status  int
	Message string
}

RequestError contains only a public message, never the submitted body or key.

func (*RequestError) Error added in v0.2.3

func (e *RequestError) Error() string

Directories

Path Synopsis
Package luckyagent is a reverse proxy.
Package luckyagent is a reverse proxy.
Package resources serves optional tool-runtime HTTP resources through host-supplied ports.
Package resources serves optional tool-runtime HTTP resources through host-supplied ports.

Jump to

Keyboard shortcuts

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