agent

package
v0.80.5 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Overview

Package agent provides conversation context management for multi-turn dialogues. This module maintains state across conversation turns to enable handling of refinements like "change it to 3pm" without re-specifying the full context.

Package agent provides error classification for intelligent retry logic. This system categorizes errors into transient (retryable), permanent (non-retryable), and conflict (special handling) types to improve agent reliability.

Package agent provides recoverable error definitions for AI agents. These errors are designed to work with the error recovery system.

Package agent provides prompt version management for A/B testing and rollout.

Package agent provides error recovery mechanisms for AI agents. This system automatically attempts to recover from certain error types by modifying inputs and retrying, improving user experience.

Note: ErrorRecovery instances are designed to be created per-request or shared as immutable configurations. Use WithTimezone to create a new instance with different settings rather than modifying existing ones.

Index

Constants

View Source
const (
	// Maximum input length to log (prevents log flooding)
	MaxInputLogLength = 50
	// Maximum pattern match length to log
	MaxPatternLogLength = 100
	// Maximum command display length for UI
	MaxDisplayLength = 100
)

Constants for danger detector logging and display limits.

View Source
const (
	// DefaultCacheEntries is the default maximum number of cache entries.
	DefaultCacheEntries = 100

	// DefaultCacheTTL is the default time-to-live for cache entries.
	DefaultCacheTTL = 5 * time.Minute
)

Constants for MemoParrot configuration.

View Source
const (
	EnvMemoVersion     = "MEMO_PROMPT_VERSION"
	EnvScheduleVersion = "SCHEDULE_PROMPT_VERSION"
	EnvAmazingVersion  = "AMAZING_PROMPT_VERSION"
)

Environment variables for prompt version configuration.

View Source
const (
	EventToolUse    = "tool_use"
	EventToolResult = "tool_result"
	EventAnswer     = "answer"
)

Event constants for callbacks.

View Source
const (
	EventTypeThinking    = "thinking"     // Agent is thinking
	EventTypeToolUse     = "tool_use"     // Agent is using a tool
	EventTypeToolResult  = "tool_result"  // Tool execution result
	EventTypeAnswer      = "answer"       // Final answer from agent
	EventTypeError       = "error"        // Error occurred
	EventTypeDangerBlock = "danger_block" // Dangerous operation was blocked

	// Memo-specific events.
	EventTypeMemoQueryResult = "memo_query_result" // Memo search results

	// Schedule-specific events.
	EventTypeScheduleQueryResult = "schedule_query_result" // Schedule query results
	EventTypeScheduleUpdated     = "schedule_updated"      // Schedule created/updated

	// UI 工具事件 - 用于生成式 UI.
	EventTypeUIScheduleSuggestion = "ui_schedule_suggestion" // Suggested schedule for confirmation
	EventTypeUITimeSlotPicker     = "ui_time_slot_picker"    // Time slot selection
	EventTypeUIConflictResolution = "ui_conflict_resolution" // Conflict resolution options
	EventTypeUIQuickActions       = "ui_quick_actions"       // Quick action buttons
	EventTypeUIMemoPreview        = "ui_memo_preview"        // Memo preview cards
	EventTypeUIScheduleList       = "ui_schedule_list"       // Schedule list display
)

常用事件类型.

Variables

View Source
var (
	// ErrInvalidTimeFormat indicates the time expression could not be parsed.
	// Recovery: Attempt to normalize the time expression and retry.
	ErrInvalidTimeFormat = errors.New("invalid time format")

	// ErrToolNotFound indicates the requested tool does not exist.
	// Recovery: Re-route to find an appropriate tool.
	ErrToolNotFound = errors.New("tool not found")

	// ErrParseError indicates the input could not be parsed.
	// Recovery: Simplify the input and retry.
	ErrParseError = errors.New("parse error")

	// ErrNetworkError indicates a network-related failure.
	// Recovery: Not automatically recoverable, return friendly message.
	ErrNetworkError = errors.New("network error")

	// ErrServiceUnavailable indicates the service is temporarily unavailable.
	// Recovery: Not automatically recoverable, return friendly message.
	ErrServiceUnavailable = errors.New("service unavailable")

	// ErrInvalidInput indicates the user input is invalid.
	// Recovery: Not automatically recoverable, return friendly message.
	ErrInvalidInput = errors.New("invalid input")

	// ErrScheduleConflict indicates a schedule time conflict.
	// Recovery: Not automatically recoverable, suggest alternatives.
	ErrScheduleConflict = errors.New("schedule conflict")
)

Recoverable error types for the error recovery system. These errors can be automatically handled by ErrorRecovery.

View Source
var (
	MemoABExperiment     = NewABExperiment(ABConfig{ExperimentID: "memo-v1-v2", ControlVersion: PromptV1, TreatmentVersion: PromptV2, TrafficPercent: 0, Enabled: false})
	ScheduleABExperiment = NewABExperiment(ABConfig{ExperimentID: "schedule-v1-v2", ControlVersion: PromptV1, TreatmentVersion: PromptV2, TrafficPercent: 0, Enabled: false})
	AmazingABExperiment  = NewABExperiment(ABConfig{ExperimentID: "amazing-v1-v2", ControlVersion: PromptV1, TreatmentVersion: PromptV2, TrafficPercent: 0, Enabled: false})
)

Global experiments (can be configured at runtime).

View Source
var PromptRegistry = struct {
	Memo     *AgentPrompts
	Schedule *AgentPrompts
	Amazing  *AgentPrompts
	mu       sync.RWMutex
}{
	Memo:     NewAgentPrompts(),
	Schedule: NewAgentPrompts(),
	Amazing:  NewAgentPrompts(),
}

PromptRegistry manages prompts for all agent types. Thread-safe: uses mu for concurrent access to prompts.

Functions

func ConfigureABExperimentFromEnv

func ConfigureABExperimentFromEnv()

ConfigureABExperimentFromEnv configures A/B experiments from environment variables. Format: MEMO_AB_TRAFFIC=50 enables 50% traffic to V2.

func ConversationIDToSessionID added in v0.80.0

func ConversationIDToSessionID(conversationID int64) string

ConversationIDToSessionID converts a database ConversationID to a deterministic UUID v5. This ensures the same ConversationID always maps to the same SessionID, enabling reliable session resume across backend restarts. 将数据库 ConversationID 转换为确定性的 UUID v5。 确保相同的 ConversationID 始终映射到相同的 SessionID,实现跨重启的可靠会话恢复。

func FormatTZOffset

func FormatTZOffset(offset int) string

Exported for use in scheduler_v2.go.

func GenerateCacheKey

func GenerateCacheKey(agentName string, userID int32, userInput string) string

GenerateCacheKey creates a cache key from agent name, userID and userInput using SHA256 hash. GenerateCacheKey 使用 SHA256 哈希从代理名称、用户ID和用户输入创建缓存键。 Uses full SHA256 hex to eliminate collision risk.

func GetActionHint

func GetActionHint(err error) string

GetActionHint returns the suggested action for handling the error.

func GetAmazingPlanningPrompt

func GetAmazingPlanningPrompt(args ...any) string

GetAmazingPlanningPrompt returns the amazing planning prompt with variable substitution.

func GetAmazingSynthesisPrompt

func GetAmazingSynthesisPrompt(args ...any) string

GetAmazingSynthesisPrompt returns the amazing synthesis prompt with variable substitution.

func GetMemoSystemPrompt

func GetMemoSystemPrompt(args ...any) string

GetMemoSystemPrompt returns the memo system prompt with variable substitution.

func GetPromptMetricsSnapshot

func GetPromptMetricsSnapshot(agentType string, version PromptVersion) (requests, successes int64, avgLatencyMs int64)

GetPromptMetricsSnapshot returns the current in-memory metrics for a prompt version. Concurrent-safe: uses RWMutex for map access.

func GetRetryDelay

func GetRetryDelay(err error) time.Duration

GetRetryDelay returns the suggested delay before retry, or 0 if not retryable.

func GetScheduleSystemPrompt

func GetScheduleSystemPrompt(time, timezone, tzOffset string) string

GetScheduleSystemPrompt returns the schedule system prompt with timezone formatting. It handles the special case of 3 parameters: time, timezone, and tzOffset.

func InitBuiltinPrompts

func InitBuiltinPrompts()

InitBuiltinPrompts initializes built-in prompt templates. This can be called during service startup.

func IsRecoverableError

func IsRecoverableError(err error) bool

IsRecoverableError checks if the error can be automatically recovered.

func IsTransientError

func IsTransientError(err error) bool

IsTransientError checks if the error is transient and might succeed on retry.

func LogExperimentReport

func LogExperimentReport(agentType string)

LogExperimentReport logs the experiment report to slog.

func RecordPromptUsage

func RecordPromptUsage(agentType string, userID int32, success bool, latencyMs int64)

RecordPromptUsage records a prompt usage with metrics. This should be called after each agent execution.

func RecordPromptUsageInMemory

func RecordPromptUsageInMemory(agentType string, version PromptVersion, success bool, latencyMs int64)

RecordPromptUsageInMemory records prompt usage to in-memory counters. This is a lightweight alternative for real-time monitoring. Concurrent-safe: uses RWMutex for map access, atomic operations for counters.

func SetMetricsRecorder

func SetMetricsRecorder(recorder MetricsRecorder)

SetMetricsRecorder sets the global metrics recorder.

func SetPromptVersion

func SetPromptVersion(agentType string, version PromptVersion) error

SetPromptVersion sets the active prompt version for an agent type. Returns error if the version is not registered.

func ShouldRetry

func ShouldRetry(err error) bool

ShouldRetry returns true if the error warrants a retry attempt.

Types

type ABConfig

type ABConfig struct {
	ExperimentID     string
	ControlVersion   PromptVersion // V1 typically
	TreatmentVersion PromptVersion // V2 typically
	TrafficPercent   int           // 0-100, percentage for treatment
	Enabled          bool
}

ABConfig represents A/B testing configuration for a prompt experiment.

type ABExperiment

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

ABExperiment manages an A/B testing experiment for prompts.

func NewABExperiment

func NewABExperiment(config ABConfig) *ABExperiment

NewABExperiment creates a new A/B experiment with the given configuration.

func (*ABExperiment) GetVersionForUser

func (exp *ABExperiment) GetVersionForUser(userID int32) PromptVersion

GetVersionForUser returns the prompt version for a specific user based on A/B bucket. Users are deterministically assigned to buckets based on userID.

type Agent

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

Agent is a lightweight, framework-less AI agent. It uses native LLM tool calling without LangChainGo.

func NewAgent

func NewAgent(llm ai.LLMService, config AgentConfig, tools []ToolWithSchema) *Agent

NewAgent creates a new Agent with the given configuration.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, input string) (string, error)

Run executes the agent with the given input. Returns the final response or an error.

func (*Agent) RunWithCallback

func (a *Agent) RunWithCallback(ctx context.Context, input string, callback Callback) (string, error)

RunWithCallback executes the agent with callback support.

type AgentConfig

type AgentConfig struct {
	// Name identifies this agent.
	Name string

	// SystemPrompt is the base system prompt for the LLM.
	SystemPrompt string

	// MaxIterations is the maximum number of tool-calling loops.
	MaxIterations int
}

AgentConfig holds configuration for creating a new Agent.

type AgentPrompts

type AgentPrompts struct {
	// System is the main system prompt.
	System *PromptConfig

	// Planning is used for multi-step planning (optional).
	Planning *PromptConfig

	// Synthesis is used for result synthesis (optional).
	Synthesis *PromptConfig
}

AgentPrompts holds all prompts for a specific agent type.

func NewAgentPrompts

func NewAgentPrompts() *AgentPrompts

NewAgentPrompts creates a new AgentPrompts with default configs.

func (*AgentPrompts) GetPlanningPrompt

func (p *AgentPrompts) GetPlanningPrompt(args ...any) string

GetPlanningPrompt returns the active planning prompt with variable substitution.

func (*AgentPrompts) GetSynthesisPrompt

func (p *AgentPrompts) GetSynthesisPrompt(args ...any) string

GetSynthesisPrompt returns the active synthesis prompt with variable substitution.

func (*AgentPrompts) GetSystemPrompt

func (p *AgentPrompts) GetSystemPrompt(args ...any) string

GetSystemPrompt returns the active system prompt with variable substitution.

type AmazingParrot

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

AmazingParrot is the comprehensive assistant parrot (🦜 折衷). AmazingParrot 是综合助手鹦鹉(🦜 折衷)。 It combines memo and schedule capabilities for integrated assistance.

func NewAmazingParrot

func NewAmazingParrot(
	llm ai.LLMService,
	retriever *retrieval.AdaptiveRetriever,
	scheduleService schedule.Service,
	userID int32,
) (*AmazingParrot, error)

NewAmazingParrot creates a new amazing parrot agent. NewAmazingParrot 创建一个新的综合助手鹦鹉(折衷)。

func (*AmazingParrot) ExecuteWithCallback

func (p *AmazingParrot) ExecuteWithCallback(
	ctx context.Context,
	userInput string,
	history []string,
	callback EventCallback,
) error

ExecuteWithCallback executes the amazing parrot with callback support. ExecuteWithCallback 执行综合助手鹦鹉(折衷)并支持回调.

Implementation: Two-phase concurrent retrieval for optimal performance. Phase 1: Analyze user intent and plan concurrent retrievals. Phase 2: Execute retrievals concurrently, then synthesize answer.

func (*AmazingParrot) GetStats

func (p *AmazingParrot) GetStats() CacheStats

GetStats returns the cache statistics.

func (*AmazingParrot) Name

func (*AmazingParrot) Name() string

Name returns the name of the parrot. Name 返回鹦鹉名称。

func (*AmazingParrot) SelfDescribe

func (p *AmazingParrot) SelfDescribe() *ParrotSelfCognition

SelfDescribe returns the amazing parrot's metacognitive understanding of itself. SelfDescribe 返回综合助手鹦鹉(折衷)的元认知自我理解。

type AssistantMessage

type AssistantMessage struct {
	ID      string         `json:"id,omitempty"`
	Type    string         `json:"type,omitempty"`
	Role    string         `json:"role,omitempty"`
	Content []ContentBlock `json:"content,omitempty"`
}

AssistantMessage represents the nested message structure in assistant events. AssistantMessage 表示 assistant 事件中的嵌套消息结构。

type AvianIdentity

type AvianIdentity struct {
	Species          string   `json:"species"`
	Origin           string   `json:"origin"`
	SymbolicMeaning  string   `json:"symbolic_meaning"`
	AvianPhilosophy  string   `json:"avian_philosophy"`
	NaturalAbilities []string `json:"natural_abilities"`
}

AvianIdentity represents the parrot's cognition of its avian nature. AvianIdentity 表示鹦鹉对其鸟类本质的认知。

type BaseTool

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

BaseTool provides a reusable base implementation for tools. BaseTool 为工具提供可复用的基础实现。

func NewBaseTool

func NewBaseTool(
	name string,
	description string,
	execute func(ctx context.Context, input string) (string, error),
	opts ...ToolOption,
) *BaseTool

NewBaseTool creates a new BaseTool. NewBaseTool 创建一个新的 BaseTool。

Parameters:

  • name: The name of the tool
  • description: A description of what the tool does
  • execute: The function to execute when the tool is run
  • opts: Optional configuration functions

Example:

tool := NewBaseTool(
    "my_tool",
    "Does something useful",
    func(ctx context.Context, input string) (string, error) {
        return "result", nil
    },
    WithTimeout(30*time.Second),
)

func (*BaseTool) Description

func (t *BaseTool) Description() string

Description returns the description of the tool. Description 返回工具描述。

func (*BaseTool) Name

func (t *BaseTool) Name() string

Name returns the name of the tool. Name 返回工具名称。

func (*BaseTool) Run

func (t *BaseTool) Run(ctx context.Context, input string) (string, error)

Run executes the tool with validation and error handling. Run 执行工具,包含验证和错误处理。

type BiDirectionalStreamer added in v0.80.0

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

BiDirectionalStreamer handles the IO loop for a session.

func NewBiDirectionalStreamer added in v0.80.0

func NewBiDirectionalStreamer(logger *slog.Logger) *BiDirectionalStreamer

NewBiDirectionalStreamer creates a streamer.

func (*BiDirectionalStreamer) BuildUserMessage added in v0.80.0

func (s *BiDirectionalStreamer) BuildUserMessage(text string) map[string]any

BuildUserMessage constructs the JSON payload for user input.

func (*BiDirectionalStreamer) StreamOutput added in v0.80.0

func (s *BiDirectionalStreamer) StreamOutput(stdout io.Reader, eventChan chan<- StreamEvent) error

StreamOutput reads from stdout and sends events to the callback channel. It runs until stdout is closed or context cancelled.

type CCMode added in v0.70.0

type CCMode interface {
	// Name returns the mode identifier.
	Name() string

	// BuildSystemPrompt constructs the mode-specific system prompt.
	BuildSystemPrompt(cfg *CCRunnerConfig) string

	// GetWorkDir returns the working directory for the mode.
	GetWorkDir(userID int32) string

	// CheckPermission validates if the user can use this mode.
	CheckPermission(ctx context.Context, userID int32) error

	// OnComplete is called after successful execution.
	OnComplete(ctx context.Context) error
}

CCMode defines the interface for mode-specific behavior in CCRunner. CCMode 定义 CCRunner 中模式特定行为的接口。

Each mode (Geek, Evolution, etc.) implements this interface to provide mode-specific configuration, permissions, and post-execution behavior. 每个模式(极客、进化等)实现此接口以提供模式特定的配置、权限和执行后行为。

type CCRunner added in v0.70.0

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

CCRunner is the unified Claude Code CLI integration layer. CCRunner 是统一的 Claude Code CLI 集成层。

It provides a shared implementation for all modes that need to interact with Claude Code CLI (Geek Mode, Evolution Mode, etc.). 它为所有需要与 Claude Code CLI 交互的模式提供共享实现(极客模式、进化模式等)。

func NewCCRunner added in v0.70.0

func NewCCRunner(timeout time.Duration, logger *slog.Logger) (*CCRunner, error)

NewCCRunner creates a new CCRunner instance. NewCCRunner 创建一个新的 CCRunner 实例。

func (*CCRunner) Execute added in v0.70.0

func (r *CCRunner) Execute(ctx context.Context, cfg *CCRunnerConfig, prompt string, callback EventCallback) error

Execute runs Claude Code CLI with the given configuration and streams events. Execute 使用给定配置运行 Claude Code CLI 并流式传输事件。

func (*CCRunner) GetCLIVersion added in v0.70.0

func (r *CCRunner) GetCLIVersion() (string, error)

GetCLIVersion returns the Claude Code CLI version. GetCLIVersion 返回 Claude Code CLI 版本。

func (*CCRunner) GetDangerDetector added in v0.80.0

func (r *CCRunner) GetDangerDetector() *DangerDetector

GetDangerDetector returns the danger detector instance. GetDangerDetector 返回危险检测器实例。

func (*CCRunner) GetSessionManager added in v0.80.0

func (r *CCRunner) GetSessionManager() *CCSessionManager

GetSessionManager returns the improved session manager.

func (*CCRunner) GetSessionStats added in v0.80.0

func (r *CCRunner) GetSessionStats() *SessionStats

GetSessionStats returns a copy of the current session stats. GetSessionStats 返回当前会话统计数据的副本。

func (*CCRunner) SetDangerAllowPaths added in v0.80.0

func (r *CCRunner) SetDangerAllowPaths(paths []string)

SetDangerAllowPaths sets the allowed safe paths for the danger detector. SetDangerAllowPaths 设置危险检测器的允许安全路径。

func (*CCRunner) SetDangerBypassEnabled added in v0.80.0

func (r *CCRunner) SetDangerBypassEnabled(enabled bool)

SetDangerBypassEnabled enables or disables danger detection bypass. WARNING: Only use for Evolution mode (admin only). SetDangerBypassEnabled 启用或禁用危险检测绕过。 警告:仅用于进化模式(仅管理员)。

func (*CCRunner) StartAsyncSession added in v0.80.0

func (r *CCRunner) StartAsyncSession(ctx context.Context, cfg *CCRunnerConfig) (*Session, error)

StartAsyncSession starts a persistent session and returns the session object.

func (*CCRunner) StopSession added in v0.80.0

func (r *CCRunner) StopSession(sessionID string, reason string) error

StopSession terminates a running session by session ID. This is the implementation for session.stop from the spec. StopSession 通过 session ID 终止正在运行的会话。 这是规范中 session.stop 的实现。

func (*CCRunner) StopSessionByConversationID added in v0.80.0

func (r *CCRunner) StopSessionByConversationID(conversationID int64, reason string) error

StopSessionByConversationID terminates a session by its conversation ID. StopSessionByConversationID 通过对话 ID 终止会话。

type CCRunnerConfig added in v0.70.0

type CCRunnerConfig struct {
	Mode           string // "geek" | "evolution"
	WorkDir        string // Working directory for CLI
	ConversationID int64  // Database conversation ID for deterministic UUID v5 mapping
	SessionID      string // Session identifier (derived from ConversationID if empty)
	UserID         int32  // User ID for logging/context
	SystemPrompt   string // Mode-specific system prompt
	DeviceContext  string // Device/browser context JSON

	// Security / Permission Control
	// 安全/权限控制
	PermissionMode string // "default", "bypassPermissions", etc.

	// Evolution Mode specific
	// 进化模式专用
	AllowedPaths   []string // Path whitelist (evolution mode)
	ForbiddenPaths []string // Path blacklist (evolution mode)
}

CCRunnerConfig defines mode-specific configuration for CCRunner execution. CCRunnerConfig 定义 CCRunner 执行的模式特定配置。

type CCSessionManager added in v0.80.0

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

CCSessionManager implements SessionManager.

func NewCCSessionManager added in v0.80.0

func NewCCSessionManager(logger *slog.Logger, timeout time.Duration) *CCSessionManager

NewCCSessionManager creates a new session manager.

func (*CCSessionManager) GetOrCreateSession added in v0.80.0

func (sm *CCSessionManager) GetOrCreateSession(ctx context.Context, sessionID string, cfg CCRunnerConfig) (*Session, error)

GetOrCreateSession returns an existing session or starts a new one.

func (*CCSessionManager) GetSession added in v0.80.0

func (sm *CCSessionManager) GetSession(sessionID string) (*Session, bool)

GetSession retrieves an active session.

func (*CCSessionManager) ListActiveSessions added in v0.80.0

func (sm *CCSessionManager) ListActiveSessions() []*Session

ListActiveSessions returns all active sessions.

func (*CCSessionManager) Shutdown added in v0.80.0

func (sm *CCSessionManager) Shutdown()

Shutdown gracefully stops the session manager and all active sessions. Shutdown 优雅停止会话管理器和所有活动会话。

func (*CCSessionManager) TerminateSession added in v0.80.0

func (sm *CCSessionManager) TerminateSession(sessionID string) error

TerminateSession stops and removes a session.

type CacheEntry

type CacheEntry struct {
	Value      interface{} `json:"value"`
	Key        string      `json:"key"`
	ExpiresAt  int64       `json:"expires_at"`
	SizeBytes  int         `json:"size_bytes"`
	AccessTime int64       `json:"access_time"`
}

CacheEntry represents a cached value with metadata. CacheEntry 表示带有元数据的缓存值。

type CacheStats

type CacheStats struct {
	Size       int     `json:"size"`
	MaxEntries int     `json:"max_entries"`
	Hits       int64   `json:"hits"`
	Misses     int64   `json:"misses"`
	HitRate    float64 `json:"hit_rate"`
}

CacheStats represents cache statistics. CacheStats 表示缓存统计信息。

type Callback

type Callback func(event string, data string)

Callback is called during agent execution for events.

type ChatRouteResult

type ChatRouteResult struct {
	Route      ChatRouteType `json:"route"`
	Method     string        `json:"method"`
	Confidence float64       `json:"confidence"`
}

ChatRouteResult represents the routing classification result.

type ChatRouteType

type ChatRouteType string

ChatRouteType represents the type of chat routing.

const (
	// RouteTypeMemo routes to MemoParrot (灰灰) for memo search and retrieval.
	RouteTypeMemo ChatRouteType = "memo"

	// RouteTypeSchedule routes to ScheduleParrot (时巧) for schedule management.
	RouteTypeSchedule ChatRouteType = "schedule"

	// RouteTypeAmazing routes to AmazingParrot (折衷) for comprehensive assistance.
	RouteTypeAmazing ChatRouteType = "amazing"
)

type ChatRouter

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

ChatRouter routes user input to the appropriate Parrot agent. It uses a hybrid approach: fast rule matching first, then LLM for uncertain cases. Optionally uses the three-layer router.Service for enhanced history matching.

func NewChatRouter

func NewChatRouter(cfg ChatRouterConfig, routerSvc *router.Service) *ChatRouter

NewChatRouter creates a new chat router with hybrid rule+LLM classification. If routerSvc is provided, uses the three-layer router (rule + history + LLM). Otherwise, falls back to two-layer routing (rule + LLM only).

func (*ChatRouter) Route

func (r *ChatRouter) Route(ctx context.Context, input string) (*ChatRouteResult, error)

Route determines the appropriate Parrot agent for the user input. Uses hybrid approach: rule matching (0ms) → history matching (~10ms) → LLM classification (~400ms) if uncertain.

type ChatRouterConfig

type ChatRouterConfig struct {
	APIKey  string
	BaseURL string
	Model   string // Default: Qwen/Qwen2.5-7B-Instruct
}

ChatRouterConfig holds configuration for the chat router.

type ClassifiedError

type ClassifiedError struct {
	Original   error
	ActionHint string
	Class      ErrorClass
	RetryAfter time.Duration
}

ClassifiedError wraps an error with its classification and retry guidance.

func ClassifyError

func ClassifyError(err error) *ClassifiedError

ClassifyError analyzes an error and determines its class and retry strategy.

func (*ClassifiedError) Error

func (c *ClassifiedError) Error() string

Error returns a formatted error message.

func (*ClassifiedError) IsConflict

func (c *ClassifiedError) IsConflict() bool

IsConflict returns true if the error is a conflict.

func (*ClassifiedError) IsPermanent

func (c *ClassifiedError) IsPermanent() bool

IsPermanent returns true if the error is non-retryable.

func (*ClassifiedError) IsTransient

func (c *ClassifiedError) IsTransient() bool

IsTransient returns true if the error is temporary and should be retried.

func (*ClassifiedError) Unwrap

func (c *ClassifiedError) Unwrap() error

Unwrap returns the original error for errors.Is/As.

type ContentBlock

type ContentBlock struct {
	Type    string         `json:"type"`
	Text    string         `json:"text,omitempty"`
	Name    string         `json:"name,omitempty"`
	ID      string         `json:"id,omitempty"`
	Input   map[string]any `json:"input,omitempty"`
	Content string         `json:"content,omitempty"`
	IsError bool           `json:"is_error,omitempty"`
}

ContentBlock represents a content block in stream-json format. ContentBlock 表示 stream-json 格式中的内容块。

type ContextStore

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

ContextStore manages conversation contexts for multiple sessions.

func NewContextStore

func NewContextStore() *ContextStore

NewContextStore creates a new context store.

func (*ContextStore) CleanupOld

func (s *ContextStore) CleanupOld(maxAge time.Duration) int

CleanupOld removes contexts older than the specified duration.

func (*ContextStore) Delete

func (s *ContextStore) Delete(sessionID string)

Delete removes a conversation context.

func (*ContextStore) Get

func (s *ContextStore) Get(sessionID string) *ConversationContext

Get retrieves a conversation context if it exists.

func (*ContextStore) GetOrCreate

func (s *ContextStore) GetOrCreate(sessionID string, userID int32, timezone string) *ConversationContext

GetOrCreate retrieves or creates a conversation context.

type ContextSummary

type ContextSummary struct {
	CreatedAt           time.Time
	UpdatedAt           time.Time
	SessionID           string
	CurrentStep         WorkflowStep
	LastIntent          string
	TurnCount           int
	ConflictCount       int
	UserID              int32
	HasProposedSchedule bool
}

ContextSummary provides a quick overview of the context state.

type ConversationContext

type ConversationContext struct {
	CreatedAt    time.Time
	UpdatedAt    time.Time
	WorkingState *WorkingState
	SessionID    string
	Timezone     string
	Turns        []ConversationTurn

	UserID int32
	// contains filtered or unexported fields
}

ConversationContext maintains state across conversation turns.

func NewConversationContext

func NewConversationContext(sessionID string, userID int32, timezone string) *ConversationContext

NewConversationContext creates a new conversation context.

func (*ConversationContext) AddTurn

func (c *ConversationContext) AddTurn(userInput, agentOutput string, toolCalls []ToolCallRecord)

AddTurn adds a new turn to the conversation history.

func (*ConversationContext) Clear

func (c *ConversationContext) Clear()

Clear resets the conversation context.

func (*ConversationContext) ExtractRefinement

func (c *ConversationContext) ExtractRefinement(userInput string) *ScheduleDraft

ExtractRefinement attempts to extract a refinement from user input based on the current working state. For example: "change to 3pm" when there's a proposed schedule.

func (*ConversationContext) GetLastNTurns

func (c *ConversationContext) GetLastNTurns(n int) []ConversationTurn

GetLastNTurns returns the last N conversation turns.

func (*ConversationContext) GetLastTurn

func (c *ConversationContext) GetLastTurn() *ConversationTurn

GetLastTurn returns a copy of the most recent conversation turn.

func (*ConversationContext) GetSummary

func (c *ConversationContext) GetSummary() ContextSummary

GetSummary returns a summary of the conversation context.

func (*ConversationContext) GetWorkingState

func (c *ConversationContext) GetWorkingState() *WorkingState

GetWorkingState returns a deep copy of the current working state.

func (*ConversationContext) ToHistoryPrompt

func (c *ConversationContext) ToHistoryPrompt() string

ToHistoryPrompt converts the conversation history to a string format suitable for LLM context. It formats turns as "User: ...\nAssistant: ..." and optionally includes tool usage summaries.

func (*ConversationContext) ToJSON

func (c *ConversationContext) ToJSON() (string, error)

ToJSON exports the conversation context to JSON for persistence.

func (*ConversationContext) UpdateWorkingState

func (c *ConversationContext) UpdateWorkingState(state *WorkingState)

UpdateWorkingState updates the working state with new information.

type ConversationTurn

type ConversationTurn struct {
	Timestamp   time.Time
	UserInput   string
	AgentOutput string
	ToolCalls   []ToolCallRecord
}

ConversationTurn represents a single turn in the conversation.

type DangerBlockEvent added in v0.80.0

type DangerBlockEvent struct {
	Operation      string      `json:"operation"`
	Reason         string      `json:"reason"`
	PatternMatched string      `json:"pattern_matched"`
	Level          DangerLevel `json:"level"`
	Category       string      `json:"category"`
	BypassAllowed  bool        `json:"bypass_allowed"`
	Suggestions    []string    `json:"suggestions,omitempty"`
}

DangerBlockEvent represents a detected dangerous operation that was blocked.

type DangerDetector added in v0.80.0

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

DangerDetector detects potentially dangerous commands before execution. Implements security layer per spec 6: "Frontend Confirmation + Git Recovery".

func NewDangerDetector added in v0.80.0

func NewDangerDetector(logger *slog.Logger) *DangerDetector

NewDangerDetector creates a new danger detector with default patterns.

func (*DangerDetector) CheckFileAccess added in v0.80.0

func (dd *DangerDetector) CheckFileAccess(filePath string) bool

CheckFileAccess checks if file access is within allowed paths. Returns true if the access is safe (within allowed paths), false otherwise.

func (*DangerDetector) CheckInput added in v0.80.0

func (dd *DangerDetector) CheckInput(input string) *DangerBlockEvent

CheckInput checks if the input contains any dangerous operations. Returns a DangerBlockEvent if a dangerous operation is detected, nil otherwise.

func (*DangerDetector) IsPathAllowed added in v0.80.0

func (dd *DangerDetector) IsPathAllowed(path string) bool

IsPathAllowed checks if a path is in the allowlist.

func (*DangerDetector) LoadCustomPatterns added in v0.80.0

func (dd *DangerDetector) LoadCustomPatterns(filename string) error

LoadCustomPatterns loads custom danger patterns from a file. File format: one pattern per line: "regex|description|level|category"

func (*DangerDetector) SetAllowPaths added in v0.80.0

func (dd *DangerDetector) SetAllowPaths(paths []string)

SetAllowPaths sets the list of allowed safe paths.

func (*DangerDetector) SetBypassEnabled added in v0.80.0

func (dd *DangerDetector) SetBypassEnabled(enabled bool)

SetBypassEnabled enables or disables bypass mode. When enabled, dangerous operations are NOT blocked (admin/Evolution mode only).

type DangerLevel added in v0.80.0

type DangerLevel int

DangerLevel represents the severity level of a dangerous operation.

const (
	// DangerLevelCritical can cause irreversible data loss or system damage.
	DangerLevelCritical DangerLevel = iota
	// DangerLevelHigh can cause significant data loss or system impact.
	DangerLevelHigh
	// DangerLevelModerate may cause unintended changes.
	DangerLevelModerate
)

func (DangerLevel) String added in v0.80.0

func (d DangerLevel) String() string

String returns a string representation of the danger level.

type DangerPattern added in v0.80.0

type DangerPattern struct {
	Pattern     *regexp.Regexp
	Description string
	Level       DangerLevel
	Category    string // "file_delete", "system", "network", "permission"
}

DangerPattern defines a dangerous command pattern to detect.

type EmotionalExpression

type EmotionalExpression struct {
	SoundEffects map[string]string `json:"sound_effects"`
	MoodTriggers map[string]string `json:"mood_triggers,omitempty"`
	DefaultMood  string            `json:"default_mood"`
	Catchphrases []string          `json:"catchphrases"`
}

EmotionalExpression defines how a parrot expresses emotions. EmotionalExpression 定义鹦鹉的情感表达方式。

type ErrorClass

type ErrorClass int

ErrorClass represents the category of error for retry decisions.

const (
	// Examples: network timeout, temporary service unavailability.
	ErrorClassTransient ErrorClass = iota

	// Examples: validation failures, permission denied, invalid input.
	ErrorClassPermanent

	// Examples: schedule overlap, duplicate booking.
	ErrorClassConflict
)

func (ErrorClass) String

func (e ErrorClass) String() string

String returns the string representation of ErrorClass.

type ErrorRecovery

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

ErrorRecovery provides automatic error recovery for agent executions. It attempts to recover from certain error types by modifying inputs and retrying. This struct is safe for concurrent use as long as configuration is not modified after creation. Use WithTimezone to create new instances with different settings.

func NewErrorRecovery

func NewErrorRecovery(timeService aitime.TimeService) *ErrorRecovery

NewErrorRecovery creates a new ErrorRecovery instance.

func (*ErrorRecovery) ExecuteWithRecovery

func (r *ErrorRecovery) ExecuteWithRecovery(
	ctx context.Context,
	executor ExecutorFunc,
	input string,
) (string, error)

ExecuteWithRecovery executes the given function with automatic error recovery. If the execution fails with a recoverable error, it attempts to fix the input and retry once.

Returns:

  • On success: (result, nil)
  • On failure: (user-friendly message, original error)

Use ExecuteWithRecoveryDetailed if you need more detailed execution information.

func (*ErrorRecovery) ExecuteWithRecoveryDetailed

func (r *ErrorRecovery) ExecuteWithRecoveryDetailed(
	ctx context.Context,
	executor ExecutorFunc,
	input string,
) RecoveryResult

ExecuteWithRecoveryDetailed executes with recovery and returns detailed result. This is the recommended method when you need to programmatically distinguish between successful results and error messages.

func (*ErrorRecovery) WithTimezone

func (r *ErrorRecovery) WithTimezone(tz string) *ErrorRecovery

WithTimezone returns a new ErrorRecovery instance with the specified timezone. This method is safe for concurrent use as it creates a new instance.

type EventCallback

type EventCallback func(eventType string, eventData interface{}) error

EventCallback is the callback function type for agent events. EventCallback 是代理事件的回调函数类型。

The callback receives:

  • eventType: The type of event (e.g., "thinking", "tool_use", "tool_result", "answer", "error")
  • eventData: The event data (can be a struct, string, or nil)

返回错误将中止代理执行。

type EventMeta added in v0.80.0

type EventMeta struct {
	// Timing
	DurationMs      int64 // Event duration in milliseconds
	TotalDurationMs int64 // Total elapsed time since start

	// Tool call info
	ToolName string // Tool name (e.g., "bash", "editor_write")
	ToolID   string // Unique tool call ID
	Status   string // "running", "success", "error"
	ErrorMsg string // Error message if status=error

	// Token usage (when available)
	InputTokens      int32 // Input tokens
	OutputTokens     int32 // Output tokens
	CacheWriteTokens int32 // Cache write tokens
	CacheReadTokens  int32 // Cache read tokens

	// Summaries for UI
	InputSummary  string // Human-readable input summary
	OutputSummary string // Truncated output preview

	// File operations
	FilePath  string // Affected file path
	LineCount int32  // Number of lines affected
}

EventMeta contains detailed metadata for streaming events. EventMeta 包含流式事件的详细元数据。

type EventWithMeta added in v0.80.0

type EventWithMeta struct {
	EventType string     // Event type (thinking, tool_use, tool_result, etc.)
	EventData string     // Event data content
	Meta      *EventMeta // Enhanced metadata
}

EventWithMeta extends the basic event with metadata for observability. EventWithMeta 扩展基本事件,添加元数据以增强可观测性。

type EvolutionMode added in v0.70.0

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

EvolutionMode implements CCMode for Evolution Mode (self-evolution). EvolutionMode 为进化模式(自我进化)实现 CCMode。

Evolution Mode allows DivineSense to modify its own source code using Claude Code CLI. The actual git operations and PR creation are handled by CC itself - this mode only provides configuration and permission checking.

func NewEvolutionMode added in v0.70.0

func NewEvolutionMode(cfg *EvolutionModeConfig) *EvolutionMode

NewEvolutionMode creates a new EvolutionMode instance. NewEvolutionMode 创建一个新的 EvolutionMode 实例。

func (*EvolutionMode) BuildSystemPrompt added in v0.70.0

func (m *EvolutionMode) BuildSystemPrompt(cfg *CCRunnerConfig) string

BuildSystemPrompt builds the Evolution Mode system prompt.

func (*EvolutionMode) CheckPermission added in v0.70.0

func (m *EvolutionMode) CheckPermission(ctx context.Context, userID int32) error

CheckPermission validates that the user can use Evolution Mode. Only admins can use Evolution Mode when enabled via environment variable.

func (*EvolutionMode) GetWorkDir added in v0.70.0

func (m *EvolutionMode) GetWorkDir(userID int32) string

GetWorkDir returns the source code directory for evolution.

func (*EvolutionMode) Name added in v0.70.0

func (m *EvolutionMode) Name() string

Name returns the mode identifier.

func (*EvolutionMode) OnComplete added in v0.70.0

func (m *EvolutionMode) OnComplete(ctx context.Context) error

OnComplete is a no-op for Evolution Mode (CC handles PR creation).

type EvolutionModeConfig added in v0.70.0

type EvolutionModeConfig struct {
	SourceDir string       // Project root directory for evolution
	AdminOnly bool         // Whether only admins can use evolution mode
	Store     *store.Store // Store for user role checking (optional, skips admin check if nil)
}

EvolutionModeConfig holds configuration for EvolutionMode. EvolutionModeConfig 保存 EvolutionMode 的配置。

type EvolutionParrot added in v0.70.0

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

EvolutionParrot implements the Evolution Mode agent for self-evolution. EvolutionParrot 实现进化模式代理用于自我进化。

Evolution Mode allows DivineSense to modify its own source code under strict safety constraints. All git operations and PR creation are handled by Claude Code CLI itself - this parrot only provides configuration.

func NewEvolutionParrot added in v0.70.0

func NewEvolutionParrot(sourceDir string, userID int32, sessionID string, st *store.Store, adminOnly ...bool) (*EvolutionParrot, error)

NewEvolutionParrot creates a new EvolutionParrot instance. NewEvolutionParrot 创建一个新的 EvolutionParrot 实例。

Parameters:

  • sourceDir: DivineSense source code directory
  • userID: User ID requesting evolution mode
  • sessionID: Session identifier for persistence
  • st: Store for user role checking (required for admin verification)
  • adminOnly: Whether only admins can use evolution mode (default: from env or true)

func (*EvolutionParrot) Cancel added in v0.70.0

func (p *EvolutionParrot) Cancel()

Cancel cancels the current evolution session. Cancel 取消当前进化会话。

func (*EvolutionParrot) ExecuteWithCallback added in v0.70.0

func (p *EvolutionParrot) ExecuteWithCallback(
	ctx context.Context,
	userInput string,
	history []string,
	callback EventCallback,
) error

ExecuteWithCallback runs the Evolution Mode agent with streaming. ExecuteWithCallback 运行进化模式代理并流式传输。

func (*EvolutionParrot) GetSessionID added in v0.70.0

func (p *EvolutionParrot) GetSessionID() string

GetSessionID returns the current session ID. GetSessionID 返回当前会话 ID。

func (*EvolutionParrot) GetSessionStats added in v0.80.0

func (p *EvolutionParrot) GetSessionStats() *SessionStats

GetSessionStats returns the session statistics from the last execution. GetSessionStats 返回上次执行的会话统计数据。

func (*EvolutionParrot) GetTaskID added in v0.70.0

func (p *EvolutionParrot) GetTaskID() string

GetTaskID returns the evolution task ID. GetTaskID 返回进化任务 ID。

func (*EvolutionParrot) GetUserID added in v0.70.0

func (p *EvolutionParrot) GetUserID() int32

GetUserID returns the user ID. GetUserID 返回用户 ID。

func (*EvolutionParrot) GetWorkDir added in v0.70.0

func (p *EvolutionParrot) GetWorkDir() string

GetWorkDir returns the working directory. GetWorkDir 返回工作目录。

func (*EvolutionParrot) IsSessionActive added in v0.70.0

func (p *EvolutionParrot) IsSessionActive() bool

IsSessionActive returns whether a session has been started. IsSessionActive 返回是否已启动会话。

func (*EvolutionParrot) Name added in v0.70.0

func (p *EvolutionParrot) Name() string

Name returns the name of the parrot. Name 返回鹦鹉名称。

func (*EvolutionParrot) ResetSession added in v0.70.0

func (p *EvolutionParrot) ResetSession()

ResetSession resets the evolution session. ResetSession 重置进化会话。

func (*EvolutionParrot) SelfDescribe added in v0.70.0

func (p *EvolutionParrot) SelfDescribe() *ParrotSelfCognition

SelfDescribe returns the EvolutionParrot's metacognitive information. SelfDescribe 返回进化鹦鹉的元认知信息。

func (*EvolutionParrot) SetDeviceContext added in v0.70.0

func (p *EvolutionParrot) SetDeviceContext(contextJson string)

SetDeviceContext sets the device context for the parrot. SetDeviceContext 设置鹦鹉的设备上下文。

type ExecutorFunc

type ExecutorFunc func(ctx context.Context, input string) (string, error)

ExecutorFunc is the function signature for agent executors.

type GeekMode added in v0.70.0

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

GeekMode implements CCMode for the Geek Mode (user sandbox). GeekMode 为极客模式(用户沙箱)实现 CCMode。

func NewGeekMode added in v0.70.0

func NewGeekMode(baseWorkDir string) *GeekMode

NewGeekMode creates a new GeekMode instance. NewGeekMode 创建一个新的 GeekMode 实例。

func (*GeekMode) BuildSystemPrompt added in v0.70.0

func (m *GeekMode) BuildSystemPrompt(cfg *CCRunnerConfig) string

BuildSystemPrompt builds the Geek Mode system prompt. Geek Mode is a general-purpose assistant for code-related tasks. Adds File Output section (Geek-specific) to base prompt.

func (*GeekMode) CheckPermission added in v0.70.0

func (m *GeekMode) CheckPermission(ctx context.Context, userID int32) error

CheckPermission validates that the user can use Geek Mode. All authenticated users can use Geek Mode.

func (*GeekMode) GetWorkDir added in v0.70.0

func (m *GeekMode) GetWorkDir(userID int32) string

GetWorkDir returns the user-specific sandbox directory.

func (*GeekMode) Name added in v0.70.0

func (m *GeekMode) Name() string

Name returns the mode identifier.

func (*GeekMode) OnComplete added in v0.70.0

func (m *GeekMode) OnComplete(ctx context.Context) error

OnComplete is a no-op for Geek Mode.

type GeekParrot

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

GeekParrot is the Geek Mode specialist parrot (🦜 极客). GeekParrot 是极客模式专用鹦鹉(🦜 极客).

It provides DIRECT access to Claude Code CLI without any LLM processing, using the unified CCRunner + GeekMode architecture. 它提供 Claude Code CLI 的直接访问,不经过任何 LLM 处理,使用统一的 CCRunner + GeekMode 架构。

func NewGeekParrot

func NewGeekParrot(sourceDir string, userID int32, sessionID string) (*GeekParrot, error)

NewGeekParrot creates a new GeekParrot instance. NewGeekParrot 创建一个新的 GeekParrot 实例。

func (*GeekParrot) Cancel

func (p *GeekParrot) Cancel()

Cancel is a no-op for Geek Mode (session continues unless explicitly reset). Cancel 对极客模式是空操作(会话继续,除非显式重置)。

func (*GeekParrot) ExecuteWithCallback

func (p *GeekParrot) ExecuteWithCallback(
	ctx context.Context,
	userInput string,
	history []string,
	callback EventCallback,
) error

ExecuteWithCallback runs Claude Code CLI with session persistence. ExecuteWithCallback 运行 Claude Code CLI,支持会话持久化。

func (*GeekParrot) GetSessionID

func (p *GeekParrot) GetSessionID() string

GetSessionID returns the current session ID. GetSessionID 返回当前会话 ID。

func (*GeekParrot) GetSessionStats added in v0.80.0

func (p *GeekParrot) GetSessionStats() *SessionStats

GetSessionStats returns the session statistics from the last execution. GetSessionStats 返回上次执行的会话统计数据。

func (*GeekParrot) GetUserID

func (p *GeekParrot) GetUserID() int32

GetUserID returns the user ID for this parrot. GetUserID 返回此鹦鹉的用户 ID。

func (*GeekParrot) GetWorkDir

func (p *GeekParrot) GetWorkDir() string

GetWorkDir returns the working directory for Claude Code CLI. GetWorkDir 返回 Claude Code CLI 的工作目录。

func (*GeekParrot) IsSessionActive

func (p *GeekParrot) IsSessionActive() bool

IsSessionActive returns whether a session has been started. IsSessionActive 返回是否已启动会话。

func (*GeekParrot) Name

func (p *GeekParrot) Name() string

Name returns the name of the parrot. Name 返回鹦鹉名称。

func (*GeekParrot) ResetSession

func (p *GeekParrot) ResetSession()

ResetSession resets the session state (e.g., on error or user request). ResetSession 重置会话状态(例如出错或用户请求时)。

func (*GeekParrot) SelfDescribe

func (p *GeekParrot) SelfDescribe() *ParrotSelfCognition

SelfDescribe returns the GeekParrot's metacognitive information. SelfDescribe 返回极客鹦鹉的元认知信息。

func (*GeekParrot) SetDeviceContext

func (p *GeekParrot) SetDeviceContext(contextJson string)

SetDeviceContext sets the full device and browser context for the parrot. SetDeviceContext 为鹦鹉设置完整的设备和浏览器上下文。

type GenericCache

type GenericCache[T any] struct {
	// contains filtered or unexported fields
}

GenericCache is a generic type-safe cache wrapper. GenericCache 是泛型类型安全的缓存包装器。

func NewGenericCache

func NewGenericCache[T any](maxEntries int, ttl time.Duration) *GenericCache[T]

NewGenericCache creates a new generic cache. NewGenericCache 创建一个新的泛型缓存。

func (*GenericCache[T]) Clear

func (g *GenericCache[T]) Clear()

Clear removes all entries from the generic cache. Clear 从泛型缓存中移除所有条目。

func (*GenericCache[T]) Delete

func (g *GenericCache[T]) Delete(key string)

Delete removes a key from the generic cache. Delete 从泛型缓存中删除键。

func (*GenericCache[T]) Get

func (g *GenericCache[T]) Get(key string) (T, bool)

Get retrieves a value from the generic cache. Get 从泛型缓存中检索值。

func (*GenericCache[T]) Set

func (g *GenericCache[T]) Set(key string, value T)

Set stores a value in the generic cache. Set 在泛型缓存中存储值。

func (*GenericCache[T]) Size

func (g *GenericCache[T]) Size() int

Size returns the current number of entries in the generic cache. Size 返回泛型缓存中的当前条目数。

func (*GenericCache[T]) Stats

func (g *GenericCache[T]) Stats() CacheStats

Stats returns cache statistics for the generic cache. Stats 返回泛型缓存的缓存统计信息。

type IntentClassifier

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

- Batch tasks (IntentBatchCreate) → Plan-Execute mode.

func NewIntentClassifier

func NewIntentClassifier() *IntentClassifier

NewIntentClassifier creates a new IntentClassifier with default patterns.

func (*IntentClassifier) Classify

func (ic *IntentClassifier) Classify(input string) TaskIntent

Classify determines the intent of the user input. Handles negation patterns (e.g., "不要创建", "不是今天").

func (*IntentClassifier) ClassifyAndRoute

func (ic *IntentClassifier) ClassifyAndRoute(input string) (TaskIntent, bool)

ClassifyAndRoute is a convenience method that classifies and returns the execution mode.

func (*IntentClassifier) ShouldUsePlanExecute

func (ic *IntentClassifier) ShouldUsePlanExecute(intent TaskIntent) bool

ShouldUsePlanExecute returns true if the intent should use Plan-Execute mode.

type IntentResult

type IntentResult struct {
	Intent     TaskIntent `json:"intent"`
	Reasoning  string     `json:"reasoning,omitempty"`
	Confidence float64    `json:"confidence"`
}

IntentResult represents the LLM classification result.

type LLMIntentClassifier

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

LLMIntentClassifier uses a lightweight LLM for intent classification. This provides better accuracy than rule-based matching, especially for nuanced natural language inputs.

func NewLLMIntentClassifier

func NewLLMIntentClassifier(cfg LLMIntentConfig) *LLMIntentClassifier

NewLLMIntentClassifier creates a new LLM-based intent classifier. Uses a lightweight model optimized for fast classification.

func (*LLMIntentClassifier) Classify

func (ic *LLMIntentClassifier) Classify(ctx context.Context, input string) (TaskIntent, error)

Classify determines the intent of the user input using LLM.

func (*LLMIntentClassifier) ClassifyAndRoute

func (ic *LLMIntentClassifier) ClassifyAndRoute(ctx context.Context, input string) (TaskIntent, bool, error)

ClassifyAndRoute is a convenience method that classifies and returns the execution mode.

func (*LLMIntentClassifier) ClassifyWithDetails

func (ic *LLMIntentClassifier) ClassifyWithDetails(ctx context.Context, input string) (*IntentResult, error)

ClassifyWithDetails returns the full classification result including confidence.

func (*LLMIntentClassifier) ShouldUsePlanExecute

func (ic *LLMIntentClassifier) ShouldUsePlanExecute(intent TaskIntent) bool

ShouldUsePlanExecute returns true if the intent should use Plan-Execute mode.

type LLMIntentConfig

type LLMIntentConfig struct {
	APIKey  string
	BaseURL string
	Model   string // Recommended: Qwen/Qwen2.5-7B-Instruct
}

LLMIntentConfig holds configuration for the LLM intent classifier.

type LRUCache

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

LRUCache is a thread-safe LRU (Least Recently Used) cache with TTL support. LRUCache 是一个线程安全的 LRU(最近最少使用)缓存,支持 TTL。

func NewLRUCache

func NewLRUCache(maxEntries int, ttl time.Duration) *LRUCache

NewLRUCache creates a new LRUCache. NewLRUCache 创建一个新的 LRUCache。

Parameters:

  • maxEntries: Maximum number of entries in the cache (must be > 0)
  • ttl: Time-to-live for cache entries (0 = no expiration)

Example:

// Create a cache with max 100 entries and 5 minute TTL
cache := NewLRUCache(100, 5*time.Minute)

func (*LRUCache) Clear

func (c *LRUCache) Clear()

Clear removes all entries from the cache. Clear 从缓存中移除所有条目。

func (*LRUCache) Delete

func (c *LRUCache) Delete(key string)

Delete removes a key from the cache. Delete 从缓存中删除键。

func (*LRUCache) Get

func (c *LRUCache) Get(key string) (interface{}, bool)

Get retrieves a value from the cache. Get 从缓存中检索值。

Returns:

  • value: The cached value (or nil if not found/expired)
  • found: Whether the value was found and not expired

func (*LRUCache) Set

func (c *LRUCache) Set(key string, value interface{})

Set stores a value in the cache. Set 在缓存中存储值。

If the key already exists, the value is updated and the entry is moved to the front. If the cache is full, the least recently used entry is evicted.

func (*LRUCache) Size

func (c *LRUCache) Size() int

Size returns the current number of entries in the cache. Size 返回缓存中的当前条目数。

func (*LRUCache) Stats

func (c *LRUCache) Stats() CacheStats

Stats returns cache statistics. Stats 返回缓存统计信息。

func (*LRUCache) String

func (c *LRUCache) String() string

String returns a string representation of the cache. String 返回缓存的字符串表示。

type MemoParrot

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

MemoParrot is the note-taking assistant parrot (🦜 灰灰). MemoParrot 是笔记助手鹦鹉(🦜 灰灰)。

func NewMemoParrot

func NewMemoParrot(
	retriever *retrieval.AdaptiveRetriever,
	llm ai.LLMService,
	userID int32,
) (*MemoParrot, error)

NewMemoParrot creates a new memo parrot agent. NewMemoParrot 创建一个新的笔记助手鹦鹉。

func (*MemoParrot) ExecuteWithCallback

func (p *MemoParrot) ExecuteWithCallback(
	ctx context.Context,
	userInput string,
	history []string,
	callback EventCallback,
) error

ExecuteWithCallback executes the memo parrot with callback support. ExecuteWithCallback 执行笔记助手鹦鹉并支持回调。

func (*MemoParrot) GetStats

func (p *MemoParrot) GetStats() CacheStats

GetStats returns the cache statistics for the memo parrot. GetStats 返回笔记助手鹦鹉的缓存统计信息。

func (*MemoParrot) Name

func (p *MemoParrot) Name() string

Name returns the name of the parrot. Name 返回鹦鹉名称。

func (*MemoParrot) SelfDescribe

func (p *MemoParrot) SelfDescribe() *ParrotSelfCognition

SelfDescribe returns the memo parrot's metacognitive understanding of itself. SelfDescribe 返回笔记助手鹦鹉的元认知自我理解。

type MemoQueryResultData

type MemoQueryResultData struct {
	Query string        `json:"query"`
	Memos []MemoSummary `json:"memos"`
	Count int           `json:"count"`
}

MemoQueryResultData represents the result of a memo search. MemoQueryResultData 表示笔记搜索的结果。

type MemoSummary

type MemoSummary struct {
	UID     string  `json:"uid"`
	Content string  `json:"content"`
	Score   float32 `json:"score"`
}

MemoSummary represents a simplified memo for query results. MemoSummary 表示查询结果中的简化笔记。

type MetricsRecorder

type MetricsRecorder interface {
	RecordPromptVersion(agentType, promptVersion string, success bool, latencyMs int64)
}

MetricsRecorder defines the interface for recording prompt version metrics. This allows dependency injection for testing and different backends.

type NativeTool

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

NativeTool implements ToolWithSchema with direct function execution.

func (*NativeTool) Description

func (t *NativeTool) Description() string

Description returns the tool description.

func (*NativeTool) Name

func (t *NativeTool) Name() string

Name returns the tool name.

func (*NativeTool) Parameters

func (t *NativeTool) Parameters() map[string]interface{}

Parameters returns the JSON Schema for parameters.

func (*NativeTool) Run

func (t *NativeTool) Run(ctx context.Context, input string) (string, error)

Run executes the tool.

type ParrotAgent

type ParrotAgent interface {
	// Name returns the name of the parrot agent.
	Name() string

	// ExecuteWithCallback executes the agent with callback support for real-time feedback.
	// ExecuteWithCallback 执行代理并支持回调以实现实时反馈。
	ExecuteWithCallback(ctx context.Context, userInput string, history []string, callback EventCallback) error

	// SelfDescribe returns the parrot's self-cognition (metacognition) information.
	// SelfDescribe 返回鹦鹉的自我认知(元认知)信息。
	SelfDescribe() *ParrotSelfCognition
}

ParrotAgent is the interface for all parrot agents. ParrotAgent 是所有鹦鹉代理的接口。

type ParrotError

type ParrotError struct {
	Err       error
	AgentName string
	Operation string
}

ParrotError represents an error from a parrot agent. ParrotError 表示来自鹦鹉代理的错误。

func NewParrotError

func NewParrotError(agentName, operation string, err error) *ParrotError

NewParrotError creates a new ParrotError. NewParrotError 创建一个新的 ParrotError。

func (*ParrotError) Error

func (e *ParrotError) Error() string

Error implements the error interface. Error 实现错误接口。

func (*ParrotError) Unwrap

func (e *ParrotError) Unwrap() error

Unwrap returns the underlying error. Unwrap 返回底层错误。

type ParrotSelfCognition

type ParrotSelfCognition struct {
	AvianIdentity       *AvianIdentity       `json:"avian_identity"`
	EmotionalExpression *EmotionalExpression `json:"emotional_expression,omitempty"`
	WorkingStyle        string               `json:"working_style"`
	Title               string               `json:"title"`
	Emoji               string               `json:"emoji"`
	Name                string               `json:"name"`
	SelfIntroduction    string               `json:"self_introduction"`
	FunFact             string               `json:"fun_fact"`
	AvianBehaviors      []string             `json:"avian_behaviors,omitempty"`
	Personality         []string             `json:"personality"`
	Capabilities        []string             `json:"capabilities"`
	Limitations         []string             `json:"limitations"`
	FavoriteTools       []string             `json:"favorite_tools"`
}

ParrotSelfCognition represents a parrot's metacognitive understanding of itself. ParrotSelfCognition 表示鹦鹉对自己的元认知理解。

type ParrotStream

type ParrotStream interface {
	// Send sends an event to the client.
	// Send 向客户端发送一个事件。
	Send(eventType string, eventData interface{}) error

	// Close closes the stream.
	// Close 关闭流。
	Close() error
}

ParrotStream is the interface for streaming responses to the client. ParrotStream 是向客户端流式传输响应的接口。

type ParrotStreamAdapter

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

ParrotStreamAdapter adapts Connect RPC server stream to ParrotStream interface. ParrotStreamAdapter 将 Connect RPC 服务端流适配到 ParrotStream 接口。

func NewParrotStreamAdapter

func NewParrotStreamAdapter(sendFunc func(eventType string, eventData interface{}) error) *ParrotStreamAdapter

NewParrotStreamAdapter creates a new ParrotStreamAdapter. NewParrotStreamAdapter 创建一个新的 ParrotStreamAdapter。

func (*ParrotStreamAdapter) Close

func (a *ParrotStreamAdapter) Close() error

Close is a no-op for the adapter (the caller manages stream lifecycle). Close 对适配器来说是无操作(调用者管理流的生命周期)。

func (*ParrotStreamAdapter) Send

func (a *ParrotStreamAdapter) Send(eventType string, eventData interface{}) error

Send sends an event through the adapter. Send 通过适配器发送事件。

type PromptConfig

type PromptConfig struct {
	Templates map[PromptVersion]string
	Version   PromptVersion
	Enabled   bool
}

PromptConfig holds versioned prompt templates.

func DefaultPromptConfig

func DefaultPromptConfig() *PromptConfig

DefaultPromptConfig returns the default prompt configuration.

func (*PromptConfig) AddTemplate

func (c *PromptConfig) AddTemplate(v PromptVersion, template string)

AddTemplate adds or updates a prompt template for a version.

func (*PromptConfig) GetTemplate

func (c *PromptConfig) GetTemplate() string

GetTemplate returns the active prompt template.

func (*PromptConfig) SetVersion

func (c *PromptConfig) SetVersion(v PromptVersion) error

SetVersion sets the active prompt version.

type PromptExperimentReport

type PromptExperimentReport struct {
	GeneratedAt          time.Time
	AgentType            string
	ControlVersion       PromptVersion
	TreatmentVersion     PromptVersion
	Confidence           string
	Recommendation       string
	TreatmentRequests    int64
	ControlAvgLatency    int64
	ControlSuccessRate   float64
	TreatmentSuccesses   int64
	TreatmentSuccessRate float64
	TreatmentAvgLatency  int64
	SuccessRateDelta     float64
	LatencyDelta         int64
	ControlSuccesses     int64
	ControlRequests      int64
	TrafficPercent       int
}

PromptExperimentReport represents a report of an A/B experiment's performance.

func GenerateExperimentReport

func GenerateExperimentReport(agentType string) *PromptExperimentReport

GenerateExperimentReport generates an A/B experiment report for an agent type.

type PromptVersion

type PromptVersion string

PromptVersion identifies a specific version of a prompt template.

const (
	// PromptV1 is the initial prompt version (baseline).
	PromptV1 PromptVersion = "v1"
	// PromptV2 is an experimental version for A/B testing.
	PromptV2 PromptVersion = "v2"
)

func GetPromptVersion

func GetPromptVersion(agentType string) PromptVersion

GetPromptVersion returns the current active prompt version for an agent type. Thread-safe: uses read lock for concurrent access.

func GetPromptVersionForUser

func GetPromptVersionForUser(agentType string, userID int32) PromptVersion

GetPromptVersionForUser returns the appropriate prompt version for a user, taking into account A/B experiments if enabled.

type RecoveryResult

type RecoveryResult struct {
	OriginalError error
	Result        string
	Success       bool
	WasRecovered  bool
}

RecoveryResult contains the result of an execution with recovery.

type ScheduleDraft

type ScheduleDraft struct {
	StartTime     *time.Time
	EndTime       *time.Time
	Recurrence    *schedule.RecurrenceRule
	Confidence    map[string]float32
	Title         string
	Description   string
	Location      string
	Timezone      string
	OriginalInput string
	AllDay        bool
}

ScheduleDraft represents a partially specified schedule.

type ScheduleParrotV2

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

ScheduleParrotV2 is the schedule assistant parrot using the new framework-less agent. It wraps SchedulerAgentV2 with zero code rewriting.

func NewScheduleParrotV2

func NewScheduleParrotV2(agent *SchedulerAgentV2) (*ScheduleParrotV2, error)

NewScheduleParrotV2 creates a new schedule parrot agent with the V2 framework.

func (*ScheduleParrotV2) ExecuteWithCallback

func (p *ScheduleParrotV2) ExecuteWithCallback(
	ctx context.Context,
	userInput string,
	history []string,
	callback EventCallback,
) error

ExecuteWithCallback executes the schedule parrot by forwarding to SchedulerAgentV2.

func (*ScheduleParrotV2) Name

func (p *ScheduleParrotV2) Name() string

Name returns the name of the parrot.

func (*ScheduleParrotV2) SelfDescribe

func (p *ScheduleParrotV2) SelfDescribe() *ParrotSelfCognition

SelfDescribe returns the schedule parrot's metacognitive understanding of itself.

func (*ScheduleParrotV2) StreamChat

func (p *ScheduleParrotV2) StreamChat(ctx context.Context, input string, history []string) (<-chan string, error)

StreamChat is the streaming entry point.

type ScheduleQueryResultData

type ScheduleQueryResultData struct {
	Query                string            `json:"query"`
	TimeRangeDescription string            `json:"time_range_description"`
	QueryType            string            `json:"query_type"`
	Schedules            []ScheduleSummary `json:"schedules"`
	Count                int               `json:"count"`
}

ScheduleQueryResultData represents the result of a schedule query. ScheduleQueryResultData 表示日程查询的结果。

type ScheduleSummary

type ScheduleSummary struct {
	UID            string `json:"uid"`
	Title          string `json:"title"`
	Location       string `json:"location,omitempty"`
	Status         string `json:"status"`
	StartTimestamp int64  `json:"start_ts"`
	EndTimestamp   int64  `json:"end_ts"`
	AllDay         bool   `json:"all_day"`
}

ScheduleSummary represents a simplified schedule for query results. ScheduleSummary 表示查询结果中的简化日程。

type SchedulerAgentV2

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

SchedulerAgentV2 is the new framework-less schedule agent. It uses native LLM tool calling without LangChainGo dependency.

func NewSchedulerAgentV2

func NewSchedulerAgentV2(llm ai.LLMService, scheduleSvc schedule.Service, userID int32, userTimezone string) (*SchedulerAgentV2, error)

NewSchedulerAgentV2 creates a new framework-less schedule agent.

func (*SchedulerAgentV2) Execute

func (a *SchedulerAgentV2) Execute(ctx context.Context, userInput string) (string, error)

Execute runs the agent with the given user input.

func (*SchedulerAgentV2) ExecuteWithCallback

func (a *SchedulerAgentV2) ExecuteWithCallback(ctx context.Context, userInput string, conversationCtx *ConversationContext, callback func(event string, data string)) (string, error)

ExecuteWithCallback runs the agent with state-aware context and callback support.

func (*SchedulerAgentV2) SetIntentClassifier

func (a *SchedulerAgentV2) SetIntentClassifier(classifier *LLMIntentClassifier)

SetIntentClassifier configures the LLM-based intent classifier. When set, the agent will classify user input before execution to optimize routing and provide better responses.

type Session added in v0.80.0

type Session struct {
	ID         string
	Config     CCRunnerConfig
	Cmd        *exec.Cmd
	Stdin      io.WriteCloser
	Stdout     io.ReadCloser
	Stderr     io.ReadCloser
	Cancel     context.CancelFunc
	CreatedAt  time.Time
	LastActive time.Time
	Status     SessionStatus
	// contains filtered or unexported fields
}

Session represents a persistent process of Claude Code CLI.

func (*Session) GetStatus added in v0.80.0

func (s *Session) GetStatus() SessionStatus

GetStatus returns the current session status. GetStatus 返回当前会话状态。

func (*Session) IsAlive added in v0.80.0

func (s *Session) IsAlive() bool

IsAlive checks if the process is still running.

func (*Session) SetStatus added in v0.80.0

func (s *Session) SetStatus(status SessionStatus)

SetStatus updates the session status with proper locking. SetStatus 使用适当的锁更新会话状态。

func (*Session) Touch added in v0.80.0

func (s *Session) Touch()

Touch updates LastActive time.

func (*Session) WriteInput added in v0.80.0

func (s *Session) WriteInput(msg map[string]any) error

WriteInput injects a JSON message to Stdin. Transitions session to Busy during write, back to Ready after completion. 注入 JSON 消息到 Stdin。写入时转换为 Busy,完成后恢复为 Ready。

type SessionManager added in v0.80.0

type SessionManager interface {
	GetOrCreateSession(ctx context.Context, sessionID string, cfg CCRunnerConfig) (*Session, error)
	GetSession(sessionID string) (*Session, bool)
	TerminateSession(sessionID string) error
	ListActiveSessions() []*Session
}

SessionManager defines the interface for managing persistent sessions.

type SessionStats added in v0.80.0

type SessionStats struct {
	SessionID            string
	StartTime            time.Time
	TotalDurationMs      int64
	ThinkingDurationMs   int64
	ToolDurationMs       int64
	GenerationDurationMs int64
	InputTokens          int32
	OutputTokens         int32
	CacheWriteTokens     int32
	CacheReadTokens      int32
	ToolCallCount        int32
	ToolsUsed            map[string]bool
	FilesModified        int32
	FilePaths            []string
	// contains filtered or unexported fields
}

SessionStats collects session-level statistics for Geek/Evolution modes. SessionStats 收集极客/进化模式的会话级别统计数据。

func (*SessionStats) EndGeneration added in v0.80.0

func (s *SessionStats) EndGeneration()

EndGeneration marks the end of the generation phase and records its duration. EndGeneration 标记生成阶段的结束并记录其持续时间。

func (*SessionStats) EndThinking added in v0.80.0

func (s *SessionStats) EndThinking()

EndThinking marks the end of the thinking phase and records its duration. EndThinking 标记思考阶段的结束并记录其持续时间。

func (*SessionStats) RecordTokens added in v0.80.0

func (s *SessionStats) RecordTokens(input, output, cacheWrite, cacheRead int32)

RecordTokens records token usage.

func (*SessionStats) RecordToolResult added in v0.80.0

func (s *SessionStats) RecordToolResult() (durationMs int64)

RecordToolResult records the end of a tool call.

func (*SessionStats) RecordToolUse added in v0.80.0

func (s *SessionStats) RecordToolUse(toolName, toolID string)

RecordToolUse records the start of a tool call.

func (*SessionStats) StartGeneration added in v0.80.0

func (s *SessionStats) StartGeneration()

StartGeneration marks the start of the generation phase. StartGeneration 标记生成阶段的开始。

func (*SessionStats) StartThinking added in v0.80.0

func (s *SessionStats) StartThinking()

StartThinking marks the start of the thinking phase. StartThinking 标记思考阶段的开始。

func (*SessionStats) ToSummary added in v0.80.0

func (s *SessionStats) ToSummary() map[string]interface{}

ToSummary converts stats to a summary map for JSON serialization.

type SessionStatsProvider added in v0.80.0

type SessionStatsProvider interface {
	// GetSessionStats returns the session statistics from the last execution.
	// GetSessionStats 返回上次执行的会话统计数据。
	GetSessionStats() *SessionStats
}

SessionStatsProvider is an optional interface for agents that can provide session statistics. SessionStatsProvider 是可选接口,用于可以提供会话统计数据的代理。 Only GeekParrot and EvolutionParrot (which use CCRunner) implement this interface. 只有 GeekParrot 和 EvolutionParrot(使用 CCRunner)实现此接口。

type SessionStatus added in v0.80.0

type SessionStatus string

SessionStatus defines the current state of a session.

const (
	SessionStatusStarting SessionStatus = "starting"
	SessionStatusReady    SessionStatus = "ready"
	SessionStatusBusy     SessionStatus = "busy"
	SessionStatusDead     SessionStatus = "dead"
)

type StreamEvent added in v0.80.0

type StreamEvent struct {
	Type      string           `json:"type"`           // thinking, tool_use, tool_result, answer, error
	Content   string           `json:"content"`        // The actual text content
	Meta      *StreamEventMeta `json:"meta,omitempty"` // Strongly-typed metadata
	Timestamp int64            `json:"timestamp"`
}

StreamEvent represents a standardized event for the Web UI.

type StreamEventMeta added in v0.80.0

type StreamEventMeta struct {
	ToolName  string `json:"tool_name,omitempty"`   // Tool name for tool_use events
	ToolID    string `json:"tool_id,omitempty"`     // Tool ID for tool_use events
	IsError   bool   `json:"is_error,omitempty"`    // Error flag for tool_result events
	FilePath  string `json:"file_path,omitempty"`   // File path for file operations
	ExitCode  int    `json:"exit_code,omitempty"`   // Process exit code for run events
	Duration  int    `json:"duration_ms,omitempty"` // Operation duration in milliseconds
	SessionID string `json:"session_id,omitempty"`  // Associated session ID

	// Raw allows access to any additional fields not in the typed struct.
	// Raw 允许访问类型化结构之外的任何其他字段。
	Raw map[string]any `json:"-"`
}

StreamEventMeta provides strongly-typed metadata for StreamEvent. StreamEventMeta 为 StreamEvent 提供强类型的元数据。

type StreamMessage

type StreamMessage struct {
	Message   *AssistantMessage `json:"message,omitempty"`
	Input     map[string]any    `json:"input,omitempty"`
	Type      string            `json:"type"`
	Timestamp string            `json:"timestamp,omitempty"`
	SessionID string            `json:"session_id,omitempty"`
	Role      string            `json:"role,omitempty"`
	Name      string            `json:"name,omitempty"`
	Output    string            `json:"output,omitempty"`
	Status    string            `json:"status,omitempty"`
	Error     string            `json:"error,omitempty"`
	Content   []ContentBlock    `json:"content,omitempty"`
	Duration  int               `json:"duration_ms,omitempty"`
}

StreamMessage represents a single event in the stream-json format. StreamMessage 表示 stream-json 格式中的单个事件。

func (*StreamMessage) GetContentBlocks

func (m *StreamMessage) GetContentBlocks() []ContentBlock

GetContentBlocks returns the content blocks, checking both direct and nested locations. GetContentBlocks 返回内容块,同时检查直接和嵌套位置。

type TaskIntent

type TaskIntent string

TaskIntent represents the type of task across all agents. This unified intent system covers memo, schedule, and amazing agents.

const (
	// Schedule-related intents.
	IntentSimpleCreate    TaskIntent = "schedule_create"   // 创建单个日程
	IntentSimpleQuery     TaskIntent = "schedule_query"    // 查询日程/空闲
	IntentSimpleUpdate    TaskIntent = "schedule_update"   // 修改/删除日程
	IntentBatchCreate     TaskIntent = "schedule_batch"    // 重复日程
	IntentConflictResolve TaskIntent = "schedule_conflict" // 处理冲突

	// Memo-related intents.
	IntentMemoSearch TaskIntent = "memo_search" // 搜索笔记
	IntentMemoCreate TaskIntent = "memo_create" // 创建笔记

	// Amazing agent intent.
	IntentAmazing TaskIntent = "amazing" // 综合分析

	// Legacy aliases for backward compatibility.
	IntentScheduleQuery  TaskIntent = "schedule_query"
	IntentScheduleCreate TaskIntent = "schedule_create"
	IntentScheduleUpdate TaskIntent = "schedule_update"
	IntentBatchSchedule  TaskIntent = "schedule_batch"
	IntentMultiQuery     TaskIntent = "amazing" // Alias to amazing
)

type Tool

type Tool interface {
	// Name returns the name of the tool.
	Name() string

	// Description returns a description of what the tool does.
	Description() string

	// Run executes the tool with the given input.
	// Run 使用给定的输入执行工具。
	Run(ctx context.Context, input string) (string, error)
}

Tool is the interface for agent tools. Tool 是代理工具的接口。

type ToolCallRecord

type ToolCallRecord struct {
	Timestamp time.Time
	Tool      string
	Input     string
	Output    string
	Duration  time.Duration
	Success   bool
}

ToolCallRecord records a tool invocation.

type ToolOption

type ToolOption func(*BaseTool)

ToolOption is a function that configures a BaseTool. ToolOption 是配置 BaseTool 的函数。

func WithTimeout

func WithTimeout(timeout time.Duration) ToolOption

WithTimeout sets a timeout for tool execution. WithTimeout 设置工具执行的超时时间。

func WithValidator

func WithValidator(validator func(input string) error) ToolOption

WithValidator sets a custom input validator. WithValidator 设置自定义输入验证器。

type ToolRegistry

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

ToolRegistry manages a collection of tools. ToolRegistry 管理工具集合。

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates a new ToolRegistry. NewToolRegistry 创建一个新的 ToolRegistry。

func (*ToolRegistry) Count

func (r *ToolRegistry) Count() int

Count returns the number of registered tools. Count 返回已注册工具的数量。

func (*ToolRegistry) Describe

func (r *ToolRegistry) Describe() string

Describe returns a description string for all tools. Describe 返回所有工具的描述字符串。

func (*ToolRegistry) Get

func (r *ToolRegistry) Get(name string) (Tool, bool)

Get retrieves a tool by name. Get 按名称获取工具。

func (*ToolRegistry) List

func (r *ToolRegistry) List() []string

List returns all registered tool names. List 返回所有已注册的工具名称。

func (*ToolRegistry) Register

func (r *ToolRegistry) Register(tool Tool) error

Register adds a tool to the registry. Register 向注册表添加工具。

type ToolResult

type ToolResult struct {
	Name      string        `json:"name"`
	Input     string        `json:"input"`
	Output    string        `json:"output"`
	Error     string        `json:"error"`
	Duration  time.Duration `json:"duration"`
	Timestamp int64         `json:"timestamp"`
	Success   bool          `json:"success"`
}

ToolResult represents the result of a tool execution. ToolResult 表示工具执行的结果。

func NewToolResult

func NewToolResult(name, input, output string, duration time.Duration, err error) *ToolResult

NewToolResult creates a new ToolResult. NewToolResult 创建一个新的 ToolResult。

type ToolWithSchema

type ToolWithSchema interface {
	Tool

	// Parameters returns the JSON Schema for the tool's input parameters.
	Parameters() map[string]interface{}
}

ToolWithSchema extends the Tool interface to include JSON Schema definition. This is needed for the new Agent framework to provide tool definitions to the LLM.

func NewNativeTool

func NewNativeTool(
	name string,
	description string,
	execute func(ctx context.Context, input string) (string, error),
	parameters map[string]interface{},
) ToolWithSchema

NewNativeTool creates a new NativeTool.

func ToolFromLegacy

func ToolFromLegacy(
	name, description string,
	runFunc func(ctx context.Context, input string) (string, error),
	inputTypeFunc func() map[string]interface{},
) ToolWithSchema

ToolFromLegacy creates a ToolWithSchema from a tool that has InputType() method. This adapts existing tools like ScheduleQueryTool to the new framework.

type UIConflictResolutionData

type UIConflictResolutionData struct {
	AutoResolved         *UITimeSlotData          `json:"auto_resolved,omitempty"`
	NewSchedule          UIScheduleSuggestionData `json:"new_schedule"`
	SessionID            string                   `json:"session_id,omitempty"`
	ConflictingSchedules []UIConflictSchedule     `json:"conflicting_schedules"`
	SuggestedSlots       []UITimeSlotData         `json:"suggested_slots"`
	Actions              []string                 `json:"actions"`
}

UIConflictResolutionData represents conflict resolution options. UIConflictResolutionData 表示冲突解决选项。

type UIConflictSchedule

type UIConflictSchedule struct {
	UID       string `json:"uid"`
	Title     string `json:"title"`
	Location  string `json:"location,omitempty"`
	StartTime int64  `json:"start_time"`
	EndTime   int64  `json:"end_time"`
	AllDay    bool   `json:"all_day"`
}

UIConflictSchedule represents a conflicting schedule. UIConflictSchedule 表示冲突的日程。

type UIMemoPreviewData

type UIMemoPreviewData struct {
	UID        string   `json:"uid,omitempty"`
	Title      string   `json:"title"`
	Content    string   `json:"content"`
	Reason     string   `json:"reason,omitempty"`
	SessionID  string   `json:"session_id,omitempty"`
	Tags       []string `json:"tags,omitempty"`
	Confidence float32  `json:"confidence"`
}

UIMemoPreviewData represents a memo preview card for generative UI. UIMemoPreviewData 表示生成式 UI 的笔记预览卡片。

type UIQuickActionData

type UIQuickActionData struct {
	ID          string `json:"id"`             // Action ID
	Label       string `json:"label"`          // Button label
	Description string `json:"description"`    // Action description
	Icon        string `json:"icon,omitempty"` // Optional icon name
	Prompt      string `json:"prompt"`         // What to send when clicked
}

UIQuickActionData represents a quick action button. UIQuickActionData 表示快捷操作按钮。

type UIQuickActionsData

type UIQuickActionsData struct {
	Title       string              `json:"title"`
	Description string              `json:"description"`
	SessionID   string              `json:"session_id,omitempty"`
	Actions     []UIQuickActionData `json:"actions"`
}

UIQuickActionsData represents quick action buttons for user. UIQuickActionsData 表示给用户的快捷操作按钮。

type UIScheduleItem

type UIScheduleItem struct {
	UID      string `json:"uid"`
	Title    string `json:"title"`
	Location string `json:"location,omitempty"`
	Status   string `json:"status,omitempty"`
	StartTs  int64  `json:"start_ts"`
	EndTs    int64  `json:"end_ts"`
	AllDay   bool   `json:"all_day"`
}

UIScheduleItem represents a single schedule item for display. UIScheduleItem 表示用于展示的单个日程项。

type UIScheduleListData

type UIScheduleListData struct {
	Title     string           `json:"title"`
	Query     string           `json:"query"`
	TimeRange string           `json:"time_range,omitempty"`
	Reason    string           `json:"reason,omitempty"`
	SessionID string           `json:"session_id,omitempty"`
	Schedules []UIScheduleItem `json:"schedules"`
	Count     int              `json:"count"`
}

UIScheduleListData represents a list of schedules for display. UIScheduleListData 表示用于展示的日程列表。

type UIScheduleSuggestionData

type UIScheduleSuggestionData struct {
	Title       string  `json:"title"`
	Location    string  `json:"location,omitempty"`
	Description string  `json:"description,omitempty"`
	Reason      string  `json:"reason,omitempty"`
	SessionID   string  `json:"session_id,omitempty"`
	StartTs     int64   `json:"start_ts"`
	EndTs       int64   `json:"end_ts"`
	Confidence  float32 `json:"confidence"`
	AllDay      bool    `json:"all_day"`
}

UIScheduleSuggestionData represents a suggested schedule for user confirmation. UIScheduleSuggestionData 表示需要用户确认的建议日程。

type UITimeSlotData

type UITimeSlotData struct {
	Label    string `json:"label"`
	Reason   string `json:"reason"`
	StartTs  int64  `json:"start_ts"`
	EndTs    int64  `json:"end_ts"`
	Duration int    `json:"duration"`
}

UITimeSlotData represents a single time slot option. UITimeSlotData 表示单个时间槽选项。

type UITimeSlotPickerData

type UITimeSlotPickerData struct {
	Reason     string           `json:"reason"`
	SessionID  string           `json:"session_id,omitempty"`
	Slots      []UITimeSlotData `json:"slots"`
	DefaultIdx int              `json:"default_idx"`
}

UITimeSlotPickerData represents time slot options for user selection. UITimeSlotPickerData 表示供用户选择的时间槽选项。

type WorkflowStep

type WorkflowStep string

WorkflowStep represents the current step in the scheduling workflow.

const (
	StepIdle            WorkflowStep = "idle"
	StepParsing         WorkflowStep = "parsing"
	StepConflictCheck   WorkflowStep = "conflict_check"
	StepConflictResolve WorkflowStep = "conflict_resolve"
	StepConfirming      WorkflowStep = "confirming"
	StepCompleted       WorkflowStep = "completed"
)

type WorkingState

type WorkingState struct {
	ProposedSchedule *ScheduleDraft
	LastIntent       string
	LastToolUsed     string
	CurrentStep      WorkflowStep
	Conflicts        []*store.Schedule
}

WorkingState tracks the agent's current understanding and work in progress.

Directories

Path Synopsis
Package tools provides resilient tool execution for AI agents.
Package tools provides resilient tool execution for AI agents.

Jump to

Keyboard shortcuts

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