agent

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

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 IsSubagentSessionKey

func IsSubagentSessionKey(sessionKey string) bool

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

func ParseAgentSessionKey

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

ParseAgentSessionKey 解析 Agent 会话密钥

func ToExistingTools

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

ToExistingTools converts agent tools to existing tools.Tool format

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) 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) 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) Stop

func (a *Agent) Stop() error

Stop stops the agent

func (*Agent) Subscribe

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

Subscribe subscribes to agent events

func (*Agent) Unsubscribe

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

Unsubscribe removes an event subscription

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
	PendingTools  map[string]bool
	Error         error

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

	// 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

func (*AgentState) DequeueSteeringMessages

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

DequeueSteeringMessages gets and clears steering messages

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 AnnounceCallback

type AnnounceCallback func(sessionKey, message string) error

AnnounceCallback 宣告回调

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   *Message  `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"`
}

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 *Message) *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"
)

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

	// 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
}

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 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
	SkillsLoader *SkillsLoader
}

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   // 技能加载器
}

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

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

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 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 设置是否启用自动安装

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

	// 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

func ToAgentTools

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

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

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) 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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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