agent

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildWebFetchOptions

func BuildWebFetchOptions(cfg *config.Config) tools.WebFetchOptions

BuildWebFetchOptions converts config to tool options and resolves default script path.

func ExtractStepDeclarations

func ExtractStepDeclarations(content string) []string

ExtractStepDeclarations extracts new step declarations from LLM output

func IsContinueIntent

func IsContinueIntent(content string) bool

IsContinueIntent detects if the user wants to continue a paused task

Types

type AgentLoop

type AgentLoop struct {
	Bus                 *bus.MessageBus
	Provider            providers.LLMProvider
	Workspace           string
	Model               string
	MaxIterations       int
	BraveAPIKey         string
	WebFetchOptions     tools.WebFetchOptions
	ExecConfig          config.ExecToolConfig
	RestrictToWorkspace bool
	CronService         *cron.Service
	MCPServers          map[string]config.MCPServerConfig

	PlanManager *PlanManager // Task plan manager for multi-step execution
	// contains filtered or unexported fields
}

AgentLoop Agent 循环

func NewAgentLoop

func NewAgentLoop(
	bus *bus.MessageBus,
	provider providers.LLMProvider,
	workspace string,
	model string,
	maxIterations int,
	braveAPIKey string,
	webFetch tools.WebFetchOptions,
	execConfig config.ExecToolConfig,
	restrictToWorkspace bool,
	cronService *cron.Service,
	mcpServers map[string]config.MCPServerConfig,
	enableGlobalSkills bool,
) *AgentLoop

NewAgentLoop 创建 Agent 循环

func (*AgentLoop) Close

func (a *AgentLoop) Close() error

Close 释放 AgentLoop 资源(主要是 MCP 连接)。

func (*AgentLoop) ExecuteToolWithSession

func (a *AgentLoop) ExecuteToolWithSession(
	ctx context.Context,
	toolName string,
	params map[string]interface{},
	sessionKey, channel, chatID string,
) (string, error)

ExecuteToolWithSession executes one tool call with explicit runtime context.

func (*AgentLoop) HandleInterruption

func (a *AgentLoop) HandleInterruption(msg *bus.InboundMessage, explicitMode ...InterruptMode) InterruptMode

HandleInterruption 处理插话请求 explicitMode 为可选参数,如果提供则直接使用,否则通过意图分析判断

func (*AgentLoop) LoadSkills

func (a *AgentLoop) LoadSkills() error

LoadSkills 加载技能文件

func (*AgentLoop) ProcessDirect

func (a *AgentLoop) ProcessDirect(ctx context.Context, content, sessionKey, channel, chatID string) (string, error)

ProcessDirect 直接处理消息(用于 CLI)

func (*AgentLoop) ProcessDirectEventStream

func (a *AgentLoop) ProcessDirectEventStream(
	ctx context.Context,
	content, sessionKey, channel, chatID string,
	onEvent func(StreamEvent),
) (string, error)

ProcessDirectEventStream streams structured events for UI clients.

func (*AgentLoop) ProcessDirectEventStreamWithMediaAndSkills

func (a *AgentLoop) ProcessDirectEventStreamWithMediaAndSkills(
	ctx context.Context,
	content, sessionKey, channel, chatID string,
	selectedSkills []string,
	media *bus.MediaAttachment,
	onEvent func(StreamEvent),
) (string, error)

func (*AgentLoop) ProcessDirectEventStreamWithSkills

func (a *AgentLoop) ProcessDirectEventStreamWithSkills(
	ctx context.Context,
	content, sessionKey, channel, chatID string,
	selectedSkills []string,
	onEvent func(StreamEvent),
) (string, error)

func (*AgentLoop) ProcessDirectStream

func (a *AgentLoop) ProcessDirectStream(
	ctx context.Context,
	content, sessionKey, channel, chatID string,
	onDelta func(string),
) (string, error)

ProcessDirectStream 直接处理消息并按 delta 回调流式输出。

func (*AgentLoop) ProcessDirectWithMediaAndSkills

func (a *AgentLoop) ProcessDirectWithMediaAndSkills(
	ctx context.Context,
	content, sessionKey, channel, chatID string,
	selectedSkills []string,
	media *bus.MediaAttachment,
) (string, error)

func (*AgentLoop) ProcessDirectWithOptions

func (a *AgentLoop) ProcessDirectWithOptions(
	ctx context.Context,
	content, sessionKey, channel, chatID string,
	selectedSkills []string,
	modelOverride string,
) (string, error)

ProcessDirectWithOptions runs a direct request with optional model override. Used by spawned sub-sessions to keep model/context independent from the parent run.

func (*AgentLoop) ProcessDirectWithSkills

func (a *AgentLoop) ProcessDirectWithSkills(
	ctx context.Context,
	content, sessionKey, channel, chatID string,
	selectedSkills []string,
) (string, error)

func (*AgentLoop) ProcessMessage

func (a *AgentLoop) ProcessMessage(ctx context.Context, msg *bus.InboundMessage) (*bus.OutboundMessage, error)

ProcessMessage 处理单个消息(流式版本)

func (*AgentLoop) Run

func (a *AgentLoop) Run(ctx context.Context) error

Run 运行 Agent 循环

func (*AgentLoop) UpdateRuntimeExecutionMode

func (a *AgentLoop) UpdateRuntimeExecutionMode(mode string)

UpdateRuntimeExecutionMode updates execution mode for new requests.

func (*AgentLoop) UpdateRuntimeMaxIterations

func (a *AgentLoop) UpdateRuntimeMaxIterations(maxIterations int)

UpdateRuntimeMaxIterations updates the max iteration limit used by new requests.

func (*AgentLoop) UpdateRuntimeModel

func (a *AgentLoop) UpdateRuntimeModel(provider providers.LLMProvider, model string)

UpdateRuntimeModel updates the active provider/model used by new requests.

type ContextBuilder

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

ContextBuilder 上下文构建器

func NewContextBuilder

func NewContextBuilder(workspace string) *ContextBuilder

NewContextBuilder 创建上下文构建器

func NewContextBuilderWithConfig

func NewContextBuilderWithConfig(workspace string, enableGlobalSkills bool) *ContextBuilder

NewContextBuilderWithConfig 创建带配置的上下文构建器

func (*ContextBuilder) AddAssistantMessage

func (b *ContextBuilder) AddAssistantMessage(messages []providers.Message, content string, toolCalls []providers.ToolCall) []providers.Message

AddAssistantMessage 添加助手消息

func (*ContextBuilder) AddToolResult

func (b *ContextBuilder) AddToolResult(messages []providers.Message, toolCallID, name, result string) []providers.Message

AddToolResult 添加工具结果

func (*ContextBuilder) BuildMessages

func (b *ContextBuilder) BuildMessages(history []providers.Message, currentMessage string, media *bus.MediaAttachment, channel, chatID string) []providers.Message

BuildMessages 构建消息列表

func (*ContextBuilder) BuildMessagesWithPlanAndSkillRefs

func (cb *ContextBuilder) BuildMessagesWithPlanAndSkillRefs(
	history []providers.Message,
	userContent string,
	skillRefs []string,
	media *bus.MediaAttachment,
	channel, chatID string,
	plan *Plan,
) []providers.Message

BuildMessagesWithPlanAndSkillRefs builds messages with plan context

func (*ContextBuilder) BuildMessagesWithSkillRefs

func (b *ContextBuilder) BuildMessagesWithSkillRefs(
	history []providers.Message,
	currentMessage string,
	explicitSkillRefs []string,
	media *bus.MediaAttachment,
	channel, chatID string,
) []providers.Message

func (*ContextBuilder) BuildSystemPromptWithPlan

func (cb *ContextBuilder) BuildSystemPromptWithPlan(plan *Plan) string

BuildSystemPromptWithPlan creates system prompt with plan context

func (*ContextBuilder) SetExecutionMode

func (b *ContextBuilder) SetExecutionMode(mode string)

SetExecutionMode sets the execution mode injected into prompt environment context.

type IntentAnalyzer

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

IntentAnalyzer 意图分析器

func NewIntentAnalyzer

func NewIntentAnalyzer() *IntentAnalyzer

NewIntentAnalyzer 创建分析器

func (*IntentAnalyzer) Analyze

func (a *IntentAnalyzer) Analyze(input string, currentContext string) IntentResult

Analyze 分析用户输入意图

type IntentResult

type IntentResult struct {
	Intent      UserIntent
	Confidence  float64
	IsInterrupt bool
	Explanation string
}

IntentResult 意图分析结果

type InterruptMode

type InterruptMode string

InterruptMode 插话模式

const (
	InterruptNone   InterruptMode = ""       // 无中断
	InterruptCancel InterruptMode = "cancel" // 打断重来
	InterruptAppend InterruptMode = "append" // 补充上下文
)

type InterruptRequest

type InterruptRequest struct {
	Message   *bus.InboundMessage
	Mode      InterruptMode
	Timestamp time.Time
}

InterruptRequest 中断请求

type InterruptibleContext

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

InterruptibleContext 可中断的上下文

func NewInterruptibleContext

func NewInterruptibleContext(parent context.Context, b *bus.MessageBus) *InterruptibleContext

NewInterruptibleContext 创建可中断上下文

func (*InterruptibleContext) Context

func (ic *InterruptibleContext) Context() context.Context

Context 返回底层 context

func (*InterruptibleContext) Done

func (ic *InterruptibleContext) Done() <-chan struct{}

Done 返回完成通道

func (*InterruptibleContext) Err

func (ic *InterruptibleContext) Err() error

Err 返回错误

func (*InterruptibleContext) GetInterrupts

func (ic *InterruptibleContext) GetInterrupts() []InterruptRequest

GetInterrupts 获取所有中断请求

func (*InterruptibleContext) GetPendingAppends

func (ic *InterruptibleContext) GetPendingAppends() []*bus.InboundMessage

GetPendingAppends 获取待处理的补充消息

func (*InterruptibleContext) IsCancelled

func (ic *InterruptibleContext) IsCancelled() bool

IsCancelled 检查是否被取消

func (*InterruptibleContext) RequestInterrupt

func (ic *InterruptibleContext) RequestInterrupt(req InterruptRequest)

RequestInterrupt 请求中断

func (*InterruptibleContext) SetOnInterrupt

func (ic *InterruptibleContext) SetOnInterrupt(cb func(InterruptRequest))

SetOnInterrupt 设置中断回调

type Plan

type Plan struct {
	ID               string     `json:"id"`
	Goal             string     `json:"goal"`
	Status           PlanStatus `json:"status"`
	CreatedAt        time.Time  `json:"created_at"`
	UpdatedAt        time.Time  `json:"updated_at"`
	Steps            []*Step    `json:"steps"`
	CurrentStepIndex int        `json:"current_step_index"`
	IterationCount   int        `json:"iteration_count"`
}

Plan represents a task plan for the agent

func CreatePlan

func CreatePlan(goal string) *Plan

CreatePlan creates a new plan for a goal

func (*Plan) AddStep

func (p *Plan) AddStep(description string) *Step

AddStep adds a new step to the plan

func (*Plan) CompleteCurrentStep

func (p *Plan) CompleteCurrentStep(result string)

CompleteCurrentStep marks the current step as completed and advances

func (*Plan) CurrentStep

func (p *Plan) CurrentStep() *Step

CurrentStep returns the current step or nil if all steps completed

func (*Plan) GenerateProgressSummary

func (p *Plan) GenerateProgressSummary() string

GenerateProgressSummary creates a human-readable progress summary

func (*Plan) IsTerminal

func (p *Plan) IsTerminal() bool

IsTerminal returns true if the plan is in a terminal state

func (*Plan) ToContextString

func (p *Plan) ToContextString() string

ToContextString returns a concise version for LLM context

type PlanManager

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

PlanManager manages plan storage and lifecycle

func NewPlanManager

func NewPlanManager(workspace string) *PlanManager

NewPlanManager creates a new PlanManager

func (*PlanManager) Delete

func (pm *PlanManager) Delete(sessionKey string) error

Delete removes a plan for the given session key

func (*PlanManager) Exists

func (pm *PlanManager) Exists(sessionKey string) bool

Exists checks if a plan exists for the given session key

func (*PlanManager) Load

func (pm *PlanManager) Load(sessionKey string) (*Plan, error)

Load loads a plan for the given session key

func (*PlanManager) Save

func (pm *PlanManager) Save(sessionKey string, plan *Plan) error

Save saves a plan for the given session key

type PlanStatus

type PlanStatus string

PlanStatus represents the status of a plan

const (
	PlanStatusPending   PlanStatus = "pending"
	PlanStatusRunning   PlanStatus = "running"
	PlanStatusPaused    PlanStatus = "paused"
	PlanStatusCompleted PlanStatus = "completed"
	PlanStatusFailed    PlanStatus = "failed"
)

type Progress

type Progress struct {
	Current int `json:"current"`
	Total   int `json:"total"`
}

Progress tracks sub-progress within a step

type Step

type Step struct {
	ID          string     `json:"id"`
	Description string     `json:"description"`
	Status      StepStatus `json:"status"`
	Result      string     `json:"result"`
	Progress    *Progress  `json:"progress,omitempty"`
	StartedAt   *time.Time `json:"started_at,omitempty"`
	CompletedAt *time.Time `json:"completed_at,omitempty"`
}

Step represents a single step in a plan

type StepDetector

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

StepDetector handles detecting when a step is completed

func NewStepDetector

func NewStepDetector() *StepDetector

NewStepDetector creates a new StepDetector with default settings

func (*StepDetector) DetectCompletion

func (sd *StepDetector) DetectCompletion(llmOutput string, iterationInStep int) bool

DetectCompletion analyzes LLM output to determine if current step is complete Uses hybrid strategy: explicit markers > transition words > timeout fallback

type StepStatus

type StepStatus string

StepStatus represents the status of a step

const (
	StepStatusPending   StepStatus = "pending"
	StepStatusRunning   StepStatus = "running"
	StepStatusCompleted StepStatus = "completed"
	StepStatusFailed    StepStatus = "failed"
)

type StreamEvent

type StreamEvent struct {
	Type       string `json:"type"`
	Iteration  int    `json:"iteration,omitempty"`
	Message    string `json:"message,omitempty"`
	Delta      string `json:"delta,omitempty"`
	ToolID     string `json:"toolId,omitempty"`
	ToolName   string `json:"toolName,omitempty"`
	ToolArgs   string `json:"toolArgs,omitempty"`
	Summary    string `json:"summary,omitempty"`
	ToolResult string `json:"toolResult,omitempty"`
	Response   string `json:"response,omitempty"`
	Done       bool   `json:"done,omitempty"`
}

StreamEvent is a structured event for UI streaming consumers.

type UserIntent

type UserIntent string

UserIntent 用户意图类型

const (
	IntentContinue   UserIntent = "continue"   // 继续当前话题
	IntentCorrection UserIntent = "correction" // 纠正/否定
	IntentAppend     UserIntent = "append"     // 补充信息
	IntentNewTopic   UserIntent = "new_topic"  // 新话题
	IntentStop       UserIntent = "stop"       // 明确要求停止
)

Jump to

Keyboard shortcuts

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