agent

package
v0.0.0-...-4bd36a1 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors

NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors

NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors

Index

Constants

View Source
const (
	// DetailLevelFull means log everything
	DetailLevelFull = "full"
	// DetailLevelTruncated means truncate long content
	DetailLevelTruncated = "truncated"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AgentInstance

type AgentInstance struct {
	ID             string
	Name           string
	Model          string
	Fallbacks      []string
	Workspace      string
	MaxIterations  int
	ContextWindow  int
	Provider       providers.LLMProvider
	ProviderMeta   *ProviderMetadata // Provider metadata for logging
	Sessions       *session.SessionManager
	ContextBuilder *ContextBuilder
	Tools          *tools.ToolRegistry
	Subagents      *config.SubagentsConfig
	SkillsFilter   []string
	Candidates     []providers.FallbackCandidate
	PluginMgr      *plugin.Manager
}

AgentInstance represents a fully configured agent with its own workspace, session manager, context builder, and tool registry.

func NewAgentInstance

func NewAgentInstance(
	agentCfg *config.AgentConfig,
	defaults *config.AgentDefaults,
	cfg *config.Config,
	provider providers.LLMProvider,
) *AgentInstance

NewAgentInstance creates an agent instance from config.

type AgentLoop

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

func NewAgentLoop

func NewAgentLoop(cfg *config.Config, msgBus *bus.MessageBus, provider providers.LLMProvider) *AgentLoop

func (*AgentLoop) GetStartupInfo

func (al *AgentLoop) GetStartupInfo() map[string]interface{}

GetStartupInfo returns information about loaded tools and skills for logging.

func (*AgentLoop) ProcessDirect

func (al *AgentLoop) ProcessDirect(ctx context.Context, content, sessionKey string) (string, error)

func (*AgentLoop) ProcessDirectWithChannel

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

func (*AgentLoop) ProcessHeartbeat

func (al *AgentLoop) ProcessHeartbeat(ctx context.Context, content, channel, chatID string) (string, error)

ProcessHeartbeat processes a heartbeat request without session history. Each heartbeat is independent and doesn't accumulate context.

func (*AgentLoop) RecordLastChannel

func (al *AgentLoop) RecordLastChannel(channel string) error

RecordLastChannel records the last active channel for this workspace. This uses the atomic state save mechanism to prevent data loss on crash.

func (*AgentLoop) RecordLastChatID

func (al *AgentLoop) RecordLastChatID(chatID string) error

RecordLastChatID records the last active chat ID for this workspace. This uses the atomic state save mechanism to prevent data loss on crash.

func (*AgentLoop) RegisterTool

func (al *AgentLoop) RegisterTool(tool tools.Tool)

func (*AgentLoop) Run

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

func (*AgentLoop) SetChannelManager

func (al *AgentLoop) SetChannelManager(cm *channels.Manager)

func (*AgentLoop) Stop

func (al *AgentLoop) Stop()

type AgentRegistry

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

AgentRegistry manages multiple agent instances and routes messages to them.

func NewAgentRegistry

func NewAgentRegistry(
	cfg *config.Config,
	provider providers.LLMProvider,
) *AgentRegistry

NewAgentRegistry creates a registry from config, instantiating all agents.

func (*AgentRegistry) CanSpawnSubagent

func (r *AgentRegistry) CanSpawnSubagent(parentAgentID, targetAgentID string) bool

CanSpawnSubagent checks if parentAgentID is allowed to spawn targetAgentID.

func (*AgentRegistry) GetAgent

func (r *AgentRegistry) GetAgent(agentID string) (*AgentInstance, bool)

GetAgent returns the agent instance for a given ID.

func (*AgentRegistry) GetDefaultAgent

func (r *AgentRegistry) GetDefaultAgent() *AgentInstance

GetDefaultAgent returns the default agent instance.

func (*AgentRegistry) ListAgentIDs

func (r *AgentRegistry) ListAgentIDs() []string

ListAgentIDs returns all registered agent IDs.

func (*AgentRegistry) ResolveRoute

func (r *AgentRegistry) ResolveRoute(input routing.RouteInput) routing.ResolvedRoute

ResolveRoute determines which agent handles the message.

type ContextBuilder

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

func NewContextBuilder

func NewContextBuilder(workspace string) *ContextBuilder

func (*ContextBuilder) AddAssistantMessage

func (cb *ContextBuilder) AddAssistantMessage(messages []providers.Message, content string, toolCalls []map[string]interface{}) []providers.Message

func (*ContextBuilder) AddToolResult

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

func (*ContextBuilder) BuildMessages

func (cb *ContextBuilder) BuildMessages(history []providers.Message, summary string, currentMessage string, media []string, channel, chatID string, skipBootstrap bool) []providers.Message

func (*ContextBuilder) BuildSystemPrompt

func (cb *ContextBuilder) BuildSystemPrompt(skipBootstrap bool) string

func (*ContextBuilder) GetSkillsInfo

func (cb *ContextBuilder) GetSkillsInfo() map[string]interface{}

GetSkillsInfo returns information about loaded skills.

func (*ContextBuilder) LoadBootstrapFiles

func (cb *ContextBuilder) LoadBootstrapFiles(skipBootstrap bool) string

func (*ContextBuilder) SetToolsRegistry

func (cb *ContextBuilder) SetToolsRegistry(registry *tools.ToolRegistry)

SetToolsRegistry sets the tools registry for dynamic tool summary generation.

type FallbackAttemptInfo

type FallbackAttemptInfo struct {
	ProviderName string
	ModelName    string
	APIKey       string // Masked
	APIBase      string
	ErrorMessage string
	Duration     time.Duration
}

FallbackAttemptInfo holds information about a single fallback attempt

type FinalResponseInfo

type FinalResponseInfo struct {
	Timestamp     time.Time
	TotalDuration time.Duration
	LLMRounds     int
	Content       string
	Channel       string
	ChatID        string
}

FinalResponseInfo holds information about the final response

type LLMRequestInfo

type LLMRequestInfo struct {
	Round     int
	Timestamp time.Time
	Model     string

	// New fields for comprehensive logging
	ProviderName     string                 // Provider name (e.g., "zhipu", "openai")
	APIKey           string                 // Masked API key
	APIBase          string                 // API base URL
	HTTPHeaders      map[string]string      // HTTP headers (excluding Authorization)
	FullConfig       map[string]interface{} // Complete request configuration
	FallbackAttempts []FallbackAttemptInfo  // All attempted providers in fallback chain

	// Legacy fields kept for backward compatibility
	Messages []providers.Message
	Tools    []providers.ToolDefinition
}

LLMRequestInfo holds information about an LLM request

type LLMResponseInfo

type LLMResponseInfo struct {
	Round        int
	Timestamp    time.Time
	Duration     time.Duration
	Content      string
	ToolCalls    []providers.ToolCall
	Usage        *providers.UsageInfo
	FinishReason string
}

LLMResponseInfo holds information about an LLM response

type LocalOperationInfo

type LocalOperationInfo struct {
	Round      int
	Timestamp  time.Time
	Operations []Operation
}

LocalOperationInfo holds information about local operations

type MemoryStore

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

MemoryStore manages persistent memory for the agent. - Long-term memory: memory/MEMORY.md - Daily notes: memory/YYYYMM/YYYYMMDD.md

func NewMemoryStore

func NewMemoryStore(workspace string) *MemoryStore

NewMemoryStore creates a new MemoryStore with the given workspace path. It ensures the memory directory exists.

func (*MemoryStore) AppendToday

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

AppendToday appends content to today's daily note. If the file doesn't exist, it creates a new file with a date header.

func (*MemoryStore) GetMemoryContext

func (ms *MemoryStore) GetMemoryContext() string

GetMemoryContext returns formatted memory context for the agent prompt. Includes long-term memory and recent daily notes.

func (*MemoryStore) GetRecentDailyNotes

func (ms *MemoryStore) GetRecentDailyNotes(days int) string

GetRecentDailyNotes returns daily notes from the last N days. Contents are joined with "---" separator.

func (*MemoryStore) ReadLongTerm

func (ms *MemoryStore) ReadLongTerm() string

ReadLongTerm reads the long-term memory (MEMORY.md). Returns empty string if the file doesn't exist.

func (*MemoryStore) ReadToday

func (ms *MemoryStore) ReadToday() string

ReadToday reads today's daily note. Returns empty string if the file doesn't exist.

func (*MemoryStore) WriteLongTerm

func (ms *MemoryStore) WriteLongTerm(content string) error

WriteLongTerm writes content to the long-term memory file (MEMORY.md).

type Operation

type Operation struct {
	Type      string // "tool_call", "file_write", "file_read", etc.
	Name      string
	Arguments map[string]interface{}
	Result    interface{}
	Status    string // "Success" or "Failed"
	Error     string
	Duration  time.Duration
}

Operation represents a single local operation

type ProviderMetadata

type ProviderMetadata struct {
	Name    string // Provider name (e.g., "zhipu", "openai")
	APIKey  string // Masked API key
	APIBase string // API base URL
}

ProviderMetadata holds provider configuration metadata for logging

type RequestLogger

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

RequestLogger handles logging of LLM requests and responses

func NewRequestLogger

func NewRequestLogger(cfg *config.LoggingConfig, workspace string) *RequestLogger

NewRequestLogger creates a new request logger

func (*RequestLogger) Close

func (rl *RequestLogger) Close()

Close closes the request logger

func (*RequestLogger) CreateSession

func (rl *RequestLogger) CreateSession() error

CreateSession creates a new logging session directory

func (*RequestLogger) IsEnabled

func (rl *RequestLogger) IsEnabled() bool

IsEnabled returns whether the logger is enabled

func (*RequestLogger) LogFinalResponse

func (rl *RequestLogger) LogFinalResponse(info FinalResponseInfo) error

LogFinalResponse logs the final response to the user

func (*RequestLogger) LogLLMRequest

func (rl *RequestLogger) LogLLMRequest(info LLMRequestInfo) error

LogLLMRequest logs an LLM request

func (*RequestLogger) LogLLMResponse

func (rl *RequestLogger) LogLLMResponse(info LLMResponseInfo) error

LogLLMResponse logs an LLM response

func (*RequestLogger) LogLocalOperations

func (rl *RequestLogger) LogLocalOperations(info LocalOperationInfo) error

LogLocalOperations logs local operations for a round

func (*RequestLogger) LogUserRequest

func (rl *RequestLogger) LogUserRequest(info UserRequestInfo) error

LogUserRequest logs the initial user request

func (*RequestLogger) NextIndex

func (rl *RequestLogger) NextIndex() string

NextIndex returns the next file index

type UserRequestInfo

type UserRequestInfo struct {
	Timestamp time.Time
	Channel   string
	SenderID  string
	ChatID    string
	Content   string
}

UserRequestInfo holds information about the user's request

Jump to

Keyboard shortcuts

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