agent

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SessionKeyContextKey contextKey = "session_key"
	AgentIDContextKey    contextKey = "agent_id"
)
View Source
const (
	DefaultInstallTimeout = 5 * time.Minute
)

Default installation timeout

Variables

View Source
var DefaultToolDenyList = []string{
	"sessions_spawn",
	"sessions_list",
	"sessions_history",
	"sessions_delete",
	"gateway",
	"cron",
}

DefaultToolDenyList 默认拒绝的工具列表

Functions

func BuildSubagentSystemPrompt

func BuildSubagentSystemPrompt(params *SubagentSystemPromptParams) string

BuildSubagentSystemPrompt 构建分身系统提示词

func GenerateChildSessionKey

func GenerateChildSessionKey(agentID string) string

GenerateChildSessionKey 生成子会话密钥

func GenerateRunID

func GenerateRunID() string

GenerateRunID 生成运行ID

func IsRetryableError added in v0.4.0

func IsRetryableError(err error, classifier errors.ErrorClassifier) bool

IsRetryableError 检查错误是否可重试(辅助函数)

func IsSubagentSessionKey

func IsSubagentSessionKey(sessionKey string) bool

IsSubagentSessionKey 判断是否为分身会话密钥

func ParseAgentSessionKey

func ParseAgentSessionKey(sessionKey string) (agentID string, subagentID string, isSubagent bool)

ParseAgentSessionKey 解析 Agent 会话密钥

func ParseFrontmatter added in v0.2.0

func ParseFrontmatter(content string) map[string]string

ParseFrontmatter 解析 YAML frontmatter

func ParseOpenClawMetadata added in v0.2.0

func ParseOpenClawMetadata(frontmatter map[string]string) map[string]any

ParseOpenClawMetadata 解析 OpenClaw/goclaw 特定的元数据

func StripFrontmatter added in v0.2.0

func StripFrontmatter(content string) string

StripFrontmatter 移除 YAML frontmatter

func ToExistingTools

func ToExistingTools(agentTools []Tool) []tools.Tool

ToExistingTools converts agent tools to existing tools.Tool format

func ValidateToolParameters added in v0.2.0

func ValidateToolParameters(params map[string]any, schema map[string]any) error

ValidateToolParameters validates tool parameters against schema

Types

type Agent

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

Agent represents the main AI agent New implementation inspired by pi-mono architecture

func NewAgent

func NewAgent(cfg *NewAgentConfig) (*Agent, error)

NewAgent creates a new agent

func (*Agent) Abort added in v0.2.0

func (a *Agent) Abort()

Abort aborts the current agent execution Inspired by pi-mono's Agent.abort() method

func (*Agent) FollowUp added in v0.2.0

func (a *Agent) FollowUp(msg AgentMessage)

FollowUp adds a follow-up message to be processed after agent finishes Inspired by pi-mono's Agent.followUp() method

func (*Agent) GetCurrentChannel

func (a *Agent) GetCurrentChannel() string

GetCurrentChannel returns the current output channel

func (*Agent) GetCurrentChatID

func (a *Agent) GetCurrentChatID() string

GetCurrentChatID returns the current chat ID

func (*Agent) GetOrchestrator

func (a *Agent) GetOrchestrator() *Orchestrator

GetOrchestrator 获取 orchestrator(供 AgentManager 使用)

func (*Agent) GetState

func (a *Agent) GetState() *AgentState

GetState returns a copy of the current agent state

func (*Agent) Prompt

func (a *Agent) Prompt(ctx context.Context, content string) error

Prompt sends a user message to the agent

func (*Agent) ReplaceMessages added in v0.2.0

func (a *Agent) ReplaceMessages(messages []AgentMessage)

ReplaceMessages replaces the message history Inspired by pi-mono's Agent.replaceMessages() method

func (*Agent) Reset added in v0.2.0

func (a *Agent) Reset()

Reset resets the agent state Inspired by pi-mono's Agent.reset() method

func (*Agent) SetFollowUpMode added in v0.2.0

func (a *Agent) SetFollowUpMode(mode MessageQueueMode)

SetFollowUpMode sets how follow-up messages are delivered

func (*Agent) SetSteeringMode added in v0.2.0

func (a *Agent) SetSteeringMode(mode MessageQueueMode)

SetSteeringMode sets how steering messages are delivered

func (*Agent) SetSystemPrompt

func (a *Agent) SetSystemPrompt(prompt string)

SetSystemPrompt updates the system prompt

func (*Agent) SetTools

func (a *Agent) SetTools(tools []Tool)

SetTools updates the available tools

func (*Agent) Start

func (a *Agent) Start(ctx context.Context) error

Start starts the agent loop

func (*Agent) Steer added in v0.2.0

func (a *Agent) Steer(msg AgentMessage)

Steer adds a steering message to interrupt the agent mid-run Inspired by pi-mono's Agent.steer() method

func (*Agent) Stop

func (a *Agent) Stop() error

Stop stops the agent

func (*Agent) Subscribe

func (a *Agent) Subscribe() <-chan *Event

Subscribe subscribes to agent events Returns a read-only channel. Call Unsubscribe to clean up. IMPORTANT: Always call Unsubscribe when done to prevent memory leaks.

func (*Agent) Unsubscribe

func (a *Agent) Unsubscribe(ch <-chan *Event)

Unsubscribe removes an event subscription The channel will be removed from the subscriber list but not closed (since it's receive-only from the caller's perspective). Any pending events in the channel can still be read by the caller.

func (*Agent) WaitForIdle added in v0.2.0

func (a *Agent) WaitForIdle(ctx context.Context) error

WaitForIdle waits until the agent is not streaming Inspired by pi-mono's Agent.waitForIdle() method

type AgentHelper added in v0.2.0

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

AgentHelper provides helper functions for agent message processing

func NewAgentHelper added in v0.2.0

func NewAgentHelper(sessionMgr *session.Manager) *AgentHelper

NewAgentHelper creates a new agent helper

func (*AgentHelper) UpdateSession added in v0.2.0

func (h *AgentHelper) UpdateSession(sess *session.Session, messages []AgentMessage, opts *UpdateSessionOptions) error

UpdateSession updates the session with new messages This function is shared between Agent and AgentManager to avoid code duplication

type AgentManager

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

AgentManager 管理多个 Agent 实例

func NewAgentManager

func NewAgentManager(cfg *NewAgentManagerConfig) *AgentManager

NewAgentManager 创建 Agent 管理器

func (*AgentManager) GetAgent

func (m *AgentManager) GetAgent(agentID string) (*Agent, bool)

GetAgent 获取 Agent

func (*AgentManager) GetDefaultAgent

func (m *AgentManager) GetDefaultAgent() *Agent

GetDefaultAgent 获取默认 Agent

func (*AgentManager) GetToolsInfo

func (m *AgentManager) GetToolsInfo() (map[string]interface{}, error)

GetToolsInfo 获取工具信息

func (*AgentManager) ListAgents

func (m *AgentManager) ListAgents() []string

ListAgents 列出所有 Agent ID

func (*AgentManager) RouteInbound

func (m *AgentManager) RouteInbound(ctx context.Context, msg *bus.InboundMessage) error

RouteInbound 路由入站消息到对应的 Agent

func (*AgentManager) SetupFromConfig

func (m *AgentManager) SetupFromConfig(cfg *config.Config, contextBuilder *ContextBuilder) error

SetupFromConfig 从配置设置 Agent 和绑定

func (*AgentManager) Start

func (m *AgentManager) Start(ctx context.Context) error

Start 启动所有 Agent

func (*AgentManager) Stop

func (m *AgentManager) Stop() error

Stop 停止所有 Agent

type AgentMessage

type AgentMessage struct {
	ID        string         `json:"id,omitempty"`
	Role      MessageRole    `json:"role"`
	Content   []ContentBlock `json:"content"`
	Timestamp int64          `json:"timestamp,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

AgentMessage represents a message in the agent conversation (renamed to avoid conflict with context.go)

type AgentState

type AgentState struct {
	SystemPrompt  string
	Model         string
	Provider      string
	ThinkingLevel string // off, minimal, low, medium, high, xhigh
	Tools         []Tool
	Messages      []AgentMessage
	IsStreaming   bool
	StreamMessage *AgentMessage // Current streaming message
	PendingTools  map[string]bool
	Error         error

	// Queues for message injection (inspired by pi-mono)
	SteeringQueue []AgentMessage
	SteeringMode  MessageQueueMode
	FollowUpQueue []AgentMessage
	FollowUpMode  MessageQueueMode

	// Session key
	SessionKey string

	// Skills support
	LoadedSkills []string
}

AgentState represents the current state of the agent

func NewAgentState

func NewAgentState() *AgentState

NewAgentState creates a new agent state

func (*AgentState) AddMessage

func (s *AgentState) AddMessage(msg AgentMessage)

AddMessage adds a message to the agent state

func (*AgentState) AddMessages

func (s *AgentState) AddMessages(msgs []AgentMessage)

AddMessages adds multiple messages to the agent state

func (*AgentState) AddPendingTool

func (s *AgentState) AddPendingTool(toolID string)

AddPendingTool adds a tool to the pending set

func (*AgentState) ClearMessages

func (s *AgentState) ClearMessages()

ClearMessages clears all messages from the agent state

func (*AgentState) ClearPendingTools

func (s *AgentState) ClearPendingTools()

ClearPendingTools clears all pending tools

func (*AgentState) Clone

func (s *AgentState) Clone() *AgentState

Clone creates a deep copy of the agent state

func (*AgentState) DequeueFollowUpMessages

func (s *AgentState) DequeueFollowUpMessages() []AgentMessage

DequeueFollowUpMessages gets and clears follow-up messages based on queue mode

func (*AgentState) DequeueSteeringMessages

func (s *AgentState) DequeueSteeringMessages() []AgentMessage

DequeueSteeringMessages gets and clears steering messages based on queue mode

func (*AgentState) FollowUp

func (s *AgentState) FollowUp(msg AgentMessage)

FollowUp adds a follow-up message to be processed after agent finishes

func (*AgentState) GetLastMessage

func (s *AgentState) GetLastMessage() *AgentMessage

GetLastMessage returns the last message in the state

func (*AgentState) HasPendingToolCalls

func (s *AgentState) HasPendingToolCalls() bool

HasPendingToolCalls checks if there are pending tool executions

func (*AgentState) HasQueuedMessages

func (s *AgentState) HasQueuedMessages() bool

HasQueuedMessages checks if there are queued messages

func (*AgentState) RemovePendingTool

func (s *AgentState) RemovePendingTool(toolID string)

RemovePendingTool removes a tool from the pending set

func (*AgentState) Steer

func (s *AgentState) Steer(msg AgentMessage)

Steer adds a steering message to interrupt the agent mid-run

type AgentTool added in v0.2.0

type AgentTool interface {
	// Name returns the tool name (used for tool calls)
	Name() string

	// Description returns what the tool does
	Description() string

	// Parameters returns JSON Schema for the tool's parameters
	Parameters() map[string]any

	// Label returns a human-readable label for UI display
	// Inspired by pi-mono's AgentTool.label
	Label() string

	// Execute runs the tool with streaming update support
	// toolCallId: unique identifier for this tool call
	// params: validated parameters
	// signal: cancellation signal
	// onUpdate: callback for streaming updates
	Execute(ctx context.Context, toolCallId string, params map[string]any, signal context.Context, onUpdate func(AgentToolResult)) (AgentToolResult, error)
}

AgentTool is the unified tool interface for the agent Inspired by pi-mono's AgentTool<TParameters, TDetails> interface

func AdaptTool added in v0.2.0

func AdaptTool(tool Tool) AgentTool

AdaptTool converts an existing Tool to AgentTool

func AgentToolFromFunc added in v0.2.0

func AgentToolFromFunc(name, label, description string, parameters map[string]any, fn func(ctx context.Context, params map[string]any) (string, error)) AgentTool

AgentToolFromFunc creates an AgentTool from a simple function

func ToAgentToolsSlice added in v0.2.0

func ToAgentToolsSlice(tools []Tool) []AgentTool

ToAgentTools converts a slice of Tool to AgentTool

type AgentToolResult added in v0.2.0

type AgentToolResult struct {
	// Content blocks supporting text and images
	Content []ContentBlock `json:"content"`
	// Details to be displayed in a UI or logged
	Details map[string]any `json:"details"`
}

AgentToolResult represents the result of a tool execution Inspired by pi-mono's AgentToolResult<T>

func NewAgentToolResult added in v0.2.0

func NewAgentToolResult(content string) AgentToolResult

NewAgentToolResult creates a new tool result

func NewAgentToolResultWithDetails added in v0.2.0

func NewAgentToolResultWithDetails(content string, details map[string]any) AgentToolResult

NewAgentToolResultWithDetails creates a new tool result with details

type AnnounceCallback

type AnnounceCallback func(sessionKey, message string) error

AnnounceCallback 宣告回调

type BaseAgentTool added in v0.2.0

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

BaseAgentTool provides a base implementation of AgentTool

func NewBaseAgentTool added in v0.2.0

func NewBaseAgentTool(name, label, description string, parameters map[string]any, executeFunc func(ctx context.Context, toolCallId string, params map[string]any, signal context.Context, onUpdate func(AgentToolResult)) (AgentToolResult, error)) *BaseAgentTool

NewBaseAgentTool creates a new base agent tool

func (*BaseAgentTool) Description added in v0.2.0

func (t *BaseAgentTool) Description() string

Description returns the tool description

func (*BaseAgentTool) Execute added in v0.2.0

func (t *BaseAgentTool) Execute(ctx context.Context, toolCallId string, params map[string]any, signal context.Context, onUpdate func(AgentToolResult)) (AgentToolResult, error)

Execute executes the tool

func (*BaseAgentTool) Label added in v0.2.0

func (t *BaseAgentTool) Label() string

Label returns the tool label

func (*BaseAgentTool) Name added in v0.2.0

func (t *BaseAgentTool) Name() string

Name returns the tool name

func (*BaseAgentTool) Parameters added in v0.2.0

func (t *BaseAgentTool) Parameters() map[string]any

Parameters returns the tool parameters

type BindingEntry

type BindingEntry struct {
	AgentID   string
	Channel   string
	AccountID string
	Agent     *Agent
}

BindingEntry Agent 绑定条目

type ContentBlock

type ContentBlock interface {
	ContentType() string
}

ContentBlock represents a block of content in a message

type ContextBuilder

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

ContextBuilder 上下文构建器

func NewContextBuilder

func NewContextBuilder(memory *MemoryStore, workspace string) *ContextBuilder

NewContextBuilder 创建上下文构建器

func (*ContextBuilder) BuildMessages

func (b *ContextBuilder) BuildMessages(history []session.Message, currentMessage string, skills []*Skill, loadedSkills []string) []Message

BuildMessages 构建消息列表

func (*ContextBuilder) BuildMessagesWithMode

func (b *ContextBuilder) BuildMessagesWithMode(history []session.Message, currentMessage string, skills []*Skill, loadedSkills []string, mode PromptMode) []Message

BuildMessagesWithMode 使用指定模式构建消息列表

func (*ContextBuilder) BuildSystemPrompt

func (b *ContextBuilder) BuildSystemPrompt(skills []*Skill) string

BuildSystemPrompt 构建系统提示词

func (*ContextBuilder) BuildSystemPromptWithMode

func (b *ContextBuilder) BuildSystemPromptWithMode(skills []*Skill, mode PromptMode) string

BuildSystemPromptWithMode 使用指定模式构建系统提示词

type DeliveryContext

type DeliveryContext struct {
	Channel   string `json:"channel,omitempty"`
	AccountID string `json:"account_id,omitempty"`
	To        string `json:"to,omitempty"`
	ThreadID  string `json:"thread_id,omitempty"`
}

DeliveryContext 传递上下文

type Event

type Event struct {
	Type      EventType     `json:"type"`
	Message   *AgentMessage `json:"message,omitempty"`
	Timestamp int64         `json:"timestamp"`
	// Tool execution fields
	ToolID     string         `json:"tool_id,omitempty"`
	ToolName   string         `json:"tool_name,omitempty"`
	ToolArgs   map[string]any `json:"tool_args,omitempty"`
	ToolResult *ToolResult    `json:"tool_result,omitempty"`
	ToolError  bool           `json:"tool_error,omitempty"`
	// Turn end fields
	StopReason    string         `json:"stop_reason,omitempty"`
	FinalMessages []AgentMessage `json:"final_messages,omitempty"`
	// Message update event
	AssistantMessageEvent interface{} `json:"assistant_message_event,omitempty"`
	// Streaming fields
	StreamContent string `json:"stream_content,omitempty"`
}

Event represents an event from the agent

func NewEvent

func NewEvent(eventType EventType) *Event

NewEvent creates a new event with current timestamp

func (*Event) WithFinalMessages

func (e *Event) WithFinalMessages(msgs []AgentMessage) *Event

WithFinalMessages adds final messages to the event

func (*Event) WithMessage

func (e *Event) WithMessage(msg *AgentMessage) *Event

WithMessage adds message to the event

func (*Event) WithStopReason

func (e *Event) WithStopReason(reason string) *Event

WithStopReason adds stop reason to the event

func (*Event) WithToolExecution

func (e *Event) WithToolExecution(toolID, toolName string, args map[string]any) *Event

WithToolExecution adds tool execution info to the event

func (*Event) WithToolResult

func (e *Event) WithToolResult(result *ToolResult, isError bool) *Event

WithToolResult adds tool result to the event

type EventType

type EventType string

EventType represents types of events emitted by the agent

const (
	EventAgentStart          EventType = "agent_start"
	EventAgentEnd            EventType = "agent_end"
	EventTurnStart           EventType = "turn_start"
	EventTurnEnd             EventType = "turn_end"
	EventMessageStart        EventType = "message_start"
	EventMessageUpdate       EventType = "message_update"
	EventMessageEnd          EventType = "message_end"
	EventToolExecutionStart  EventType = "tool_execution_start"
	EventToolExecutionUpdate EventType = "tool_execution_update"
	EventToolExecutionEnd    EventType = "tool_execution_end"
	// Streaming events
	EventStreamContent  EventType = "stream_content"
	EventStreamThinking EventType = "stream_thinking"
	EventStreamFinal    EventType = "stream_final"
	EventStreamDone     EventType = "stream_done"
)

type ImageContent

type ImageContent struct {
	URL      string `json:"url,omitempty"`
	Data     string `json:"data,omitempty"` // base64
	MimeType string `json:"mimeType,omitempty"`
}

ImageContent represents image content

func (ImageContent) ContentType

func (i ImageContent) ContentType() string

type LoopConfig

type LoopConfig struct {
	Model         string
	Provider      providers.Provider
	SessionMgr    *session.Manager
	MaxIterations int
	SessionID     string
	ToolTimeout   time.Duration // Timeout for individual tool executions (default: 3 minutes)
	Retry         *RetryConfig  // Retry configuration

	// Hooks for message transformation
	ConvertToLLM     func([]AgentMessage) ([]providers.Message, error)
	TransformContext func([]AgentMessage) ([]AgentMessage, error)

	// Queues for message injection
	GetSteeringMessages func() ([]AgentMessage, error)
	GetFollowUpMessages func() ([]AgentMessage, error)

	// Skills support
	Skills         []*Skill
	LoadedSkills   []string
	ContextBuilder *ContextBuilder

	// Error handling
	ErrorClassifier errors.ErrorClassifier
}

LoopConfig contains configuration for the agent loop

type MemoryStore

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

MemoryStore 记忆存储

func NewMemoryStore

func NewMemoryStore(workspace string) *MemoryStore

NewMemoryStore 创建记忆存储

func (*MemoryStore) AppendLongTerm

func (m *MemoryStore) AppendLongTerm(content string) error

AppendLongTerm 追加到长期记忆

func (*MemoryStore) AppendToday

func (m *MemoryStore) AppendToday(content string) error

AppendToday 追加到今日笔记

func (*MemoryStore) EnsureBootstrapFiles

func (m *MemoryStore) EnsureBootstrapFiles() error

EnsureBootstrapFiles 确保 bootstrap 文件存在

func (*MemoryStore) GetMemoryContext

func (m *MemoryStore) GetMemoryContext() (string, error)

GetMemoryContext 获取格式化的记忆上下文

func (*MemoryStore) ReadBootstrapFile

func (m *MemoryStore) ReadBootstrapFile(filename string) (string, error)

ReadBootstrapFile 读取 bootstrap 文件

func (*MemoryStore) ReadLongTerm

func (m *MemoryStore) ReadLongTerm() (string, error)

ReadLongTerm 读取长期记忆

func (*MemoryStore) ReadToday

func (m *MemoryStore) ReadToday() (string, error)

ReadToday 读取今日笔记

type Message

type Message struct {
	Role       string     `json:"role"`
	Content    string     `json:"content"`
	Images     []string   `json:"images,omitempty"`
	ToolCallID string     `json:"tool_call_id,omitempty"`
	ToolCalls  []ToolCall `json:"tool_calls,omitempty"`
}

Message 消息(用于 LLM)

type MessageQueueMode added in v0.2.0

type MessageQueueMode string

MessageQueueMode defines how messages are delivered from queues

const (
	// QueueModeAll delivers all queued messages at once
	QueueModeAll MessageQueueMode = "all"
	// QueueModeOneAtATime delivers messages one at a time
	QueueModeOneAtATime MessageQueueMode = "one-at-a-time"
)

type MessageRole

type MessageRole string

MessageRole represents the role of a message

const (
	RoleUser       MessageRole = "user"
	RoleAssistant  MessageRole = "assistant"
	RoleToolResult MessageRole = "tool"
	RoleSystem     MessageRole = "system"
)

type MissingDeps

type MissingDeps struct {
	Bins       []string `yaml:"bins"`       // 缺失的二进制
	AnyBins    []string `yaml:"anyBins"`    // 缺失的可选二进制
	Env        []string `yaml:"env"`        // 缺失的环境变量
	PythonPkgs []string `yaml:"pythonPkgs"` // 缺失的Python包
	NodePkgs   []string `yaml:"nodePkgs"`   // 缺失的Node.js包
}

MissingDeps 缺失的依赖信息

type NewAgentConfig

type NewAgentConfig struct {
	Bus                *bus.MessageBus
	Provider           providers.Provider
	SessionMgr         *session.Manager
	Tools              *ToolRegistry
	Context            *ContextBuilder
	Workspace          string
	MaxIteration       int
	MaxHistoryMessages int // 最大历史消息数量
	SkillsLoader       *SkillsLoader
	Retry              *RetryConfig // Retry configuration
}

NewAgentConfig configures the agent

type NewAgentManagerConfig

type NewAgentManagerConfig struct {
	Bus            *bus.MessageBus
	Provider       providers.Provider
	SessionMgr     *session.Manager
	Tools          *ToolRegistry
	DataDir        string          // 数据目录,用于存储分身注册表
	ContextBuilder *ContextBuilder // 上下文构建器
	SkillsLoader   *SkillsLoader   // 技能加载器
	ChannelMgr     *channels.Manager
}

NewAgentManagerConfig AgentManager 配置

type Orchestrator

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

Orchestrator manages the agent execution loop Based on pi-mono's agent-loop.ts design

Concurrency: Each Run() call creates a cloned state for isolation. The original state stored in o.state is used only as a template. Multiple Run() calls can execute concurrently safely.

func NewOrchestrator

func NewOrchestrator(config *LoopConfig, initialState *AgentState) *Orchestrator

NewOrchestrator creates a new agent orchestrator

func (*Orchestrator) Run

func (o *Orchestrator) Run(ctx context.Context, prompts []AgentMessage) ([]AgentMessage, error)

Run starts the agent loop with initial prompts

func (*Orchestrator) Stop

func (o *Orchestrator) Stop()

Stop stops the orchestrator Safe to call multiple times

func (*Orchestrator) Subscribe

func (o *Orchestrator) Subscribe() <-chan *Event

Subscribe returns the event channel

type PackageType

type PackageType string

PackageType 包类型枚举

const (
	PackageTypePython PackageType = "python"
	PackageTypeNode   PackageType = "node"
)

type PromptMode

type PromptMode string

PromptMode 控制系统提示词中包含哪些硬编码部分 - "full": 所有部分(默认,用于主 agent) - "minimal": 精简部分(Tooling, Workspace, Runtime)- 用于子 agent - "none": 仅基本身份行,没有部分

const (
	PromptModeFull    PromptMode = "full"
	PromptModeMinimal PromptMode = "minimal"
	PromptModeNone    PromptMode = "none"
)

type RecoveryAction added in v0.4.0

type RecoveryAction string

RecoveryAction 恢复动作

const (
	RecoveryActionNone            RecoveryAction = "none"
	RecoveryActionRotateProfile   RecoveryAction = "rotate_profile"
	RecoveryActionBackoff         RecoveryAction = "backoff"
	RecoveryActionCompressContext RecoveryAction = "compress_context"
)

type RetryConfig added in v0.4.0

type RetryConfig struct {
	Enabled               bool
	MaxRetries            int
	InitialDelay          time.Duration
	MaxDelay              time.Duration
	BackoffFactor         float64
	RetryableErrors       []string
	ContextOverflowAction string
}

RetryConfig 重试配置(用于 agent 包内部)

func DefaultRetryConfig added in v0.4.0

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig 返回默认重试配置

type RetryDecision added in v0.4.0

type RetryDecision struct {
	ShouldRetry     bool
	Delay           time.Duration
	Action          RecoveryAction
	ProfileToUse    string
	CompressContext bool
	Reason          string
}

RetryDecision 重试决策

type RetryManager added in v0.4.0

type RetryManager interface {
	ShouldRetry(err error) bool
	GetDelay() time.Duration
	RecordError(err error) RetryDecision
	RecordSuccess()
	GetState() *RetryState
	Reset()
}

RetryManager 重试管理器接口

func NewRetryManager added in v0.4.0

func NewRetryManager(cfg *RetryConfig, classifier errors.ErrorClassifier) RetryManager

NewRetryManager 创建重试管理器

type RetryState added in v0.4.0

type RetryState struct {
	Attempt         int
	LastError       error
	LastErrorReason errors.FailoverReason
	NextRetryAt     time.Time
	TotalDelay      time.Duration
}

RetryState 重试状态

type SearchResult

type SearchResult struct {
	Skill   *Skill
	Source  string // skill的来源路径
	Score   float64
	Matches []string // 匹配的字段
}

SearchResult 搜索结果

type Skill

type Skill struct {
	Name        string `yaml:"name"`
	Description string `yaml:"description"`
	Version     string `yaml:"version"`
	Author      string `yaml:"author"`
	Homepage    string `yaml:"homepage"`
	Always      bool   `yaml:"always"`
	Metadata    struct {
		OpenClaw struct {
			Emoji    string `yaml:"emoji"`
			Always   bool   `yaml:"always"`
			Requires struct {
				Bins       []string `yaml:"bins"`
				AnyBins    []string `yaml:"anyBins"`
				Env        []string `yaml:"env"`
				Config     []string `yaml:"config"`
				OS         []string `yaml:"os"`
				PythonPkgs []string `yaml:"pythonPkgs"` // Python包依赖
				NodePkgs   []string `yaml:"nodePkgs"`   // Node.js包依赖
			} `yaml:"requires"`
			Install []SkillInstall `yaml:"install"`
		} `yaml:"openclaw"`
	} `yaml:"metadata"`
	Requires SkillRequirements `yaml:"requires"` // 兼容旧格式
	Content  string            `yaml:"-"`        // 技能内容(Markdown)
	// 缺失的依赖信息
	MissingDeps *MissingDeps `yaml:"-"` // 解析时填充
}

Skill 技能定义

type SkillInstall

type SkillInstall struct {
	ID      string   `yaml:"id"`      // 安装方式唯一标识
	Kind    string   `yaml:"kind"`    // 安装方式: brew, apt, npm, pip, uv, go
	Formula string   `yaml:"formula"` // 包名 (brew, apt)
	Package string   `yaml:"package"` // 包名 (npm, pip, go)
	Bins    []string `yaml:"bins"`    // 安装后提供的可执行文件
	Label   string   `yaml:"label"`   // 安装说明
	OS      []string `yaml:"os"`      // 适用的操作系统
	Command string   `yaml:"command"` // 自定义安装命令
}

SkillInstall 技能安装配置

type SkillRequirements

type SkillRequirements struct {
	Bins []string `yaml:"bins"`
	Env  []string `yaml:"env"`
}

SkillRequirements 技能需求 (旧格式)

type SkillsLoader

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

SkillsLoader 技能加载器

func NewSkillsLoader

func NewSkillsLoader(workspace string, skillsDirs []string) *SkillsLoader

NewSkillsLoader 创建技能加载器

func (*SkillsLoader) BuildSummary

func (l *SkillsLoader) BuildSummary() string

BuildSummary 构建技能摘要

func (*SkillsLoader) Discover

func (l *SkillsLoader) Discover() error

Discover 发现技能 按照顺序加载技能,后加载的同名技能会覆盖前面的

func (*SkillsLoader) Get

func (l *SkillsLoader) Get(name string) (*Skill, bool)

Get 获取技能

func (*SkillsLoader) GetAlwaysSkills

func (l *SkillsLoader) GetAlwaysSkills() []string

GetAlwaysSkills 获取始终加载的技能

func (*SkillsLoader) InstallDependencies

func (l *SkillsLoader) InstallDependencies(skillName string) error

InstallDependencies 安装技能依赖

func (*SkillsLoader) List

func (l *SkillsLoader) List() []*Skill

List 列出所有技能

func (*SkillsLoader) LoadContent

func (l *SkillsLoader) LoadContent(name string) (string, error)

LoadContent 加载技能内容

func (*SkillsLoader) Search

func (l *SkillsLoader) Search(query string) []*SearchResult

Search 搜索技能

func (*SkillsLoader) SetAutoInstall

func (l *SkillsLoader) SetAutoInstall(enabled bool)

SetAutoInstall 设置是否启用自动安装

func (*SkillsLoader) SetInstallTimeout added in v0.2.0

func (l *SkillsLoader) SetInstallTimeout(timeout time.Duration)

SetInstallTimeout 设置安装超时时间

type SubagentAnnounceParams

type SubagentAnnounceParams struct {
	ChildSessionKey     string
	ChildRunID          string
	RequesterSessionKey string
	RequesterOrigin     *DeliveryContext
	RequesterDisplayKey string
	Task                string
	Label               string
	StartedAt           *int64
	EndedAt             *int64
	Outcome             *SubagentRunOutcome
	Cleanup             string
	AnnounceType        SubagentAnnounceType
	TimeoutSeconds      int
}

SubagentAnnounceParams 分身宣告参数

type SubagentAnnounceType

type SubagentAnnounceType string

SubagentAnnounceType 分身宣告类型

const (
	SubagentAnnounceTypeTask SubagentAnnounceType = "subagent task"
	SubagentAnnounceTypeCron SubagentAnnounceType = "cron job"
)

type SubagentAnnouncer

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

SubagentAnnouncer 分身宣告器

func NewSubagentAnnouncer

func NewSubagentAnnouncer(onAnnounce AnnounceCallback) *SubagentAnnouncer

NewSubagentAnnouncer 创建分身宣告器

func (*SubagentAnnouncer) RunAnnounceFlow

func (a *SubagentAnnouncer) RunAnnounceFlow(params *SubagentAnnounceParams) error

RunAnnounceFlow 执行宣告流程

type SubagentCompletion

type SubagentCompletion struct {
	Status    string // ok, error, timeout
	StartedAt int64
	EndedAt   int64
	Error     string
}

SubagentCompletion 分身完成结果

func WaitForSubagentCompletion

func WaitForSubagentCompletion(runID string, timeoutSeconds int, waitFunc func(string, int) (*SubagentCompletion, error)) (*SubagentCompletion, error)

WaitForSubagentCompletion 等待分身完成

type SubagentRegistry

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

SubagentRegistry 分身注册表

func NewSubagentRegistry

func NewSubagentRegistry(dataDir string) *SubagentRegistry

NewSubagentRegistry 创建分身注册表

func (*SubagentRegistry) BeginCleanup

func (r *SubagentRegistry) BeginCleanup(runID string) bool

BeginCleanup 开始清理流程

func (*SubagentRegistry) Cleanup

func (r *SubagentRegistry) Cleanup(runID string, cleanup string, didAnnounce bool)

Cleanup 标记清理已完成

func (*SubagentRegistry) Count

func (r *SubagentRegistry) Count() int

Count 获取运行数量

func (*SubagentRegistry) DeleteChildSession

func (r *SubagentRegistry) DeleteChildSession(sessionKey string) error

DeleteChildSession 删除子会话

func (*SubagentRegistry) GetRun

func (r *SubagentRegistry) GetRun(runID string) (*SubagentRunRecord, bool)

GetRun 获取运行记录

func (*SubagentRegistry) ListRunsForRequester

func (r *SubagentRegistry) ListRunsForRequester(requesterSessionKey string) []*SubagentRunRecord

ListRunsForRequester 列出请求者的所有分身运行

func (*SubagentRegistry) LoadFromDisk

func (r *SubagentRegistry) LoadFromDisk() error

LoadFromDisk 从磁盘加载

func (*SubagentRegistry) MarkCompleted

func (r *SubagentRegistry) MarkCompleted(runID string, outcome *SubagentRunOutcome, endedAt *int64) error

MarkCompleted 标记分身运行完成

func (*SubagentRegistry) RegisterRun

func (r *SubagentRegistry) RegisterRun(params *SubagentRunParams) error

RegisterRun 注册分身运行

func (*SubagentRegistry) ReleaseRun

func (r *SubagentRegistry) ReleaseRun(runID string)

ReleaseRun 释放运行记录

func (*SubagentRegistry) SetOnRunComplete

func (r *SubagentRegistry) SetOnRunComplete(fn func(runID string, record *SubagentRunRecord))

SetOnRunComplete 设置运行完成回调

type SubagentRunOutcome

type SubagentRunOutcome struct {
	Status string `json:"status"` // ok, error, timeout, unknown
	Error  string `json:"error,omitempty"`
}

SubagentRunOutcome 分身运行结果

type SubagentRunParams

type SubagentRunParams struct {
	RunID               string
	ChildSessionKey     string
	RequesterSessionKey string
	RequesterOrigin     *DeliveryContext
	RequesterDisplayKey string
	Task                string
	Cleanup             string
	Label               string
	ArchiveAfterMinutes int
}

SubagentRunParams 注册参数

type SubagentRunRecord

type SubagentRunRecord struct {
	RunID               string              `json:"run_id"`
	ChildSessionKey     string              `json:"child_session_key"`
	RequesterSessionKey string              `json:"requester_session_key"`
	RequesterOrigin     *DeliveryContext    `json:"requester_origin,omitempty"`
	RequesterDisplayKey string              `json:"requester_display_key"`
	Task                string              `json:"task"`
	Cleanup             string              `json:"cleanup"` // delete, keep
	Label               string              `json:"label,omitempty"`
	CreatedAt           int64               `json:"created_at"`
	StartedAt           *int64              `json:"started_at,omitempty"`
	EndedAt             *int64              `json:"ended_at,omitempty"`
	Outcome             *SubagentRunOutcome `json:"outcome,omitempty"`
	ArchiveAtMs         *int64              `json:"archive_at_ms,omitempty"`
	CleanupCompletedAt  *int64              `json:"cleanup_completed_at,omitempty"`
	CleanupHandled      bool                `json:"cleanup_handled"`
}

SubagentRunRecord 分身运行记录

type SubagentSystemPromptParams

type SubagentSystemPromptParams struct {
	RequesterSessionKey string
	RequesterOrigin     *DeliveryContext
	ChildSessionKey     string
	Label               string
	Task                string
}

SubagentSystemPromptParams 系统提示词参数

type TextContent

type TextContent struct {
	Text string `json:"text"`
}

TextContent represents text content

func (TextContent) ContentType

func (t TextContent) ContentType() string

type ThinkingContent

type ThinkingContent struct {
	Thinking string `json:"thinking"`
}

ThinkingContent represents thinking/reasoning content

func (ThinkingContent) ContentType

func (t ThinkingContent) ContentType() string

type Tool

type Tool interface {
	Name() string
	Description() string
	Parameters() map[string]any

	// Label returns a human-readable label for the tool (for UI display)
	// Inspired by pi-mono's AgentTool.label
	Label() string

	// Execute runs the tool with optional streaming updates
	Execute(ctx context.Context, params map[string]any, onUpdate func(ToolResult)) (ToolResult, error)
}

Tool represents an executable tool Inspired by pi-mono's AgentTool interface

func ToAgentTools

func ToAgentTools(existingTools []tools.Tool) []Tool

ToAgentTools converts existing tools to agent.Tool format (with adapter)

func ToTools added in v0.2.0

func ToTools(agentTools []AgentTool) []Tool

ToTools converts a slice of AgentTool to Tool (for compatibility)

type ToolCall

type ToolCall struct {
	ID     string                 `json:"id"`
	Name   string                 `json:"name"`
	Params map[string]interface{} `json:"params"`
}

ToolCall 工具调用定义(与 provider 保持一致)

type ToolCallContent

type ToolCallContent struct {
	ID        string         `json:"id"`
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments"`
}

ToolCallContent represents a tool call from assistant

func (ToolCallContent) ContentType

func (t ToolCallContent) ContentType() string

type ToolPolicy

type ToolPolicy struct {
	Deny      map[string]bool
	Allow     map[string]bool
	AllowOnly bool
}

ToolPolicy 工具策略

func ResolveToolPolicy

func ResolveToolPolicy(denyTools []string, allowTools []string) *ToolPolicy

ResolveToolPolicy 解析工具策略

func (*ToolPolicy) IsToolAllowed

func (p *ToolPolicy) IsToolAllowed(toolName string) bool

IsToolAllowed 检查工具是否被允许

type ToolRegistry

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

ToolRegistry wraps the existing tools.Registry and provides helper methods

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates a new tool registry

func (*ToolRegistry) Clear

func (r *ToolRegistry) Clear()

Clear removes all tools

func (*ToolRegistry) Count

func (r *ToolRegistry) Count() int

Count returns the number of registered tools

func (*ToolRegistry) Execute

func (r *ToolRegistry) Execute(ctx context.Context, name string, params map[string]interface{}) (string, error)

Execute executes a tool using the existing registry

func (*ToolRegistry) GetExisting

func (r *ToolRegistry) GetExisting(name string) (tools.Tool, bool)

GetExisting retrieves a tool as existing type

func (*ToolRegistry) Has

func (r *ToolRegistry) Has(name string) bool

Has checks if a tool is registered

func (*ToolRegistry) ListExisting

func (r *ToolRegistry) ListExisting() []tools.Tool

ListExisting returns tools as existing type

func (*ToolRegistry) RegisterAgentTool added in v0.3.2

func (r *ToolRegistry) RegisterAgentTool(tool Tool)

RegisterAgentTool registers an agent.Tool (with onUpdate callback support)

func (*ToolRegistry) RegisterExisting

func (r *ToolRegistry) RegisterExisting(tool tools.Tool) error

RegisterExisting registers an existing tool from tools package

func (*ToolRegistry) Unregister

func (r *ToolRegistry) Unregister(name string)

Unregister removes a tool

type ToolResult

type ToolResult struct {
	Content []ContentBlock `json:"content"`
	Details map[string]any `json:"details"`
	Error   error          `json:"error,omitempty"`
}

ToolResult represents the result of a tool execution

type ToolValidationError added in v0.2.0

type ToolValidationError struct {
	Field   string
	Message string
}

ToolValidationError is returned when parameter validation fails

func (*ToolValidationError) Error added in v0.2.0

func (e *ToolValidationError) Error() string

type UpdateSessionOptions added in v0.2.0

type UpdateSessionOptions struct {
	SaveImmediately bool // Save to disk after updating
}

UpdateSessionWithOptions updates the session with new messages with options

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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