feat(project): 项目完结

This commit is contained in:
peakxy
2026-05-30 23:16:49 +08:00
commit 60e7777cbd
97 changed files with 15027 additions and 0 deletions

View File

@@ -0,0 +1,150 @@
// Package bootstrap wires application config, armory assembly, chat service,
// and Gin HTTP routes into a single runnable engine.
package bootstrap
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"ai-agent-scaffold-go/internal/app/config"
"ai-agent-scaffold-go/internal/domain/agent/model"
"ai-agent-scaffold-go/internal/domain/agent/ports"
"ai-agent-scaffold-go/internal/domain/agent/service/armory"
"ai-agent-scaffold-go/internal/domain/agent/service/armory/factory"
"ai-agent-scaffold-go/internal/domain/agent/service/chat"
"ai-agent-scaffold-go/internal/infrastructure/adk"
"ai-agent-scaffold-go/internal/infrastructure/ai"
httptrigger "ai-agent-scaffold-go/internal/trigger/http"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
type Engine struct {
Application config.Application
Router *gin.Engine
ChatService *chat.Service
Registry ports.AgentRegistry
Sessions ports.SessionStore
Logger *zap.Logger
}
func Build(ctx context.Context, appCfg config.Application, logger *zap.Logger) (*Engine, error) {
tables, err := loadAgentTables(appCfg.Agent.ConfigPaths)
if err != nil {
return nil, err
}
if len(tables) == 0 {
return nil, fmt.Errorf("no agent tables loaded; configure agent.config-paths")
}
llmTimeout, err := appCfg.LLM.RequestTimeoutDuration()
if err != nil {
return nil, err
}
registry := ports.NewInMemoryAgentRegistry()
sessions := ports.NewInMemorySessionStore()
modelProvider := ai.NewEinoProvider().WithRequestTimeout(llmTimeout)
toolRouter := ai.NewMCPToolRouter()
mcpFactory := ai.NewToolFactory(toolRouter)
skillFactory := ai.NewSkillFactory()
agentFactory := adk.NewFactory()
agentFactory.UseToolRouter(toolRouter)
runnerFactory := agentFactory
armoryFactory := factory.NewDefaultFactory(modelProvider, mcpFactory, skillFactory, agentFactory, runnerFactory, registry)
armoryService := armory.NewService(armoryFactory.ArmoryStrategyHandler())
if err := armoryService.AcceptArmoryAgents(ctx, tables); err != nil {
return nil, fmt.Errorf("armory assembly: %w", err)
}
chatService := chat.NewService(registry, sessions)
router := newRouter(appCfg.App.Env)
httptrigger.RegisterAgentRoutes(router, chatService)
if logger != nil {
logger.Info("agents registered", zap.Int("count", len(registry.List())), zap.Duration("llm_request_timeout", llmTimeout))
}
return &Engine{
Application: appCfg,
Router: router,
ChatService: chatService,
Registry: registry,
Sessions: sessions,
Logger: logger,
}, nil
}
func (e *Engine) Run() error {
addr := e.Application.Server.Addr
if addr == "" {
addr = ":8091"
}
if e.Logger != nil {
e.Logger.Info("http server listening", zap.String("addr", addr))
}
return e.Router.Run(addr)
}
func newRouter(env string) *gin.Engine {
if env == "prod" || env == "production" {
gin.SetMode(gin.ReleaseMode)
}
router := gin.New()
router.Use(gin.Recovery())
if env != "prod" && env != "production" {
router.Use(gin.Logger())
}
router.Use(corsMiddleware())
router.GET("/healthz", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
return router
}
func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.GetHeader("Origin")
if origin != "" {
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Vary", "Origin")
} else {
c.Header("Access-Control-Allow-Origin", "*")
}
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
c.Header("Access-Control-Allow-Credentials", "true")
if c.Request.Method == http.MethodOptions {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}
func loadAgentTables(paths []string) (map[string]model.AiAgentConfigTable, error) {
merged := make(map[string]model.AiAgentConfigTable)
for _, raw := range paths {
path := strings.TrimSpace(raw)
if path == "" {
continue
}
expanded := os.ExpandEnv(path)
tables, err := config.LoadAgentTablesFile(expanded)
if err != nil {
return nil, err
}
for name, table := range tables {
merged[name] = table
}
}
return merged, nil
}

View File

@@ -0,0 +1,88 @@
package config
import (
"fmt"
"os"
"time"
"gopkg.in/yaml.v3"
)
type Application struct {
App AppSection `yaml:"app"`
Server ServerSection `yaml:"server"`
Database DatabaseSection `yaml:"database"`
Redis RedisSection `yaml:"redis"`
Agent AgentSection `yaml:"agent"`
LLM LLMSection `yaml:"llm"`
}
type AppSection struct {
Name string `yaml:"name"`
Env string `yaml:"env"`
}
type ServerSection struct {
Addr string `yaml:"addr"`
}
type DatabaseSection struct {
Required bool `yaml:"required"`
DSN string `yaml:"dsn"`
}
type RedisSection struct {
Required bool `yaml:"required"`
Addr string `yaml:"addr"`
Password string `yaml:"password"`
DB int `yaml:"db"`
}
type AgentSection struct {
ConfigPaths []string `yaml:"config-paths"`
}
type LLMSection struct {
RequestTimeout string `yaml:"request-timeout"`
}
const defaultLLMRequestTimeout = 5 * time.Minute
func (s LLMSection) RequestTimeoutDuration() (time.Duration, error) {
raw := ""
if s.RequestTimeout != "" {
raw = s.RequestTimeout
}
if raw == "" {
return defaultLLMRequestTimeout, nil
}
d, err := time.ParseDuration(raw)
if err != nil {
return 0, fmt.Errorf("invalid llm.request-timeout %q: %w", raw, err)
}
if d <= 0 {
return 0, fmt.Errorf("llm.request-timeout must be positive, got %q", raw)
}
return d, nil
}
func LoadApplication(path string) (Application, error) {
data, err := os.ReadFile(path)
if err != nil {
return Application{}, fmt.Errorf("read application config %s: %w", path, err)
}
var app Application
if err := yaml.Unmarshal(data, &app); err != nil {
return Application{}, fmt.Errorf("parse application config: %w", err)
}
if app.Server.Addr == "" {
app.Server.Addr = ":8091"
}
if app.App.Env == "" {
app.App.Env = "local"
}
if _, err := app.LLM.RequestTimeoutDuration(); err != nil {
return Application{}, err
}
return app, nil
}

View File

@@ -0,0 +1,186 @@
package config
import (
"fmt"
"os"
"regexp"
"strings"
"ai-agent-scaffold-go/internal/domain/agent/model"
"gopkg.in/yaml.v3"
)
type agentRoot struct {
AI struct {
Agent struct {
Config struct {
Tables map[string]model.AiAgentConfigTable `yaml:"tables"`
} `yaml:"config"`
} `yaml:"agent"`
} `yaml:"ai"`
}
func LoadAgentTables(data []byte) (map[string]model.AiAgentConfigTable, error) {
expanded := expandEnvPlaceholders(string(data))
var root agentRoot
if err := yaml.Unmarshal([]byte(expanded), &root); err != nil {
return nil, fmt.Errorf("parse agent config: %w", err)
}
tables := root.AI.Agent.Config.Tables
if len(tables) == 0 {
return nil, fmt.Errorf("agent config tables are required")
}
for name, table := range tables {
normalizeDefaults(&table)
if err := validateTable(name, table); err != nil {
return nil, err
}
tables[name] = table
}
return tables, nil
}
func LoadAgentTablesFile(path string) (map[string]model.AiAgentConfigTable, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read agent config %s: %w", path, err)
}
return LoadAgentTables(data)
}
var envPlaceholderRE = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}`)
// expandEnvPlaceholders replaces ${VAR} and ${VAR:-default} in YAML text using
// the current process environment. It deliberately ignores bare $NAME forms so
// dollar signs that happen to appear inside instructions or URLs are not
// mangled.
func expandEnvPlaceholders(input string) string {
return envPlaceholderRE.ReplaceAllStringFunc(input, func(match string) string {
groups := envPlaceholderRE.FindStringSubmatch(match)
name := groups[1]
if value, ok := os.LookupEnv(name); ok && value != "" {
return value
}
if len(groups) > 2 {
return groups[2]
}
return ""
})
}
func normalizeDefaults(table *model.AiAgentConfigTable) {
if table.Module.AiAPI.CompletionsPath == "" {
table.Module.AiAPI.CompletionsPath = "v1/chat/completions"
}
if table.Module.AiAPI.EmbeddingsPath == "" {
table.Module.AiAPI.EmbeddingsPath = "v1/embeddings"
}
for i := range table.Module.ChatModel.ToolSkillsList {
if table.Module.ChatModel.ToolSkillsList[i].Type == "" {
table.Module.ChatModel.ToolSkillsList[i].Type = "directory"
}
}
for i := range table.Module.AgentWorkflows {
if table.Module.AgentWorkflows[i].MaxIterations == 0 {
table.Module.AgentWorkflows[i].MaxIterations = 3
}
}
}
func validateTable(name string, table model.AiAgentConfigTable) error {
prefix := "agent table " + name
required := map[string]string{
"app-name": table.AppName,
"agent.agent-id": table.Agent.AgentID,
"module.ai-api.base-url": table.Module.AiAPI.BaseURL,
"module.ai-api.api-key": table.Module.AiAPI.APIKey,
"module.chat-model.model": table.Module.ChatModel.Model,
"module.runner.agent-name": table.Module.Runner.AgentName,
}
for field, value := range required {
if strings.TrimSpace(value) == "" {
return fmt.Errorf("%s: %s is required", prefix, field)
}
}
if len(table.Module.Agents) == 0 {
return fmt.Errorf("%s: module.agents is required", prefix)
}
for i, agent := range table.Module.Agents {
if strings.TrimSpace(agent.Name) == "" {
return fmt.Errorf("%s: module.agents[%d].name is required", prefix, i)
}
if strings.TrimSpace(agent.Instruction) == "" {
return fmt.Errorf("%s: module.agents[%d].instruction is required", prefix, i)
}
}
for i, workflow := range table.Module.AgentWorkflows {
switch workflow.Type {
case model.WorkflowTypeLoop, model.WorkflowTypeParallel, model.WorkflowTypeSequential:
default:
return fmt.Errorf("%s: module.agent-workflows[%d].type is invalid: %s", prefix, i, workflow.Type)
}
if strings.TrimSpace(workflow.Name) == "" {
return fmt.Errorf("%s: module.agent-workflows[%d].name is required", prefix, i)
}
}
for i, tool := range table.Module.ChatModel.ToolMCPList {
if err := validateMCPEntry(prefix, i, tool); err != nil {
return err
}
}
return nil
}
func validateMCPEntry(prefix string, index int, tool model.ToolMCPConfig) error {
fieldPrefix := fmt.Sprintf("%s: module.chat-model.tool-mcp-list[%d]", prefix, index)
count := 0
if tool.Local != nil {
count++
}
if tool.SSE != nil {
count++
}
if tool.Stdio != nil {
count++
}
switch count {
case 0:
return fmt.Errorf("%s must define exactly one of local, sse, or stdio", fieldPrefix)
case 1:
default:
return fmt.Errorf("%s cannot define multiple transport types", fieldPrefix)
}
if tool.Local != nil {
if strings.TrimSpace(tool.Local.Name) == "" {
return fmt.Errorf("%s.local.name is required", fieldPrefix)
}
}
if tool.SSE != nil {
if strings.TrimSpace(tool.SSE.Name) == "" {
return fmt.Errorf("%s.sse.name is required", fieldPrefix)
}
if strings.TrimSpace(tool.SSE.BaseURI) == "" {
return fmt.Errorf("%s.sse.base-uri is required", fieldPrefix)
}
if tool.SSE.RequestTimeout < 0 {
return fmt.Errorf("%s.sse.request-timeout must be positive", fieldPrefix)
}
}
if tool.Stdio != nil {
if strings.TrimSpace(tool.Stdio.Name) == "" {
return fmt.Errorf("%s.stdio.name is required", fieldPrefix)
}
if strings.TrimSpace(tool.Stdio.ServerParameters.Command) == "" {
return fmt.Errorf("%s.stdio.server-parameters.command is required", fieldPrefix)
}
if tool.Stdio.RequestTimeout < 0 {
return fmt.Errorf("%s.stdio.request-timeout must be positive", fieldPrefix)
}
}
return nil
}

2
internal/app/doc.go Normal file
View File

@@ -0,0 +1,2 @@
// Package app wires configuration, application services, and infrastructure.
package app