agent

package
v1.4.6 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrProviderNotSet = NewError(types.ErrProviderNotSet, "LLM provider not configured")
	ErrAgentNotReady  = NewError(types.ErrAgentNotReady, "agent not in ready state")
	ErrAgentBusy      = NewError(types.ErrAgentBusy, "agent is busy executing another task")
)

Functions

func CanTransition

func CanTransition(from, to State) bool

CanTransition 检查状态转换是否合法。

func DurationPtr

func DurationPtr(d time.Duration) *time.Duration

DurationPtr returns a pointer to the given time.Duration.

func Float32Ptr

func Float32Ptr(f float32) *float32

Float32Ptr returns a pointer to the given float32.

func GetErrorCode

func GetErrorCode(err error) types.ErrorCode

GetErrorCode 从错误中提取错误码。

func InitGlobalRegistry

func InitGlobalRegistry(logger *zap.Logger)

Init Global Registry将全球代理登记初始化。 此函数可以安全多次调用 - 只有第一个调用会初始化 。

func IntPtr

func IntPtr(i int) *int

IntPtr returns a pointer to the given int.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable 判断错误是否可重试。

func StringPtr

func StringPtr(s string) *string

StringPtr returns a pointer to the given string.

func WithRunConfig

func WithRunConfig(ctx context.Context, rc *RunConfig) context.Context

WithRunConfig stores a RunConfig in the context.

func WithRuntimeStreamEmitter

func WithRuntimeStreamEmitter(ctx context.Context, emit RuntimeStreamEmitter) context.Context

Types

type Agent

type Agent interface {
	// 身份标识
	ID() string
	Name() string
	Type() AgentType

	// 生命周期
	State() State
	Init(ctx context.Context) error
	Teardown(ctx context.Context) error

	// 核心执行
	Plan(ctx context.Context, input *Input) (*PlanResult, error)
	Execute(ctx context.Context, input *Input) (*Output, error)
	Observe(ctx context.Context, feedback *Feedback) error
}

Agent 定义核心行为接口

func CreateAgent

func CreateAgent(
	config types.AgentConfig,
	provider llm.Provider,
	memory MemoryManager,
	toolManager ToolManager,
	bus EventBus,
	logger *zap.Logger,
) (Agent, error)

Create Agent 使用全球登记册创建代理

type AgentBuilder

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

AgentBuilder 提供流式构建 Agent 的能力 支持链式调用,简化 Agent 创建过程

func NewAgentBuilder

func NewAgentBuilder(config types.AgentConfig) *AgentBuilder

NewAgentBuilder 创建 Agent 构建器

func (*AgentBuilder) Build

func (b *AgentBuilder) Build() (*BaseAgent, error)

Build 构建 Agent 实例

func (*AgentBuilder) Orchestrator added in v1.2.0

func (b *AgentBuilder) Orchestrator() OrchestratorRunner

Orchestrator returns the configured orchestrator runner (may be nil).

func (*AgentBuilder) ReasoningRegistry added in v1.2.0

func (b *AgentBuilder) ReasoningRegistry() *reasoning.PatternRegistry

ReasoningRegistry returns the configured reasoning pattern registry (may be nil).

func (*AgentBuilder) Validate

func (b *AgentBuilder) Validate() error

Validate 验证配置是否有效

func (*AgentBuilder) WithConversationStore added in v1.1.0

func (b *AgentBuilder) WithConversationStore(store ConversationStoreProvider) *AgentBuilder

WithConversationStore sets the conversation store for persisting chat history.

func (*AgentBuilder) WithDefaultEnhancedMemory

func (b *AgentBuilder) WithDefaultEnhancedMemory(config *memory.EnhancedMemoryConfig) *AgentBuilder

通过DefaultEnhancedMemory,可以使内置增强的内存系统与内存存储相通.

func (*AgentBuilder) WithDefaultLSPServer

func (b *AgentBuilder) WithDefaultLSPServer(name, version string) *AgentBuilder

WithDefaultLSPServer 启用默认名称/版本的内置 LSP 运行时。

func (*AgentBuilder) WithDefaultMCPServer

func (b *AgentBuilder) WithDefaultMCPServer(name, version string) *AgentBuilder

With DefaultMCPServer 启用默认名称/版本的内置的MCP服务器.

func (*AgentBuilder) WithDefaultSkills

func (b *AgentBuilder) WithDefaultSkills(directory string, config *skills.SkillManagerConfig) *AgentBuilder

With DefaultSkills 启用了内置的技能管理器,并可以选择扫描一个目录.

func (*AgentBuilder) WithEnhancedMemory

func (b *AgentBuilder) WithEnhancedMemory(mem EnhancedMemoryRunner) *AgentBuilder

WithEnhancedMemory 启用增强记忆系统

func (*AgentBuilder) WithEventBus

func (b *AgentBuilder) WithEventBus(bus EventBus) *AgentBuilder

WithEventBus 设置事件总线

func (*AgentBuilder) WithLSP

func (b *AgentBuilder) WithLSP(client LSPClientRunner) *AgentBuilder

WithLSP 启用 LSP 集成。

func (*AgentBuilder) WithLSPWithLifecycle added in v1.0.0

func (b *AgentBuilder) WithLSPWithLifecycle(client LSPClientRunner, lifecycle LSPLifecycleOwner) *AgentBuilder

WithLSPWithLifecycle 启用 LSP 集成,并注册可选生命周期对象。

func (*AgentBuilder) WithLogger

func (b *AgentBuilder) WithLogger(logger *zap.Logger) *AgentBuilder

WithLogger 设置日志器

func (*AgentBuilder) WithMCP

func (b *AgentBuilder) WithMCP(server MCPServerRunner) *AgentBuilder

WithMCP 启用 MCP 集成

func (*AgentBuilder) WithMaxReActIterations

func (b *AgentBuilder) WithMaxReActIterations(n int) *AgentBuilder

WithMaxReActIterations 设置 ReAct 最大迭代次数。 n <= 0 时忽略,使用默认值 10。

func (*AgentBuilder) WithMemory

func (b *AgentBuilder) WithMemory(memory MemoryManager) *AgentBuilder

WithMemory 设置记忆管理器

func (*AgentBuilder) WithObservability

func (b *AgentBuilder) WithObservability(obs ObservabilityRunner) *AgentBuilder

WithObservability 启用可观测性系统

func (*AgentBuilder) WithOrchestrator added in v1.2.0

func (b *AgentBuilder) WithOrchestrator(orchestrator OrchestratorRunner) *AgentBuilder

WithOrchestrator sets the orchestration runner for multi-agent coordination.

func (*AgentBuilder) WithPromptEnhancer

func (b *AgentBuilder) WithPromptEnhancer(config *PromptEnhancerConfig) *AgentBuilder

WithPromptEnhancer 启用提示词增强

func (*AgentBuilder) WithPromptStore added in v1.1.0

func (b *AgentBuilder) WithPromptStore(store PromptStoreProvider) *AgentBuilder

WithPromptStore sets the prompt store for loading prompts from MongoDB.

func (*AgentBuilder) WithProvider

func (b *AgentBuilder) WithProvider(provider llm.Provider) *AgentBuilder

WithProvider 设置 LLM Provider

func (*AgentBuilder) WithReasoning added in v1.2.0

func (b *AgentBuilder) WithReasoning(registry *reasoning.PatternRegistry) *AgentBuilder

WithReasoning sets the reasoning pattern registry for advanced reasoning strategies.

func (*AgentBuilder) WithReflection

func (b *AgentBuilder) WithReflection(config *ReflectionExecutorConfig) *AgentBuilder

WithReflection 启用 Reflection 机制

func (*AgentBuilder) WithRunStore added in v1.1.0

func (b *AgentBuilder) WithRunStore(store RunStoreProvider) *AgentBuilder

WithRunStore sets the run store for recording execution logs.

func (*AgentBuilder) WithSkills

func (b *AgentBuilder) WithSkills(discoverer SkillDiscoverer) *AgentBuilder

WithSkills 启用 Skills 系统

func (*AgentBuilder) WithToolManager

func (b *AgentBuilder) WithToolManager(toolManager ToolManager) *AgentBuilder

WithToolManager 设置工具管理器

func (*AgentBuilder) WithToolProvider

func (b *AgentBuilder) WithToolProvider(provider llm.Provider) *AgentBuilder

WithToolProvider 设置工具调用专用的 LLM Provider。 ReAct 循环中的推理和工具调用将使用此 Provider,而最终内容生成仍使用主 Provider。 如果不设置,所有调用都使用主 Provider。

func (*AgentBuilder) WithToolSelection

func (b *AgentBuilder) WithToolSelection(config *ToolSelectionConfig) *AgentBuilder

WithToolSelection 启用动态工具选择

type AgentFactory

type AgentFactory func(
	config types.AgentConfig,
	provider llm.Provider,
	memory MemoryManager,
	toolManager ToolManager,
	bus EventBus,
	logger *zap.Logger,
) (Agent, error)

Agent Factory 是创建 Agent 实例的函数

type AgentRegistry

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

Agent Registry 管理代理类型注册和创建 它提供了一种集中的方式 注册和即时处理不同的代理类型

var (
	GlobalRegistry *AgentRegistry
)

Global Registry 是默认代理注册实例

func NewAgentRegistry

func NewAgentRegistry(logger *zap.Logger) *AgentRegistry

新建代理注册

func (*AgentRegistry) Create

func (r *AgentRegistry) Create(
	config types.AgentConfig,
	provider llm.Provider,
	memory MemoryManager,
	toolManager ToolManager,
	bus EventBus,
	logger *zap.Logger,
) (Agent, error)

创建指定类型的新代理实例

func (*AgentRegistry) IsRegistered

func (r *AgentRegistry) IsRegistered(agentType AgentType) bool

如果已注册代理类型, 正在注册检查

func (*AgentRegistry) ListTypes

func (r *AgentRegistry) ListTypes() []AgentType

列表类型返回所有已注册代理类型

func (*AgentRegistry) Register

func (r *AgentRegistry) Register(agentType AgentType, factory AgentFactory)

登记册登记具有工厂功能的新代理类型

func (*AgentRegistry) Unregister

func (r *AgentRegistry) Unregister(agentType AgentType)

未注册从注册簿中删除代理类型

type AgentRunCompleteEvent added in v1.4.6

type AgentRunCompleteEvent struct {
	AgentID_         string
	TraceID          string
	RunID            string
	ParentRunID      string
	LatencyMs        int64
	PromptTokens     int
	CompletionTokens int
	TotalTokens      int
	Cost             float64
	Timestamp_       time.Time
}

AgentRunCompleteEvent Agent 运行完成事件。

func (*AgentRunCompleteEvent) Timestamp added in v1.4.6

func (e *AgentRunCompleteEvent) Timestamp() time.Time

func (*AgentRunCompleteEvent) Type added in v1.4.6

func (e *AgentRunCompleteEvent) Type() EventType

type AgentRunErrorEvent added in v1.4.6

type AgentRunErrorEvent struct {
	AgentID_    string
	TraceID     string
	RunID       string
	ParentRunID string
	LatencyMs   int64
	Error       string
	Timestamp_  time.Time
}

AgentRunErrorEvent Agent 运行失败事件。

func (*AgentRunErrorEvent) Timestamp added in v1.4.6

func (e *AgentRunErrorEvent) Timestamp() time.Time

func (*AgentRunErrorEvent) Type added in v1.4.6

func (e *AgentRunErrorEvent) Type() EventType

type AgentRunStartEvent added in v1.4.6

type AgentRunStartEvent struct {
	AgentID_    string
	TraceID     string
	RunID       string
	ParentRunID string
	Timestamp_  time.Time
}

AgentRunStartEvent Agent 运行开始事件。

func (*AgentRunStartEvent) Timestamp added in v1.4.6

func (e *AgentRunStartEvent) Timestamp() time.Time

func (*AgentRunStartEvent) Type added in v1.4.6

func (e *AgentRunStartEvent) Type() EventType

type AgentTool

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

AgentTool wraps an Agent instance as a callable tool, enabling lightweight agent-to-agent delegation via the standard tool-calling interface.

func NewAgentTool

func NewAgentTool(agent Agent, config *AgentToolConfig) *AgentTool

NewAgentTool creates an AgentTool that wraps the given Agent. If config is nil, defaults are used.

func (*AgentTool) Agent

func (at *AgentTool) Agent() Agent

Agent returns the underlying Agent instance.

func (*AgentTool) Execute

func (at *AgentTool) Execute(ctx context.Context, call types.ToolCall) llmtools.ToolResult

Execute handles a ToolCall by delegating to the wrapped Agent.

func (*AgentTool) Name

func (at *AgentTool) Name() string

Name returns the tool name.

func (*AgentTool) Schema

func (at *AgentTool) Schema() types.ToolSchema

Schema returns the ToolSchema describing this agent-as-tool.

type AgentToolConfig

type AgentToolConfig struct {
	// Name overrides the default tool name (default: "agent_<agent.Name()>".
	Name string

	// Description overrides the agent's description in the tool schema.
	Description string

	// Timeout limits the agent execution time. Zero means no extra timeout.
	Timeout time.Duration
}

AgentToolConfig configures how an Agent is exposed as a tool.

type AgentType

type AgentType string

AgentType 定义 Agent 类型 这是一个可扩展的字符串类型,用户可以定义自己的 Agent 类型

const (
	TypeGeneric    AgentType = "generic"    // 通用 Agent
	TypeAssistant  AgentType = "assistant"  // 助手
	TypeAnalyzer   AgentType = "analyzer"   // 分析
	TypeTranslator AgentType = "translator" // 翻译
	TypeSummarizer AgentType = "summarizer" // 摘要
	TypeReviewer   AgentType = "reviewer"   // 审查
)

预定义的常见 Agent 类型(可选使用)

type AsyncExecution

type AsyncExecution struct {
	ID        string
	AgentID   string
	Input     *Input
	StartTime time.Time
	// contains filtered or unexported fields
}

AsyncExecution 异步执行状态

重要:调用者必须调用 Wait() 或从 doneCh 读取结果,否则发送 goroutine 可能因 ctx 取消而丢弃结果,但 doneCh 本身(带 1 缓冲)不会泄漏。 如果不再需要结果,请确保取消传入的 context 以释放相关资源。(T-013)

func (*AsyncExecution) GetEndTime

func (e *AsyncExecution) GetEndTime() time.Time

GetEndTime returns when the execution finished.

func (*AsyncExecution) GetError

func (e *AsyncExecution) GetError() string

GetError returns the error message, if any.

func (*AsyncExecution) GetOutput

func (e *AsyncExecution) GetOutput() *Output

GetOutput returns the execution output, if completed.

func (*AsyncExecution) GetStatus

func (e *AsyncExecution) GetStatus() ExecutionStatus

GetStatus returns the current execution status.

func (*AsyncExecution) Wait

func (e *AsyncExecution) Wait(ctx context.Context) (*Output, error)

Wait 等待执行完成。可安全地被多次调用, 首次调用消费 doneCh 并缓存结果,后续调用直接返回缓存值。

type AsyncExecutor

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

AsyncExecutor 异步 Agent 执行器(基于 Anthropic 2026 标准) 支持异步 Subagent 创建和实时协调

func NewAsyncExecutor

func NewAsyncExecutor(agent Agent, logger *zap.Logger) *AsyncExecutor

NewAsyncExecutor 创建异步执行器

func (*AsyncExecutor) ExecuteAsync

func (e *AsyncExecutor) ExecuteAsync(ctx context.Context, input *Input) (*AsyncExecution, error)

ExecuteAsync 异步执行任务

func (*AsyncExecutor) ExecuteWithSubagents

func (e *AsyncExecutor) ExecuteWithSubagents(ctx context.Context, input *Input, subagents []Agent) (*Output, error)

ExecuteWithSubagents 使用 Subagents 并行执行

type BaseAgent

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

BaseAgent 提供可复用的状态管理、记忆、工具与 LLM 能力

func NewBaseAgent

func NewBaseAgent(
	cfg types.AgentConfig,
	provider llm.Provider,
	memory MemoryManager,
	toolManager ToolManager,
	bus EventBus,
	logger *zap.Logger,
) *BaseAgent

NewBaseAgent 创建基础 Agent

func (*BaseAgent) AddInputValidator

func (b *BaseAgent) AddInputValidator(v guardrails.Validator)

添加自定义输入验证器 1.7: 支持海关验证规则的登记和延期

func (*BaseAgent) AddOutputFilter

func (b *BaseAgent) AddOutputFilter(f guardrails.Filter)

添加 OutputFilter 添加自定义输出过滤器

func (*BaseAgent) AddOutputValidator

func (b *BaseAgent) AddOutputValidator(v guardrails.Validator)

添加输出变量添加自定义输出验证器 1.7: 支持海关验证规则的登记和延期

func (*BaseAgent) ChatCompletion

func (b *BaseAgent) ChatCompletion(ctx context.Context, messages []types.Message) (*llm.ChatResponse, error)

ChatCompletion 调用 LLM 完成对话

func (*BaseAgent) Config

func (b *BaseAgent) Config() types.AgentConfig

Config 返回配置

func (*BaseAgent) ContextEngineEnabled

func (b *BaseAgent) ContextEngineEnabled() bool

ContextEngineEnabled 返回上下文工程是否启用

func (*BaseAgent) EnableEnhancedMemory

func (b *BaseAgent) EnableEnhancedMemory(memorySystem EnhancedMemoryRunner)

EnableEnhancedMemory 启用增强记忆系统

func (*BaseAgent) EnableLSP

func (b *BaseAgent) EnableLSP(client LSPClientRunner)

EnableLSP 启用 LSP 集成。

func (*BaseAgent) EnableLSPWithLifecycle

func (b *BaseAgent) EnableLSPWithLifecycle(client LSPClientRunner, lifecycle LSPLifecycleOwner)

EnableLSPWithLifecycle 启用 LSP,并注册可选生命周期对象(例如 *ManagedLSP)。

func (*BaseAgent) EnableMCP

func (b *BaseAgent) EnableMCP(server MCPServerRunner)

EnableMCP 启用 MCP 集成

func (*BaseAgent) EnableObservability

func (b *BaseAgent) EnableObservability(obsSystem ObservabilityRunner)

EnableObservability 启用可观测性系统

func (*BaseAgent) EnablePromptEnhancer

func (b *BaseAgent) EnablePromptEnhancer(enhancer PromptEnhancerRunner)

EnablePromptEnhancer 启用提示词增强

func (*BaseAgent) EnableReflection

func (b *BaseAgent) EnableReflection(executor ReflectionRunner)

EnableReflection 启用 Reflection 机制

func (*BaseAgent) EnableSkills

func (b *BaseAgent) EnableSkills(manager SkillDiscoverer)

EnableSkills 启用 Skills 系统

func (*BaseAgent) EnableToolSelection

func (b *BaseAgent) EnableToolSelection(selector DynamicToolSelectorRunner)

EnableToolSelection 启用动态工具选择

func (*BaseAgent) EnsureReady

func (b *BaseAgent) EnsureReady() error

EnsureReady 确保 Agent 处于就绪状态

func (*BaseAgent) Execute

func (b *BaseAgent) Execute(ctx context.Context, input *Input) (_ *Output, execErr error)

Execute 执行任务(完整的 ReAct 循环) 这是 Agent 的核心执行方法,包含完整的推理-行动循环 Requirements 1.7: 集成输入验证 Requirements 2.4: 输出验证失败时支持重试

func (*BaseAgent) ExecuteEnhanced

func (b *BaseAgent) ExecuteEnhanced(ctx context.Context, input *Input, options EnhancedExecutionOptions) (*Output, error)

ExecuteEnhanced 增强执行(集成所有功能)

func (*BaseAgent) ExportConfiguration

func (b *BaseAgent) ExportConfiguration() map[string]any

ExportConfiguration 导出配置(用于持久化或分享)

func (*BaseAgent) GetFeatureMetrics

func (b *BaseAgent) GetFeatureMetrics() map[string]any

GetFeatureMetrics 获取功能使用指标

func (*BaseAgent) GetFeatureStatus

func (b *BaseAgent) GetFeatureStatus() map[string]bool

GetFeatureStatus 获取功能启用状态

func (*BaseAgent) GuardrailsEnabled

func (b *BaseAgent) GuardrailsEnabled() bool

是否启用了护栏

func (*BaseAgent) ID

func (b *BaseAgent) ID() string

ID 返回 Agent ID

func (*BaseAgent) Init

func (b *BaseAgent) Init(ctx context.Context) error

Init 初始化 Agent

func (*BaseAgent) Logger

func (b *BaseAgent) Logger() *zap.Logger

Logger 返回日志器

func (*BaseAgent) Memory

func (b *BaseAgent) Memory() MemoryManager

Memory 返回记忆管理器

func (*BaseAgent) Name

func (b *BaseAgent) Name() string

Name 返回 Agent 名称

func (*BaseAgent) Observe

func (b *BaseAgent) Observe(ctx context.Context, feedback *Feedback) error

Observe 处理反馈并更新 Agent 状态 这个方法允许 Agent 从外部反馈中学习和改进

func (*BaseAgent) Plan

func (b *BaseAgent) Plan(ctx context.Context, input *Input) (*PlanResult, error)

Plan 生成执行计划 使用 LLM 分析任务并生成详细的执行步骤

func (*BaseAgent) PrintFeatureStatus

func (b *BaseAgent) PrintFeatureStatus()

PrintFeatureStatus 打印功能状态

func (*BaseAgent) Provider

func (b *BaseAgent) Provider() llm.Provider

Provider 返回 LLM Provider

func (*BaseAgent) RecallMemory

func (b *BaseAgent) RecallMemory(ctx context.Context, query string, topK int) ([]MemoryRecord, error)

RecallMemory 检索记忆

func (*BaseAgent) SaveMemory

func (b *BaseAgent) SaveMemory(ctx context.Context, content string, kind MemoryKind, metadata map[string]any) error

SaveMemory 保存记忆并同步更新本地缓存

func (*BaseAgent) SetContextManager

func (b *BaseAgent) SetContextManager(cm ContextManager)

SetContextManager 设置上下文管理器

func (*BaseAgent) SetConversationStore added in v1.1.0

func (b *BaseAgent) SetConversationStore(store ConversationStoreProvider)

SetConversationStore sets the conversation store provider.

func (*BaseAgent) SetGuardrails

func (b *BaseAgent) SetGuardrails(cfg *guardrails.GuardrailsConfig)

设置守护栏为代理设置守护栏 1.7: 支持海关验证规则的登记和延期

func (*BaseAgent) SetPromptStore added in v1.1.0

func (b *BaseAgent) SetPromptStore(store PromptStoreProvider)

SetPromptStore sets the prompt store provider.

func (*BaseAgent) SetRunStore added in v1.1.0

func (b *BaseAgent) SetRunStore(store RunStoreProvider)

SetRunStore sets the run store provider.

func (*BaseAgent) SetToolProvider

func (b *BaseAgent) SetToolProvider(p llm.Provider)

SetToolProvider 设置工具调用专用的 LLM Provider

func (*BaseAgent) State

func (b *BaseAgent) State() State

State 返回当前状态

func (*BaseAgent) StreamCompletion

func (b *BaseAgent) StreamCompletion(ctx context.Context, messages []types.Message) (<-chan llm.StreamChunk, error)

StreamCompletion 流式调用 LLM

func (*BaseAgent) Teardown

func (b *BaseAgent) Teardown(ctx context.Context) error

Teardown 清理资源

func (*BaseAgent) ToolProvider

func (b *BaseAgent) ToolProvider() llm.Provider

ToolProvider 返回工具调用专用的 LLM Provider(可能为 nil)

func (*BaseAgent) Tools

func (b *BaseAgent) Tools() ToolManager

Tools 返回工具注册中心

func (*BaseAgent) Transition

func (b *BaseAgent) Transition(ctx context.Context, to State) error

Transition 状态转换(带校验)

func (*BaseAgent) TryLockExec

func (b *BaseAgent) TryLockExec() bool

TryLockExec 尝试获取执行锁,防止并发执行

func (*BaseAgent) Type

func (b *BaseAgent) Type() AgentType

Type 返回 Agent 类型

func (*BaseAgent) UnlockExec

func (b *BaseAgent) UnlockExec()

UnlockExec 释放执行锁

func (*BaseAgent) ValidateConfiguration

func (b *BaseAgent) ValidateConfiguration() error

ValidateConfiguration 验证配置

type CachingResolver added in v1.0.0

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

============================================================================= Resolver (merged from resolver.go) ============================================================================= CachingResolver resolves agent IDs to live Agent instances, creating them on demand via AgentRegistry and caching them for reuse. It uses singleflight to ensure concurrent requests for the same agentID only trigger one Create+Init cycle.

func NewCachingResolver added in v1.0.0

func NewCachingResolver(registry *AgentRegistry, provider llm.Provider, logger *zap.Logger) *CachingResolver

NewCachingResolver creates a CachingResolver backed by the given registry and LLM provider.

func (*CachingResolver) ResetCache added in v1.4.6

func (r *CachingResolver) ResetCache(ctx context.Context)

ResetCache tears down and removes all cached agent instances. Future Resolve calls will recreate agents with latest runtime settings.

func (*CachingResolver) Resolve added in v1.0.0

func (r *CachingResolver) Resolve(ctx context.Context, agentID string) (Agent, error)

Resolve returns a cached Agent for agentID, or creates and initialises one.

func (*CachingResolver) TeardownAll added in v1.0.0

func (r *CachingResolver) TeardownAll(ctx context.Context)

TeardownAll tears down all cached agent instances. Intended to be called during graceful shutdown.

func (*CachingResolver) WithConversationStore added in v1.1.0

func (r *CachingResolver) WithConversationStore(s ConversationStoreProvider) *CachingResolver

WithConversationStore sets the ConversationStoreProvider for resolved agents.

func (*CachingResolver) WithDefaultModel added in v1.4.6

func (r *CachingResolver) WithDefaultModel(model string) *CachingResolver

WithDefaultModel sets the default model used for resolved agents. Agent request can still override it at runtime via model routing params.

func (*CachingResolver) WithMemory added in v1.1.0

func (r *CachingResolver) WithMemory(m MemoryManager) *CachingResolver

WithMemory sets the MemoryManager used when creating new agent instances. When non-nil, agents created by this resolver will have memory capabilities.

func (*CachingResolver) WithPromptStore added in v1.1.0

func (r *CachingResolver) WithPromptStore(s PromptStoreProvider) *CachingResolver

WithPromptStore sets the PromptStoreProvider for resolved agents.

func (*CachingResolver) WithRunStore added in v1.1.0

func (r *CachingResolver) WithRunStore(s RunStoreProvider) *CachingResolver

WithRunStore sets the RunStoreProvider for resolved agents.

func (*CachingResolver) WithRuntimeTools added in v1.4.6

func (r *CachingResolver) WithRuntimeTools(toolNames []string) *CachingResolver

WithRuntimeTools sets a default tool whitelist for resolved agents. If empty, the resolver derives tool names from ToolManager.GetAllowedTools(agentID).

func (*CachingResolver) WithToolManager added in v1.4.6

func (r *CachingResolver) WithToolManager(m ToolManager) *CachingResolver

WithToolManager sets the ToolManager used when creating new agent instances. When non-nil, resolved agents can call tools during execution.

type Checkpoint

type Checkpoint struct {
	ID        string              `json:"id"`
	ThreadID  string              `json:"thread_id"` // 会话线程 ID
	AgentID   string              `json:"agent_id"`
	Version   int                 `json:"version"` // 版本号(线程内递增)
	State     State               `json:"state"`
	Messages  []CheckpointMessage `json:"messages"`
	Metadata  map[string]any      `json:"metadata"`
	CreatedAt time.Time           `json:"created_at"`
	ParentID  string              `json:"parent_id,omitempty"` // 父检查点 ID

	// ExecutionContext 工作流执行上下文
	ExecutionContext *ExecutionContext `json:"execution_context,omitempty"`
}

============================================================================= Checkpoint Types & Manager (merged from checkpoint_types_manager.go) ============================================================================= Checkpoint Agent 执行检查点(基于 LangGraph 2026 标准)

type CheckpointDiff

type CheckpointDiff struct {
	ThreadID     string        `json:"thread_id"`
	Version1     int           `json:"version1"`
	Version2     int           `json:"version2"`
	StateChanged bool          `json:"state_changed"`
	OldState     State         `json:"old_state"`
	NewState     State         `json:"new_state"`
	MessagesDiff string        `json:"messages_diff"`
	MetadataDiff string        `json:"metadata_diff"`
	TimeDiff     time.Duration `json:"time_diff"`
}

检查站 Diff 代表两个检查站版本之间的差异

type CheckpointManager

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

CheckpointManager 检查点管理器

func NewCheckpointManager

func NewCheckpointManager(store CheckpointStore, logger *zap.Logger) *CheckpointManager

NewCheckpointManager 创建检查点管理器

func (*CheckpointManager) CompareVersions

func (m *CheckpointManager) CompareVersions(ctx context.Context, threadID string, version1, version2 int) (*CheckpointDiff, error)

比较Version 比较两个检查点版本并返回差异

func (*CheckpointManager) CreateCheckpoint

func (m *CheckpointManager) CreateCheckpoint(ctx context.Context, agent Agent, threadID string) error

创建检查点来抓取当前代理状态并将其保存为检查点

func (*CheckpointManager) DisableAutoSave

func (m *CheckpointManager) DisableAutoSave()

禁用自动保存停止自动检查

func (*CheckpointManager) EnableAutoSave

func (m *CheckpointManager) EnableAutoSave(ctx context.Context, agent Agent, threadID string, interval time.Duration) error

启用自动保存以指定间隔自动保存检查点

func (*CheckpointManager) ListVersions

func (m *CheckpointManager) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)

ListVersion 列出用于线索的所有检查点版本

func (*CheckpointManager) LoadCheckpoint

func (m *CheckpointManager) LoadCheckpoint(ctx context.Context, checkpointID string) (*Checkpoint, error)

LoadCheckpoint 加载检查点

func (*CheckpointManager) LoadLatestCheckpoint

func (m *CheckpointManager) LoadLatestCheckpoint(ctx context.Context, threadID string) (*Checkpoint, error)

LoadLatestCheckpoint 加载最新检查点

func (*CheckpointManager) ResumeFromCheckpoint

func (m *CheckpointManager) ResumeFromCheckpoint(ctx context.Context, agent Agent, checkpointID string) error

ResumeFromCheckpoint 从检查点恢复执行

func (*CheckpointManager) RollbackToVersion

func (m *CheckpointManager) RollbackToVersion(ctx context.Context, agent Agent, threadID string, version int) error

Rollback ToVersion 将代理拖回特定检查点版本

func (*CheckpointManager) SaveCheckpoint

func (m *CheckpointManager) SaveCheckpoint(ctx context.Context, checkpoint *Checkpoint) error

SaveCheckpoint 保存检查点

type CheckpointMessage

type CheckpointMessage struct {
	Role      string               `json:"role"`
	Content   string               `json:"content"`
	ToolCalls []CheckpointToolCall `json:"tool_calls,omitempty"`
	Metadata  map[string]any       `json:"metadata,omitempty"`
}

CheckpointMessage 检查点消息

type CheckpointStore

type CheckpointStore interface {
	// Save 保存检查点
	Save(ctx context.Context, checkpoint *Checkpoint) error

	// Load 加载检查点
	Load(ctx context.Context, checkpointID string) (*Checkpoint, error)

	// LoadLatest 加载线程最新检查点
	LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)

	// List 列出线程的所有检查点
	List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)

	// Delete 删除检查点
	Delete(ctx context.Context, checkpointID string) error

	// DeleteThread 删除整个线程
	DeleteThread(ctx context.Context, threadID string) error

	// LoadVersion 加载指定版本的检查点
	LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)

	// ListVersions 列出线程的所有版本
	ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)

	// Rollback 回滚到指定版本
	Rollback(ctx context.Context, threadID string, version int) error
}

CheckpointStore 检查点存储接口(Agent 层)。

注意:项目中存在两个 CheckpointStore 接口,操作不同的检查点类型:

  • agent.CheckpointStore(本接口) — 操作 *agent.Checkpoint,含 List/DeleteThread/Rollback
  • workflow.CheckpointStore — 操作 *workflow.EnhancedCheckpoint,用于 DAG 工作流时间旅行

两者的检查点结构体字段不同(Agent 状态 vs DAG 节点结果),无法统一。

type CheckpointToolCall

type CheckpointToolCall struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
	Result    json.RawMessage `json:"result,omitempty"`
	Error     string          `json:"error,omitempty"`
}

CheckpointToolCall 工具调用记录

type CheckpointVersion

type CheckpointVersion struct {
	Version   int       `json:"version"`
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"created_at"`
	State     State     `json:"state"`
	Summary   string    `json:"summary"`
}

CheckpointVersion 检查点版本元数据

type ContextManager

type ContextManager interface {
	PrepareMessages(ctx context.Context, messages []types.Message, currentQuery string) ([]types.Message, error)
	GetStatus(messages []types.Message) any
	EstimateTokens(messages []types.Message) int
}

ContextManager 上下文管理器接口 使用 pkg/context.AgentContextManager 作为标准实现

type ConversationDoc added in v1.1.0

type ConversationDoc struct {
	ID       string                `json:"id"`
	ParentID string                `json:"parent_id,omitempty"`
	AgentID  string                `json:"agent_id"`
	TenantID string                `json:"tenant_id"`
	UserID   string                `json:"user_id"`
	Title    string                `json:"title,omitempty"`
	Messages []ConversationMessage `json:"messages"`
}

ConversationDoc is a minimal conversation document for the agent layer.

type ConversationMessage added in v1.1.0

type ConversationMessage struct {
	ID        string    `json:"id,omitempty"`
	Role      string    `json:"role"`
	Content   string    `json:"content"`
	Timestamp time.Time `json:"timestamp"`
}

ConversationMessage is a single message in a conversation document.

type ConversationStoreProvider added in v1.1.0

type ConversationStoreProvider interface {
	// ---- 原有 ----
	Create(ctx context.Context, doc *ConversationDoc) error
	GetByID(ctx context.Context, id string) (*ConversationDoc, error)
	AppendMessages(ctx context.Context, conversationID string, msgs []ConversationMessage) error

	// ---- 新增 ----
	List(ctx context.Context, tenantID, parentID string, page, pageSize int) ([]*ConversationDoc, int64, error)
	Update(ctx context.Context, id string, updates ConversationUpdate) error
	Delete(ctx context.Context, id string) error
	DeleteByParentID(ctx context.Context, tenantID, parentID string) error
	GetMessages(ctx context.Context, conversationID string, offset, limit int) ([]ConversationMessage, int64, error)
	DeleteMessage(ctx context.Context, conversationID, messageID string) error
	ClearMessages(ctx context.Context, conversationID string) error
	Archive(ctx context.Context, id string) error
}

ConversationStoreProvider persists conversation history. Implemented by: *mongodb.ConversationStoreAdapter (agent/persistence/mongodb/)

type ConversationUpdate added in v1.4.6

type ConversationUpdate struct {
	Title    *string        `json:"title,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

ConversationUpdate contains the fields that can be updated on a conversation.

type Critique

type Critique struct {
	Score       float64  `json:"score"`        // 0-1 分数
	IsGood      bool     `json:"is_good"`      // 是否达标
	Issues      []string `json:"issues"`       // 问题列表
	Suggestions []string `json:"suggestions"`  // 改进建议
	RawFeedback string   `json:"raw_feedback"` // 原始反馈
}

Critique 评审结果

type DefensivePromptConfig

type DefensivePromptConfig struct {
	// 失败处理模式
	FailureModes []FailureMode `json:"failure_modes"`

	// 输出 Schema 强制
	OutputSchema *OutputSchema `json:"output_schema,omitempty"`

	// 护栏规则
	GuardRails []GuardRail `json:"guard_rails"`

	// 提示注入防护
	InjectionDefense *InjectionDefenseConfig `json:"injection_defense,omitempty"`
}

DefensivePromptConfig 防御性提示配置(基于 2025 年生产最佳实践)

func DefaultDefensivePromptConfig

func DefaultDefensivePromptConfig() DefensivePromptConfig

DefaultDefensivePromptConfig 返回默认防御性提示配置

type DefensivePromptEnhancer

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

DefensivePromptEnhancer 防御性提示增强器

func NewDefensivePromptEnhancer

func NewDefensivePromptEnhancer(config DefensivePromptConfig) *DefensivePromptEnhancer

NewDefensivePromptEnhancer 创建防御性提示增强器

func (*DefensivePromptEnhancer) EnhancePromptBundle

func (e *DefensivePromptEnhancer) EnhancePromptBundle(bundle PromptBundle) PromptBundle

EnhancePromptBundle 增强提示词包(添加防御性规则)

func (*DefensivePromptEnhancer) SanitizeUserInput

func (e *DefensivePromptEnhancer) SanitizeUserInput(input string) (string, bool)

SanitizeUserInput 清理用户输入(防止提示注入)

func (*DefensivePromptEnhancer) ValidateOutput

func (e *DefensivePromptEnhancer) ValidateOutput(output string) error

ValidateOutput 验证输出是否符合 Schema

type DynamicToolSelector

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

DynamicToolSelector 动态工具选择器

func NewDynamicToolSelector

func NewDynamicToolSelector(agent *BaseAgent, config ToolSelectionConfig) *DynamicToolSelector

NewDynamicToolSelector 创建动态工具选择器

func (*DynamicToolSelector) ScoreTools

func (s *DynamicToolSelector) ScoreTools(ctx context.Context, task string, tools []types.ToolSchema) ([]ToolScore, error)

ScoreTools 对工具进行评分

func (*DynamicToolSelector) SelectTools

func (s *DynamicToolSelector) SelectTools(ctx context.Context, task string, availableTools []types.ToolSchema) ([]types.ToolSchema, error)

SelectTools 选择最佳工具

func (*DynamicToolSelector) UpdateToolStats

func (s *DynamicToolSelector) UpdateToolStats(toolName string, success bool, latency time.Duration, cost float64)

UpdateToolStats 更新工具统计信息

type DynamicToolSelectorRunner added in v1.0.0

type DynamicToolSelectorRunner interface {
	SelectTools(ctx context.Context, task string, availableTools any) (any, error)
}

DynamicToolSelectorRunner dynamically selects tools relevant to a given task. This uses any for availableTools to match the integration.go call site signature. Implemented by: *DynamicToolSelector (agent/tool_selector.go) via adapter

func AsToolSelectorRunner added in v1.0.0

func AsToolSelectorRunner(selector *DynamicToolSelector) DynamicToolSelectorRunner

AsToolSelectorRunner wraps a *DynamicToolSelector as a DynamicToolSelectorRunner.

type EnhancedExecutionOptions

type EnhancedExecutionOptions struct {
	// Reflection 选项
	UseReflection bool

	// 工具选择选项
	UseToolSelection bool

	// 提示词增强选项
	UsePromptEnhancer bool

	// Skills 选项
	UseSkills   bool
	SkillsQuery string

	// 记忆选项
	UseEnhancedMemory   bool
	LoadWorkingMemory   bool
	LoadShortTermMemory bool
	SaveToMemory        bool

	// 可观测性选项
	UseObservability bool
	RecordMetrics    bool
	RecordTrace      bool
}

EnhancedExecutionOptions 增强执行选项

func DefaultEnhancedExecutionOptions

func DefaultEnhancedExecutionOptions() EnhancedExecutionOptions

DefaultEnhancedExecutionOptions 默认增强执行选项

type EnhancedMemoryRunner added in v1.0.0

type EnhancedMemoryRunner interface {
	LoadWorking(ctx context.Context, agentID string) ([]any, error)
	LoadShortTerm(ctx context.Context, agentID string, limit int) ([]any, error)
	SaveShortTerm(ctx context.Context, agentID, content string, metadata map[string]any) error
	RecordEpisode(ctx context.Context, event *memory.EpisodicEvent) error
}

EnhancedMemoryRunner provides advanced memory capabilities. Implemented by: *memory.EnhancedMemorySystem (agent/memory/)

type ErrInvalidTransition

type ErrInvalidTransition struct {
	From State
	To   State
}

ErrInvalidTransition 状态转换错误。

func (ErrInvalidTransition) Error

func (e ErrInvalidTransition) Error() string

func (ErrInvalidTransition) ToAgentError

func (e ErrInvalidTransition) ToAgentError() *Error

ToAgentError 将 ErrInvalidTransition 转换为 Agent.Error。

type Error

type Error struct {
	Base      *types.Error   `json:"base,inline"`
	AgentID   string         `json:"agent_id,omitempty"`
	AgentType AgentType      `json:"agent_type,omitempty"`
	Timestamp time.Time      `json:"timestamp"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

Error Agent 统一错误类型。

func NewError

func NewError(code types.ErrorCode, message string) *Error

NewError 创建新的 Agent 错误。

func NewErrorWithCause

func NewErrorWithCause(code types.ErrorCode, message string, cause error) *Error

NewErrorWithCause 创建带原因的错误。

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

func (*Error) WithAgent

func (e *Error) WithAgent(id string, agentType AgentType) *Error

WithAgent 添加 Agent 信息。

func (*Error) WithCause

func (e *Error) WithCause(cause error) *Error

WithCause 添加原因错误。

func (*Error) WithMetadata

func (e *Error) WithMetadata(key string, value any) *Error

WithMetadata 添加元数据。

func (*Error) WithRetryable

func (e *Error) WithRetryable(retryable bool) *Error

WithRetryable 设置是否可重试。

type Event

type Event interface {
	Timestamp() time.Time
	Type() EventType
}

Event 事件接口

type EventBus

type EventBus interface {
	Publish(event Event)
	Subscribe(eventType EventType, handler EventHandler) string
	Unsubscribe(subscriptionID string)
	Stop()
}

EventBus 定义事件总线接口

func NewEventBus

func NewEventBus(logger ...*zap.Logger) EventBus

NewEventBus 创建新的事件总线

type EventHandler

type EventHandler func(Event)

EventHandler 事件处理器

type EventType

type EventType = types.AgentEventType

EventType 事件类型

const (
	EventStateChange       EventType = types.AgentEventStateChange
	EventToolCall          EventType = types.AgentEventToolCall
	EventFeedback          EventType = types.AgentEventFeedback
	EventApprovalRequested EventType = types.AgentEventApprovalRequested
	EventApprovalResponded EventType = types.AgentEventApprovalResponded
	EventSubagentCompleted EventType = types.AgentEventSubagentCompleted
	EventAgentRunStart     EventType = types.AgentEventRunStart
	EventAgentRunComplete  EventType = types.AgentEventRunComplete
	EventAgentRunError     EventType = types.AgentEventRunError
)

type Example

type Example struct {
	User      string `json:"user"`
	Assistant string `json:"assistant"`
}

type ExecutionContext

type ExecutionContext struct {
	WorkflowID  string         `json:"workflow_id,omitempty"`
	CurrentNode string         `json:"current_node,omitempty"`
	NodeResults map[string]any `json:"node_results,omitempty"`
	Variables   map[string]any `json:"variables,omitempty"`
}

ExecutionContext 工作流执行上下文

type ExecutionStatus

type ExecutionStatus string

ExecutionStatus 执行状态

const (
	ExecutionStatusPending   ExecutionStatus = "pending"
	ExecutionStatusRunning   ExecutionStatus = "running"
	ExecutionStatusCompleted ExecutionStatus = "completed"
	ExecutionStatusFailed    ExecutionStatus = "failed"
	ExecutionStatusCanceled  ExecutionStatus = "canceled"
)

type ExtensionRegistry added in v1.1.0

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

ExtensionRegistry encapsulates the 9 optional extension fields extracted from BaseAgent.

func NewExtensionRegistry added in v1.1.0

func NewExtensionRegistry(logger *zap.Logger) *ExtensionRegistry

NewExtensionRegistry creates a new ExtensionRegistry.

func (*ExtensionRegistry) EnableEnhancedMemory added in v1.1.0

func (r *ExtensionRegistry) EnableEnhancedMemory(memorySystem EnhancedMemoryRunner)

EnableEnhancedMemory enables the enhanced memory system.

func (*ExtensionRegistry) EnableLSP added in v1.1.0

func (r *ExtensionRegistry) EnableLSP(client LSPClientRunner)

EnableLSP enables LSP integration.

func (*ExtensionRegistry) EnableLSPWithLifecycle added in v1.1.0

func (r *ExtensionRegistry) EnableLSPWithLifecycle(client LSPClientRunner, lifecycle LSPLifecycleOwner)

EnableLSPWithLifecycle enables LSP with an optional lifecycle owner.

func (*ExtensionRegistry) EnableMCP added in v1.1.0

func (r *ExtensionRegistry) EnableMCP(server MCPServerRunner)

EnableMCP enables MCP integration.

func (*ExtensionRegistry) EnableObservability added in v1.1.0

func (r *ExtensionRegistry) EnableObservability(obsSystem ObservabilityRunner)

EnableObservability enables the observability system.

func (*ExtensionRegistry) EnablePromptEnhancer added in v1.1.0

func (r *ExtensionRegistry) EnablePromptEnhancer(enhancer PromptEnhancerRunner)

EnablePromptEnhancer enables prompt enhancement.

func (*ExtensionRegistry) EnableReflection added in v1.1.0

func (r *ExtensionRegistry) EnableReflection(executor ReflectionRunner)

EnableReflection enables the reflection mechanism.

func (*ExtensionRegistry) EnableSkills added in v1.1.0

func (r *ExtensionRegistry) EnableSkills(manager SkillDiscoverer)

EnableSkills enables the skills system.

func (*ExtensionRegistry) EnableToolSelection added in v1.1.0

func (r *ExtensionRegistry) EnableToolSelection(selector DynamicToolSelectorRunner)

EnableToolSelection enables dynamic tool selection.

func (*ExtensionRegistry) EnhancedMemoryExt added in v1.1.0

func (r *ExtensionRegistry) EnhancedMemoryExt() EnhancedMemoryRunner

EnhancedMemoryExt returns the enhanced memory runner.

func (*ExtensionRegistry) ExecuteWithReflection added in v1.1.0

func (r *ExtensionRegistry) ExecuteWithReflection(ctx context.Context, input *Input) (any, error)

ExecuteWithReflection delegates to the reflection executor.

func (*ExtensionRegistry) GetFeatureStatus added in v1.1.0

func (r *ExtensionRegistry) GetFeatureStatus() map[string]bool

GetFeatureStatus returns a map of feature name to enabled status.

func (*ExtensionRegistry) LSPClientExt added in v1.1.0

func (r *ExtensionRegistry) LSPClientExt() LSPClientRunner

LSPClientExt returns the LSP client runner.

func (*ExtensionRegistry) LSPLifecycleExt added in v1.1.0

func (r *ExtensionRegistry) LSPLifecycleExt() LSPLifecycleOwner

LSPLifecycleExt returns the LSP lifecycle owner.

func (*ExtensionRegistry) MCPServerExt added in v1.1.0

func (r *ExtensionRegistry) MCPServerExt() MCPServerRunner

MCPServerExt returns the MCP server runner.

func (*ExtensionRegistry) ObservabilitySystemExt added in v1.1.0

func (r *ExtensionRegistry) ObservabilitySystemExt() ObservabilityRunner

ObservabilitySystemExt returns the observability runner.

func (*ExtensionRegistry) PromptEnhancerExt added in v1.1.0

func (r *ExtensionRegistry) PromptEnhancerExt() PromptEnhancerRunner

PromptEnhancerExt returns the prompt enhancer runner.

func (*ExtensionRegistry) ReflectionExecutor added in v1.1.0

func (r *ExtensionRegistry) ReflectionExecutor() ReflectionRunner

ReflectionExecutor returns the reflection runner.

func (*ExtensionRegistry) SaveToEnhancedMemory added in v1.1.0

func (r *ExtensionRegistry) SaveToEnhancedMemory(ctx context.Context, agentID string, input *Input, output *Output, useReflection bool)

SaveToEnhancedMemory saves output to enhanced memory and records an episode.

func (*ExtensionRegistry) SkillManagerExt added in v1.1.0

func (r *ExtensionRegistry) SkillManagerExt() SkillDiscoverer

SkillManagerExt returns the skill discoverer.

func (*ExtensionRegistry) TeardownExtensions added in v1.1.0

func (r *ExtensionRegistry) TeardownExtensions(ctx context.Context) error

TeardownExtensions cleans up extension resources.

func (*ExtensionRegistry) ToolSelector added in v1.1.0

func (r *ExtensionRegistry) ToolSelector() DynamicToolSelectorRunner

ToolSelector returns the tool selector runner.

func (*ExtensionRegistry) ValidateConfiguration added in v1.1.0

func (r *ExtensionRegistry) ValidateConfiguration(cfg types.AgentConfig) []string

ValidateConfiguration validates that enabled features have their executors set.

type FailureMode

type FailureMode struct {
	Condition string `json:"condition"` // "missing_data", "ambiguous_input", "conflicting_requirements", "tool_unavailable"
	Action    string `json:"action"`    // "return_error", "request_clarification", "use_default", "escalate_to_human"
	Template  string `json:"template"`  // 错误消息模板
	Example   string `json:"example,omitempty"`
}

FailureMode 失败模式定义

type Feedback

type Feedback struct {
	Type    string         `json:"type"` // approval/rejection/correction
	Content string         `json:"content,omitempty"`
	Data    map[string]any `json:"data,omitempty"`
}

Feedback 反馈信息

type FeedbackEvent

type FeedbackEvent struct {
	AgentID_     string
	FeedbackType string
	Content      string
	Data         map[string]any
	Timestamp_   time.Time
}

FeedbackEvent 反馈事件

func (*FeedbackEvent) Timestamp

func (e *FeedbackEvent) Timestamp() time.Time

func (*FeedbackEvent) Type

func (e *FeedbackEvent) Type() EventType

type FileCheckpointStore

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

FileCheckpointStore 文件检查点存储(用于本地开发和测试)

func NewFileCheckpointStore

func NewFileCheckpointStore(basePath string, logger *zap.Logger) (*FileCheckpointStore, error)

NewFileCheckpointStore 创建文件检查点存储

func (*FileCheckpointStore) Delete

func (s *FileCheckpointStore) Delete(ctx context.Context, checkpointID string) error

Delete 删除检查点

func (*FileCheckpointStore) DeleteThread

func (s *FileCheckpointStore) DeleteThread(ctx context.Context, threadID string) error

DeleteThread 删除线程

func (*FileCheckpointStore) List

func (s *FileCheckpointStore) List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)

List 列出检查点

func (*FileCheckpointStore) ListVersions

func (s *FileCheckpointStore) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)

ListVersions 列出线程的所有版本

func (*FileCheckpointStore) Load

func (s *FileCheckpointStore) Load(ctx context.Context, checkpointID string) (*Checkpoint, error)

Load 加载检查点

func (*FileCheckpointStore) LoadLatest

func (s *FileCheckpointStore) LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)

LoadLatest 加载最新检查点

func (*FileCheckpointStore) LoadVersion

func (s *FileCheckpointStore) LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)

LoadVersion 加载指定版本的检查点

func (*FileCheckpointStore) Rollback

func (s *FileCheckpointStore) Rollback(ctx context.Context, threadID string, version int) error

Rollback 回滚到指定版本

func (*FileCheckpointStore) Save

func (s *FileCheckpointStore) Save(ctx context.Context, checkpoint *Checkpoint) error

Save 保存检查点

type GuardRail

type GuardRail struct {
	Type        string   `json:"type"`     // "never", "always", "boundary", "constraint"
	Category    string   `json:"category"` // "data_safety", "action_limit", "disclosure", "ethical"
	Description string   `json:"description"`
	Examples    []string `json:"examples,omitempty"`
	Severity    string   `json:"severity"` // "critical", "high", "medium", "low"
}

GuardRail 护栏规则(负面指令)

type GuardrailsCoordinator

type GuardrailsCoordinator = guardcore.Coordinator

GuardrailsCoordinator is the agent facade type for guardrails coordination.

func NewGuardrailsCoordinator

func NewGuardrailsCoordinator(config *guardrails.GuardrailsConfig, logger *zap.Logger) *GuardrailsCoordinator

NewGuardrailsCoordinator creates a new GuardrailsCoordinator.

type GuardrailsError

type GuardrailsError struct {
	Type    GuardrailsErrorType          `json:"type"`
	Message string                       `json:"message"`
	Errors  []guardrails.ValidationError `json:"errors"`
}

GuardrailsError 代表一个 Guardrails 验证错误。

func (*GuardrailsError) Error

func (e *GuardrailsError) Error() string

type GuardrailsErrorType

type GuardrailsErrorType string

GuardrailsErrorType 定义了 Guardrails 错误的类型。

const (
	GuardrailsErrorTypeInput  GuardrailsErrorType = "input"
	GuardrailsErrorTypeOutput GuardrailsErrorType = "output"
)

type GuardrailsManager added in v1.2.0

type GuardrailsManager = guardcore.Manager

GuardrailsManager is the agent facade type for guardrails management.

func NewGuardrailsManager added in v1.2.0

func NewGuardrailsManager(logger *zap.Logger) *GuardrailsManager

NewGuardrailsManager creates a new GuardrailsManager.

type HealthStatus

type HealthStatus struct {
	Healthy   bool      `json:"healthy"`
	State     State     `json:"state"`
	LastCheck time.Time `json:"last_check"`
	Message   string    `json:"message,omitempty"`
}

HealthStatus 健康状态

L-002: 项目中存在两个 HealthStatus 结构体,服务于不同层次:

  • agent.HealthStatus(本定义)— Agent 层健康状态,包含 State 字段
  • llm.HealthStatus — LLM Provider 层健康状态,包含 Latency/ErrorRate 字段

两者字段不同,无法统一。如需跨层传递,请使用各自的转换函数。

type InjectionDefenseConfig

type InjectionDefenseConfig struct {
	Enabled           bool     `json:"enabled"`
	DetectionPatterns []string `json:"detection_patterns"`
	UseDelimiters     bool     `json:"use_delimiters"`
	SanitizeInput     bool     `json:"sanitize_input"`
	RoleIsolation     bool     `json:"role_isolation"` // 分离用户输入和系统指令
}

InjectionDefenseConfig 提示注入防护配置

type Input

type Input struct {
	TraceID   string            `json:"trace_id"`
	TenantID  string            `json:"tenant_id,omitempty"`
	UserID    string            `json:"user_id,omitempty"`
	ChannelID string            `json:"channel_id,omitempty"`
	Content   string            `json:"content"`
	Context   map[string]any    `json:"context,omitempty"`   // 额外上下文
	Variables map[string]string `json:"variables,omitempty"` // 变量替换
}

Input Agent 输入

type LSPClientRunner added in v1.0.0

type LSPClientRunner interface {
	Shutdown(ctx context.Context) error
}

LSPClientRunner represents an LSP client instance. Implemented by: *lsp.LSPClient (agent/lsp/) Used in Teardown for Shutdown call.

type LSPLifecycleOwner added in v1.0.0

type LSPLifecycleOwner interface {
	Close() error
}

LSPLifecycleOwner represents an optional lifecycle owner for LSP (e.g. *ManagedLSP). Used in Teardown for Close call.

type LifecycleManager

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

LifecycleManager 管理 Agent 的生命周期 提供启动、停止、健康检查等功能

func NewLifecycleManager

func NewLifecycleManager(agent Agent, logger *zap.Logger) *LifecycleManager

NewLifecycleManager 创建生命周期管理器

func (*LifecycleManager) GetHealthStatus

func (lm *LifecycleManager) GetHealthStatus() HealthStatus

GetHealthStatus 获取健康状态

func (*LifecycleManager) IsRunning

func (lm *LifecycleManager) IsRunning() bool

IsRunning 检查是否正在运行

func (*LifecycleManager) Restart

func (lm *LifecycleManager) Restart(ctx context.Context) error

Restart 重启 Agent

func (*LifecycleManager) Start

func (lm *LifecycleManager) Start(ctx context.Context) error

Start 启动 Agent

func (*LifecycleManager) Stop

func (lm *LifecycleManager) Stop(ctx context.Context) error

Stop 停止 Agent

type MCPServerRunner added in v1.0.0

type MCPServerRunner interface{}

MCPServerRunner represents an MCP server instance. Implemented by: *mcp.MCPServer (agent/protocol/mcp/) Currently used only for nil-check (feature status); no methods called directly.

type ManagedLSP

type ManagedLSP struct {
	Client *agentlsp.LSPClient
	Server *agentlsp.LSPServer
	// contains filtered or unexported fields
}

ManagedLSP 封装了进程内的 LSP client/server 及其生命周期。

func NewManagedLSP

func NewManagedLSP(info agentlsp.ServerInfo, logger *zap.Logger) *ManagedLSP

NewManagedLSP 创建并启动一个进程内的 LSP runtime。

func (*ManagedLSP) Close

func (m *ManagedLSP) Close() error

Close 关闭 runtime 并回收后台 goroutine。

type MemoryCache added in v1.1.0

type MemoryCache = memorycore.Cache

MemoryCache is the agent facade type for memory cache.

func NewMemoryCache added in v1.1.0

func NewMemoryCache(agentID string, memory MemoryManager, logger *zap.Logger) *MemoryCache

NewMemoryCache creates a new MemoryCache.

type MemoryConfig

type MemoryConfig struct {
	Enabled bool `json:"enabled,omitempty"`
}

type MemoryCoordinator

type MemoryCoordinator = memorycore.Coordinator

MemoryCoordinator is the agent facade type for memory coordination.

func NewMemoryCoordinator

func NewMemoryCoordinator(agentID string, memory MemoryManager, logger *zap.Logger) *MemoryCoordinator

NewMemoryCoordinator creates a new MemoryCoordinator.

type MemoryKind

type MemoryKind = memorycore.MemoryKind

MemoryKind 记忆类型。

type MemoryManager

type MemoryManager = memorycore.MemoryManager

MemoryManager 组合读写接口。

type MemoryReader

type MemoryReader = memorycore.MemoryReader

MemoryReader 记忆读取接口。

type MemoryRecord

type MemoryRecord = memorycore.MemoryRecord

MemoryRecord 统一记忆结构。

type MemoryWriter

type MemoryWriter = memorycore.MemoryWriter

MemoryWriter 记忆写入接口。

type ObservabilityRunner added in v1.0.0

type ObservabilityRunner interface {
	StartTrace(traceID, agentID string)
	EndTrace(traceID, status string, err error)
	RecordTask(agentID string, success bool, duration time.Duration, tokens int, cost, quality float64)
}

ObservabilityRunner provides metrics, tracing, and logging. Implemented by: *observability.ObservabilitySystem (agent/observability/)

type OrchestrationTaskInput added in v1.2.0

type OrchestrationTaskInput struct {
	ID          string         `json:"id"`
	Description string         `json:"description"`
	Input       string         `json:"input"`
	Agents      []string       `json:"agents,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

OrchestrationTaskInput is the input for an orchestration task.

type OrchestrationTaskOutput added in v1.2.0

type OrchestrationTaskOutput struct {
	Pattern   string         `json:"pattern"`
	Output    string         `json:"output"`
	AgentUsed []string       `json:"agent_used,omitempty"`
	Duration  time.Duration  `json:"duration"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

OrchestrationTaskOutput is the output from an orchestration task.

type OrchestratorRunner added in v1.2.0

type OrchestratorRunner interface {
	Execute(ctx context.Context, task *OrchestrationTaskInput) (*OrchestrationTaskOutput, error)
}

OrchestratorRunner executes a multi-agent orchestration task. Implemented by: *orchestration.OrchestratorAdapter (agent/orchestration/)

type Output

type Output struct {
	TraceID      string         `json:"trace_id"`
	Content      string         `json:"content"`
	Metadata     map[string]any `json:"metadata,omitempty"`
	TokensUsed   int            `json:"tokens_used,omitempty"`
	Cost         float64        `json:"cost,omitempty"`
	Duration     time.Duration  `json:"duration"`
	FinishReason string         `json:"finish_reason,omitempty"`
}

Output Agent 输出

type OutputSchema

type OutputSchema struct {
	Type       string         `json:"type"`             // "json", "markdown", "structured_text"
	Schema     map[string]any `json:"schema,omitempty"` // JSON Schema
	Required   []string       `json:"required,omitempty"`
	Example    string         `json:"example,omitempty"`
	Validation string         `json:"validation,omitempty"` // 验证规则描述
}

OutputSchema 输出格式 Schema

type PersistenceStores added in v1.2.0

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

PersistenceStores encapsulates MongoDB persistence store fields extracted from BaseAgent.

func NewPersistenceStores added in v1.2.0

func NewPersistenceStores(logger *zap.Logger) *PersistenceStores

NewPersistenceStores creates a new PersistenceStores.

func (*PersistenceStores) ConversationStore added in v1.2.0

func (p *PersistenceStores) ConversationStore() ConversationStoreProvider

ConversationStore returns the conversation store provider.

func (*PersistenceStores) LoadPrompt added in v1.2.0

func (p *PersistenceStores) LoadPrompt(ctx context.Context, agentType, name, tenantID string) *PromptDocument

LoadPrompt attempts to load the active prompt from PromptStore. Returns nil if unavailable.

func (*PersistenceStores) PersistConversation added in v1.2.0

func (p *PersistenceStores) PersistConversation(ctx context.Context, conversationID, agentID, tenantID, userID, inputContent, outputContent string)

PersistConversation saves user input and agent output to ConversationStore.

func (*PersistenceStores) PromptStore added in v1.2.0

func (p *PersistenceStores) PromptStore() PromptStoreProvider

PromptStore returns the prompt store provider.

func (*PersistenceStores) RecordRun added in v1.2.0

func (p *PersistenceStores) RecordRun(ctx context.Context, agentID, tenantID, traceID, input string, startTime time.Time) string

RecordRun records an execution run start. Returns the run ID (empty on failure).

func (*PersistenceStores) RestoreConversation added in v1.2.0

func (p *PersistenceStores) RestoreConversation(ctx context.Context, conversationID string) []types.Message

RestoreConversation restores conversation history from the store.

func (*PersistenceStores) RunStore added in v1.2.0

func (p *PersistenceStores) RunStore() RunStoreProvider

RunStore returns the run store provider.

func (*PersistenceStores) SetConversationStore added in v1.2.0

func (p *PersistenceStores) SetConversationStore(store ConversationStoreProvider)

SetConversationStore sets the conversation store provider.

func (*PersistenceStores) SetPromptStore added in v1.2.0

func (p *PersistenceStores) SetPromptStore(store PromptStoreProvider)

SetPromptStore sets the prompt store provider.

func (*PersistenceStores) SetRunStore added in v1.2.0

func (p *PersistenceStores) SetRunStore(store RunStoreProvider)

SetRunStore sets the run store provider.

func (*PersistenceStores) UpdateRunStatus added in v1.2.0

func (p *PersistenceStores) UpdateRunStatus(ctx context.Context, runID, status string, output *RunOutputDoc, errMsg string) error

UpdateRunStatus updates the status of a run.

type PlanConfig

type PlanConfig struct {
	Enabled bool `json:"enabled,omitempty"`
}

type PlanResult

type PlanResult struct {
	Steps    []string       `json:"steps"`              // 执行步骤
	Estimate time.Duration  `json:"estimate,omitempty"` // 预估耗时
	Metadata map[string]any `json:"metadata,omitempty"`
}

PlanResult 规划结果

type PostgreSQLCheckpointStore

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

PostgreSQLCheckpointStore PostgreSQL 检查点存储

func NewPostgreSQLCheckpointStore

func NewPostgreSQLCheckpointStore(db PostgreSQLClient, logger *zap.Logger) *PostgreSQLCheckpointStore

NewPostgreSQLCheckpointStore 创建 PostgreSQL 检查点存储

func (*PostgreSQLCheckpointStore) Delete

func (s *PostgreSQLCheckpointStore) Delete(ctx context.Context, checkpointID string) error

Delete 删除检查点

func (*PostgreSQLCheckpointStore) DeleteThread

func (s *PostgreSQLCheckpointStore) DeleteThread(ctx context.Context, threadID string) error

DeleteThread 删除线程

func (*PostgreSQLCheckpointStore) List

func (s *PostgreSQLCheckpointStore) List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)

List 列出检查点

func (*PostgreSQLCheckpointStore) ListVersions

func (s *PostgreSQLCheckpointStore) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)

ListVersions 列出线程的所有版本

func (*PostgreSQLCheckpointStore) Load

func (s *PostgreSQLCheckpointStore) Load(ctx context.Context, checkpointID string) (*Checkpoint, error)

Load 加载检查点

func (*PostgreSQLCheckpointStore) LoadLatest

func (s *PostgreSQLCheckpointStore) LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)

LoadLatest 加载最新检查点

func (*PostgreSQLCheckpointStore) LoadVersion

func (s *PostgreSQLCheckpointStore) LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)

LoadVersion 加载指定版本的检查点

func (*PostgreSQLCheckpointStore) Rollback

func (s *PostgreSQLCheckpointStore) Rollback(ctx context.Context, threadID string, version int) error

Rollback 回滚到指定版本

func (*PostgreSQLCheckpointStore) Save

func (s *PostgreSQLCheckpointStore) Save(ctx context.Context, checkpoint *Checkpoint) error

Save 保存检查点

type PostgreSQLClient

type PostgreSQLClient interface {
	Exec(ctx context.Context, query string, args ...any) error
	QueryRow(ctx context.Context, query string, args ...any) Row
	Query(ctx context.Context, query string, args ...any) (Rows, error)
}

PostgreSQLClient PostgreSQL 客户端接口

type PromptBundle

type PromptBundle struct {
	Version     string             `json:"version"`
	System      SystemPrompt       `json:"system"`
	Tools       []types.ToolSchema `json:"tools,omitempty"`
	Examples    []Example          `json:"examples,omitempty"`
	Memory      MemoryConfig       `json:"memory,omitempty"`
	Plan        *PlanConfig        `json:"plan,omitempty"`
	Reflection  *ReflectionConfig  `json:"reflection,omitempty"`
	Constraints []string           `json:"constraints,omitempty"`
}

PromptBundle 模块化提示词包(按版本管理)。

说明:当前版本主要承载 System 模块,其他模块作为扩展点保留。

func NewPromptBundleFromIdentity

func NewPromptBundleFromIdentity(version, identity string) PromptBundle

func (*PromptBundle) AppendExamples

func (b *PromptBundle) AppendExamples(examples ...Example)

AppendExamples 追加 Examples

func (PromptBundle) EffectiveVersion

func (b PromptBundle) EffectiveVersion(defaultVersion string) string

func (PromptBundle) ExtractVariables

func (b PromptBundle) ExtractVariables() []string

ExtractVariables 从 PromptBundle 中提取所有模板变量名

func (PromptBundle) HasExamples

func (b PromptBundle) HasExamples() bool

HasExamples 检查是否有 Few-shot Examples

func (PromptBundle) IsZero

func (b PromptBundle) IsZero() bool

func (PromptBundle) RenderExamplesAsMessages

func (b PromptBundle) RenderExamplesAsMessages() []types.Message

RenderExamplesAsMessages 将 Examples 渲染为 LLM Message 格式

func (PromptBundle) RenderExamplesAsMessagesWithVars

func (b PromptBundle) RenderExamplesAsMessagesWithVars(vars map[string]string) []types.Message

RenderExamplesAsMessagesWithVars 渲染 Examples 并替换变量

func (PromptBundle) RenderSystemPrompt

func (b PromptBundle) RenderSystemPrompt() string

func (PromptBundle) RenderSystemPromptWithVars

func (b PromptBundle) RenderSystemPromptWithVars(vars map[string]string) string

RenderSystemPromptWithVars 渲染系统提示词并替换模板变量

func (PromptBundle) RenderWithVars

func (b PromptBundle) RenderWithVars(vars map[string]string) PromptBundle

RenderWithVars 渲染完整提示词包并替换变量(包括 Examples 中的变量)

type PromptDocument added in v1.1.0

type PromptDocument struct {
	Version     string       `json:"version"`
	System      SystemPrompt `json:"system"`
	Constraints []string     `json:"constraints,omitempty"`
}

PromptDocument is a minimal representation of a stored prompt bundle. Mirrors the fields agent/ needs from mongodb.PromptDocument.

type PromptEnhancer

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

PromptEnhancer 提示词增强器

func NewPromptEnhancer

func NewPromptEnhancer(config PromptEnhancerConfig) *PromptEnhancer

NewPromptEnhancer 创建提示词增强器

func (*PromptEnhancer) EnhancePromptBundle

func (e *PromptEnhancer) EnhancePromptBundle(bundle PromptBundle) PromptBundle

EnhancePromptBundle 增强提示词包

func (*PromptEnhancer) EnhanceUserPrompt

func (e *PromptEnhancer) EnhanceUserPrompt(prompt string, outputFormat string) string

EnhanceUserPrompt 增强用户提示词

type PromptEnhancerConfig

type PromptEnhancerConfig struct {
	UseChainOfThought   bool `json:"use_chain_of_thought"`   // Use Chain of Thought (CoT)
	UseSelfConsistency  bool `json:"use_self_consistency"`   // Use self-consistency
	UseStructuredOutput bool `json:"use_structured_output"`  // Use structured output
	UseFewShot          bool `json:"use_few_shot"`           // Use few-shot learning
	MaxExamples         int  `json:"max_examples,omitempty"` // Maximum number of examples
	UseDelimiters       bool `json:"use_delimiters"`         // Use delimiters
}

============================================================================= Prompt Engineering (merged from prompt_engineering.go) ============================================================================= PromptEnhancerConfig 提示词增强配置

func DefaultPromptEnhancerConfig

func DefaultPromptEnhancerConfig() *PromptEnhancerConfig

DefaultPromptEnhancerConfig 返回默认的提示词增强器配置

type PromptEnhancerRunner added in v1.0.0

type PromptEnhancerRunner interface {
	EnhanceUserPrompt(prompt, context string) (string, error)
}

PromptEnhancerRunner enhances user prompts with additional context. Implemented by: *PromptEnhancer (agent/prompt_enhancer.go)

func AsPromptEnhancerRunner added in v1.0.0

func AsPromptEnhancerRunner(enhancer *PromptEnhancer) PromptEnhancerRunner

AsPromptEnhancerRunner wraps a *PromptEnhancer as a PromptEnhancerRunner.

type PromptOptimizer

type PromptOptimizer struct{}

PromptOptimizer 提示词优化器(基于最佳实践)

func NewPromptOptimizer

func NewPromptOptimizer() *PromptOptimizer

NewPromptOptimizer 创建提示词优化器

func (*PromptOptimizer) OptimizePrompt

func (o *PromptOptimizer) OptimizePrompt(prompt string) string

OptimizePrompt 优化提示词 基于 2025 年最佳实践: 1. 明确具体 2. 提供示例 3. 让模型思考 4. 使用分隔符 5. 拆分复杂任务

type PromptStoreProvider added in v1.1.0

type PromptStoreProvider interface {
	GetActive(ctx context.Context, agentType, name, tenantID string) (PromptDocument, error)
}

PromptStoreProvider loads active prompt bundles from persistent storage. Implemented by: *mongodb.MongoPromptStore (agent/persistence/mongodb/)

type PromptTemplate

type PromptTemplate struct {
	Name        string
	Description string
	Template    string
	Variables   []string
	Examples    []Example
}

PromptTemplate 提示词模板

type PromptTemplateLibrary

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

PromptTemplateLibrary 提示词模板库

func NewPromptTemplateLibrary

func NewPromptTemplateLibrary() *PromptTemplateLibrary

NewPromptTemplateLibrary 创建提示词模板库

func (*PromptTemplateLibrary) GetTemplate

func (l *PromptTemplateLibrary) GetTemplate(name string) (PromptTemplate, bool)

GetTemplate 获取模板

func (*PromptTemplateLibrary) ListTemplates

func (l *PromptTemplateLibrary) ListTemplates() []string

ListTemplates 列出所有模板

func (*PromptTemplateLibrary) RegisterTemplate

func (l *PromptTemplateLibrary) RegisterTemplate(template PromptTemplate)

RegisterTemplate 注册自定义模板

func (*PromptTemplateLibrary) RenderTemplate

func (l *PromptTemplateLibrary) RenderTemplate(name string, vars map[string]string) (string, error)

RenderTemplate 渲染模板

type RealtimeCoordinator

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

RealtimeCoordinator 实时协调器 支持 Subagents 之间的实时通信和协调

func NewRealtimeCoordinator

func NewRealtimeCoordinator(manager *SubagentManager, eventBus EventBus, logger *zap.Logger) *RealtimeCoordinator

NewRealtimeCoordinator 创建实时协调器

func (*RealtimeCoordinator) CoordinateSubagents

func (c *RealtimeCoordinator) CoordinateSubagents(ctx context.Context, subagents []Agent, input *Input) (*Output, error)

CoordinateSubagents 协调多个 Subagents

type RedisCheckpointStore

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

RedisCheckpointStore Redis 检查点存储

func NewRedisCheckpointStore

func NewRedisCheckpointStore(client RedisClient, prefix string, ttl time.Duration, logger *zap.Logger) *RedisCheckpointStore

NewRedisCheckpointStore 创建 Redis 检查点存储

func (*RedisCheckpointStore) Delete

func (s *RedisCheckpointStore) Delete(ctx context.Context, checkpointID string) error

Delete 删除检查点

func (*RedisCheckpointStore) DeleteThread

func (s *RedisCheckpointStore) DeleteThread(ctx context.Context, threadID string) error

DeleteThread 删除线程

func (*RedisCheckpointStore) List

func (s *RedisCheckpointStore) List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)

List 列出检查点

func (*RedisCheckpointStore) ListVersions

func (s *RedisCheckpointStore) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)

ListVersions 列出线程的所有版本

func (*RedisCheckpointStore) Load

func (s *RedisCheckpointStore) Load(ctx context.Context, checkpointID string) (*Checkpoint, error)

Load 加载检查点

func (*RedisCheckpointStore) LoadLatest

func (s *RedisCheckpointStore) LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)

LoadLatest 加载最新检查点

func (*RedisCheckpointStore) LoadVersion

func (s *RedisCheckpointStore) LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)

LoadVersion 加载指定版本的检查点

func (*RedisCheckpointStore) Rollback

func (s *RedisCheckpointStore) Rollback(ctx context.Context, threadID string, version int) error

Rollback 回滚到指定版本

func (*RedisCheckpointStore) Save

func (s *RedisCheckpointStore) Save(ctx context.Context, checkpoint *Checkpoint) error

Save 保存检查点

type RedisClient

type RedisClient interface {
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
	Get(ctx context.Context, key string) ([]byte, error)
	Delete(ctx context.Context, key string) error
	Keys(ctx context.Context, pattern string) ([]string, error)
	ZAdd(ctx context.Context, key string, score float64, member string) error
	ZRevRange(ctx context.Context, key string, start, stop int64) ([]string, error)
	ZRemRangeByScore(ctx context.Context, key string, min, max string) error
}

RedisClient Redis 客户端接口

type ReflectionConfig

type ReflectionConfig struct {
	Enabled bool `json:"enabled,omitempty"`
}

type ReflectionExecutor

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

ReflectionExecutor Reflection 执行器

func NewReflectionExecutor

func NewReflectionExecutor(agent *BaseAgent, config ReflectionExecutorConfig) *ReflectionExecutor

NewReflectionExecutor 创建 Reflection 执行器

func (*ReflectionExecutor) ExecuteWithReflection

func (r *ReflectionExecutor) ExecuteWithReflection(ctx context.Context, input *Input) (*ReflectionResult, error)

ExecuteWithReflection 执行任务并进行 Reflection

type ReflectionExecutorConfig

type ReflectionExecutorConfig struct {
	Enabled       bool    `json:"enabled"`
	MaxIterations int     `json:"max_iterations"` // Maximum reflection iterations
	MinQuality    float64 `json:"min_quality"`    // Minimum quality threshold (0-1)
	CriticPrompt  string  `json:"critic_prompt"`  // Critic prompt template
}

反射执行器配置

func DefaultReflectionConfig

func DefaultReflectionConfig() *ReflectionExecutorConfig

默认反射 Config 返回默认反射配置

func DefaultReflectionExecutorConfig

func DefaultReflectionExecutorConfig() ReflectionExecutorConfig

默认反射 ExecutorConfig 返回默认反射配置

type ReflectionResult

type ReflectionResult struct {
	FinalOutput          *Output       `json:"final_output"`
	Iterations           int           `json:"iterations"`
	Critiques            []Critique    `json:"critiques"`
	TotalDuration        time.Duration `json:"total_duration"`
	ImprovedByReflection bool          `json:"improved_by_reflection"`
}

ReflectionResult Reflection 执行结果

type ReflectionRunner added in v1.0.0

type ReflectionRunner interface {
	ExecuteWithReflection(ctx context.Context, input *Input) (any, error)
}

ReflectionRunner executes a task with iterative self-reflection. Implemented by: *ReflectionExecutor (agent/reflection.go)

func AsReflectionRunner added in v1.0.0

func AsReflectionRunner(executor *ReflectionExecutor) ReflectionRunner

AsReflectionRunner wraps a *ReflectionExecutor as a ReflectionRunner.

type Row

type Row interface {
	Scan(dest ...any) error
}

Row 数据库行接口

type Rows

type Rows interface {
	Next() bool
	Scan(dest ...any) error
	Close() error
}

Rows 数据库行集合接口

type RunConfig

type RunConfig struct {
	Model              *string           `json:"model,omitempty"`
	Provider           *string           `json:"provider,omitempty"`
	RoutePolicy        *string           `json:"route_policy,omitempty"`
	Temperature        *float32          `json:"temperature,omitempty"`
	MaxTokens          *int              `json:"max_tokens,omitempty"`
	TopP               *float32          `json:"top_p,omitempty"`
	Stop               []string          `json:"stop,omitempty"`
	ToolChoice         *string           `json:"tool_choice,omitempty"`
	Timeout            *time.Duration    `json:"timeout,omitempty"`
	MaxReActIterations *int              `json:"max_react_iterations,omitempty"`
	Metadata           map[string]string `json:"metadata,omitempty"`
	Tags               []string          `json:"tags,omitempty"`
}

RunConfig provides runtime overrides for Agent execution. All pointer fields use nil to indicate "no override" — only non-nil values are applied, leaving the base Config defaults intact.

func GetRunConfig

func GetRunConfig(ctx context.Context) *RunConfig

GetRunConfig retrieves the RunConfig from the context. Returns nil if no RunConfig is present.

func (*RunConfig) ApplyToRequest

func (rc *RunConfig) ApplyToRequest(req *llm.ChatRequest, baseCfg types.AgentConfig)

ApplyToRequest applies RunConfig overrides to a ChatRequest. Fields in baseCfg are used as defaults; only non-nil RunConfig fields override them. If rc is nil, this is a no-op.

func (*RunConfig) EffectiveMaxReActIterations

func (rc *RunConfig) EffectiveMaxReActIterations(defaultVal int) int

EffectiveMaxReActIterations returns the RunConfig override if set, otherwise falls back to defaultVal.

type RunDoc added in v1.1.0

type RunDoc struct {
	ID        string    `json:"id"`
	AgentID   string    `json:"agent_id"`
	TenantID  string    `json:"tenant_id"`
	TraceID   string    `json:"trace_id"`
	Status    string    `json:"status"`
	Input     string    `json:"input"`
	StartTime time.Time `json:"start_time"`
}

RunDoc is a minimal run document for the agent layer.

type RunOutputDoc added in v1.1.0

type RunOutputDoc struct {
	Content      string  `json:"content"`
	TokensUsed   int     `json:"tokens_used"`
	Cost         float64 `json:"cost"`
	FinishReason string  `json:"finish_reason"`
}

RunOutputDoc holds the output portion of a run document.

type RunStoreProvider added in v1.1.0

type RunStoreProvider interface {
	RecordRun(ctx context.Context, doc *RunDoc) error
	UpdateStatus(ctx context.Context, id, status string, output *RunOutputDoc, errMsg string) error
}

RunStoreProvider records agent execution runs. Implemented by: *mongodb.MongoRunStore (agent/persistence/mongodb/)

type RuntimeStreamEmitter

type RuntimeStreamEmitter func(RuntimeStreamEvent)

type RuntimeStreamEvent

type RuntimeStreamEvent struct {
	Type       RuntimeStreamEventType `json:"type"`
	Timestamp  time.Time              `json:"timestamp"`
	Token      string                 `json:"token,omitempty"`
	Delta      string                 `json:"delta,omitempty"`
	ToolCall   *RuntimeToolCall       `json:"tool_call,omitempty"`
	ToolResult *RuntimeToolResult     `json:"tool_result,omitempty"`
	ToolCallID string                 `json:"tool_call_id,omitempty"`
	ToolName   string                 `json:"tool_name,omitempty"`
	Data       any                    `json:"data,omitempty"`
}

type RuntimeStreamEventType

type RuntimeStreamEventType string
const (
	RuntimeStreamToken        RuntimeStreamEventType = "token"
	RuntimeStreamToolCall     RuntimeStreamEventType = "tool_call"
	RuntimeStreamToolResult   RuntimeStreamEventType = "tool_result"
	RuntimeStreamToolProgress RuntimeStreamEventType = "tool_progress"
)

type RuntimeToolCall

type RuntimeToolCall struct {
	ID        string          `json:"id,omitempty"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments,omitempty"`
}

type RuntimeToolResult

type RuntimeToolResult struct {
	ToolCallID string          `json:"tool_call_id,omitempty"`
	Name       string          `json:"name"`
	Result     json.RawMessage `json:"result,omitempty"`
	Error      string          `json:"error,omitempty"`
	Duration   time.Duration   `json:"duration,omitempty"`
}

type ScopedPersistenceStores added in v1.4.6

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

ScopedPersistenceStores wraps PersistenceStores and prefixes all IDs with an agent-specific scope, ensuring sub-agent store operations are isolated.

func NewScopedPersistenceStores added in v1.4.6

func NewScopedPersistenceStores(inner *PersistenceStores, scope string) *ScopedPersistenceStores

NewScopedPersistenceStores creates a scoped wrapper.

func (*ScopedPersistenceStores) LoadPrompt added in v1.4.6

func (s *ScopedPersistenceStores) LoadPrompt(ctx context.Context, agentType, name, tenantID string) *PromptDocument

LoadPrompt delegates to inner (prompts are shared, not scoped).

func (*ScopedPersistenceStores) PersistConversation added in v1.4.6

func (s *ScopedPersistenceStores) PersistConversation(ctx context.Context, conversationID, agentID, tenantID, userID, inputContent, outputContent string)

PersistConversation delegates with scoped conversation ID.

func (*ScopedPersistenceStores) RecordRun added in v1.4.6

func (s *ScopedPersistenceStores) RecordRun(ctx context.Context, agentID, tenantID, traceID, input string, startTime time.Time) string

RecordRun delegates to inner with scoped run ID prefix.

func (*ScopedPersistenceStores) RestoreConversation added in v1.4.6

func (s *ScopedPersistenceStores) RestoreConversation(ctx context.Context, conversationID string) []types.Message

RestoreConversation delegates with scoped conversation ID.

func (*ScopedPersistenceStores) Scope added in v1.4.6

func (s *ScopedPersistenceStores) Scope() string

Scope returns the configured scope prefix.

func (*ScopedPersistenceStores) UpdateRunStatus added in v1.4.6

func (s *ScopedPersistenceStores) UpdateRunStatus(ctx context.Context, runID, status string, output *RunOutputDoc, errMsg string) error

UpdateRunStatus delegates to inner.

type SimpleEventBus

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

SimpleEventBus 简单的事件总线实现

func (*SimpleEventBus) Publish

func (b *SimpleEventBus) Publish(event Event)

Publish 发布事件

func (*SimpleEventBus) Stop

func (b *SimpleEventBus) Stop()

Stop 停止事件总线,等待所有 handler goroutine 完成

func (*SimpleEventBus) Subscribe

func (b *SimpleEventBus) Subscribe(eventType EventType, handler EventHandler) string

Subscribe 订阅事件

func (*SimpleEventBus) Unsubscribe

func (b *SimpleEventBus) Unsubscribe(subscriptionID string)

Unsubscribe 取消订阅

type SkillDiscoverer added in v1.0.0

type SkillDiscoverer interface {
	DiscoverSkills(ctx context.Context, task string) ([]*skills.Skill, error)
}

SkillDiscoverer discovers skills relevant to a task. Implemented by: *skills.DefaultSkillManager (agent/skills/)

type State

type State = agentcore.State

State 定义 Agent 生命周期状态。

const (
	StateInit      State = agentcore.StateInit
	StateReady     State = agentcore.StateReady
	StateRunning   State = agentcore.StateRunning
	StatePaused    State = agentcore.StatePaused
	StateCompleted State = agentcore.StateCompleted
	StateFailed    State = agentcore.StateFailed
)

type StateChangeEvent

type StateChangeEvent struct {
	AgentID_   string
	FromState  State
	ToState    State
	Timestamp_ time.Time
}

StateChangeEvent 状态变更事件

func (*StateChangeEvent) Timestamp

func (e *StateChangeEvent) Timestamp() time.Time

func (*StateChangeEvent) Type

func (e *StateChangeEvent) Type() EventType

type SubagentCompletedEvent

type SubagentCompletedEvent struct {
	ExecutionID string
	AgentID     string
	Output      *Output
	Timestamp_  time.Time
}

SubagentCompletedEvent Subagent 完成事件

func (*SubagentCompletedEvent) Timestamp

func (e *SubagentCompletedEvent) Timestamp() time.Time

func (*SubagentCompletedEvent) Type

type SubagentManager

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

SubagentManager Subagent 管理器

func NewSubagentManager

func NewSubagentManager(logger *zap.Logger) *SubagentManager

NewSubagentManager 创建 Subagent 管理器

func (*SubagentManager) CleanupCompleted

func (m *SubagentManager) CleanupCompleted(olderThan time.Duration) int

CleanupCompleted 清理已完成的执行

func (*SubagentManager) Close added in v1.1.0

func (m *SubagentManager) Close()

Close 停止自动清理 goroutine。

func (*SubagentManager) GetExecution

func (m *SubagentManager) GetExecution(executionID string) (*AsyncExecution, error)

GetExecution 获取执行状态

func (*SubagentManager) ListExecutions

func (m *SubagentManager) ListExecutions() []*AsyncExecution

ListExecutions 列出所有执行

func (*SubagentManager) SpawnSubagent

func (m *SubagentManager) SpawnSubagent(ctx context.Context, subagent Agent, input *Input) (*AsyncExecution, error)

SpawnSubagent 创建 Subagent 执行

type SystemPrompt

type SystemPrompt struct {
	Role        string   `json:"role,omitempty"`
	Identity    string   `json:"identity,omitempty"`
	Policies    []string `json:"policies,omitempty"`
	OutputRules []string `json:"output_rules,omitempty"`
	Prohibits   []string `json:"prohibits,omitempty"`
}

func (SystemPrompt) IsZero

func (s SystemPrompt) IsZero() bool

func (SystemPrompt) Render

func (s SystemPrompt) Render() string

type ToolCallEvent

type ToolCallEvent struct {
	AgentID_            string
	RunID               string
	TraceID             string
	PromptBundleVersion string
	ToolCallID          string
	ToolName            string
	Stage               string // start/end
	Error               string
	Timestamp_          time.Time
}

ToolCallEvent 工具调用事件

func (*ToolCallEvent) Timestamp

func (e *ToolCallEvent) Timestamp() time.Time

func (*ToolCallEvent) Type

func (e *ToolCallEvent) Type() EventType

type ToolManager

type ToolManager interface {
	GetAllowedTools(agentID string) []types.ToolSchema
	ExecuteForAgent(ctx context.Context, agentID string, calls []types.ToolCall) []llmtools.ToolResult
}

ToolManager为Agent运行时间摘要了"工具列表+工具执行"的能力.

设计目标: - 直接根据pkg/剂/工具避免pkg/剂(取消进口周期) - 允许在应用程序层注入不同的执行(默认使用工具)。 工具管理器)

type ToolScore

type ToolScore struct {
	Tool               types.ToolSchema `json:"tool"`
	SemanticSimilarity float64          `json:"semantic_similarity"` // Semantic similarity (0-1)
	EstimatedCost      float64          `json:"estimated_cost"`      // Estimated cost
	AvgLatency         time.Duration    `json:"avg_latency"`         // Average latency
	ReliabilityScore   float64          `json:"reliability_score"`   // Reliability (0-1)
	TotalScore         float64          `json:"total_score"`         // Total score (0-1)
}

ToolScore 工具评分

type ToolSelectionConfig

type ToolSelectionConfig struct {
	Enabled bool `json:"enabled"`

	// 分数
	SemanticWeight    float64 `json:"semantic_weight"`    // Semantic similarity weight
	CostWeight        float64 `json:"cost_weight"`        // Cost weight
	LatencyWeight     float64 `json:"latency_weight"`     // Latency weight
	ReliabilityWeight float64 `json:"reliability_weight"` // Reliability weight

	// 甄选战略
	MaxTools      int     `json:"max_tools"`       // Maximum number of tools to select
	MinScore      float64 `json:"min_score"`       // Minimum score threshold
	UseLLMRanking bool    `json:"use_llm_ranking"` // Whether to use LLM-assisted ranking
}

ToolSelectionConfig 工具选择配置

func DefaultToolSelectionConfig

func DefaultToolSelectionConfig() *ToolSelectionConfig

默认工具SecutConfig 返回默认工具选择配置

type ToolSelector

type ToolSelector interface {
	// SelectTools 基于任务选择最佳工具
	SelectTools(ctx context.Context, task string, availableTools []types.ToolSchema) ([]types.ToolSchema, error)

	// ScoreTools 对工具进行评分
	ScoreTools(ctx context.Context, task string, tools []types.ToolSchema) ([]ToolScore, error)
}

ToolSelector 工具选择器接口

type ToolStats

type ToolStats struct {
	Name            string
	TotalCalls      int64
	SuccessfulCalls int64
	FailedCalls     int64
	TotalLatency    time.Duration
	AvgCost         float64
}

ToolStats 工具统计信息

Directories

Path Synopsis
mongodb
Package mongodb provides adapter types that bridge the concrete MongoDB store implementations to the agent-layer interfaces defined in agent/interfaces.go.
Package mongodb provides adapter types that bridge the concrete MongoDB store implementations to the agent-layer interfaces defined in agent/interfaces.go.
protocol
a2a
mcp

Jump to

Keyboard shortcuts

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