agent

package
v0.1.1 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CodebotToolClassifier added in v0.1.0

func CodebotToolClassifier(name string) bool

func SessionMemorySeedFn added in v0.1.1

func SessionMemorySeedFn(cwd string) func() (string, error)

SessionMemorySeedFn returns a closure suitable for plugging into agentcore's SessionMemoryStrategy. The closure reads the project-scoped memory file on each compaction attempt and returns the empty string when the file is missing or still matches the initial template — both of which signal "no useful memory yet, fall through to LLM summarization".

Types

type CompactionKind added in v0.1.0

type CompactionKind string
const (
	CompactionKindMicro CompactionKind = "micro"
	CompactionKindFull  CompactionKind = "full"
	CompactionKindTrim  CompactionKind = "trim"
	CompactionKindPrune CompactionKind = "prune"
)

type CompactionResult added in v0.0.2

type CompactionResult struct {
	Changed        bool
	TokensBefore   int
	TokensAfter    int
	Reason         string
	Strategy       string
	CompactedCount int
	KeptCount      int
	SplitTurn      bool
}

type CompactionSnapshot added in v0.1.0

type CompactionSnapshot struct {
	Kind           CompactionKind
	Strategy       string
	Reason         string
	Changed        bool
	TokensBefore   int
	TokensAfter    int
	CompactedCount int
	KeptCount      int
	SplitTurn      bool
	Timestamp      time.Time
}

type ContextBreakdown added in v0.1.0

type ContextBreakdown struct {
	UserText      int
	AssistantText int
	ToolCalls     int
	ToolResults   int
	Summaries     int
	Images        int
	Total         int
	ContextWindow int

	// TopTools lists the heaviest tools by total (call + result) tokens.
	TopTools []ToolTokenUsage
}

ContextBreakdown reports per-category token distribution in the conversation.

type ContextSuggestion added in v0.1.0

type ContextSuggestion struct {
	Severity string // "warning" or "info"
	Message  string
	Savings  int // estimated token savings, 0 if unknown
}

ContextSuggestion is an actionable recommendation to reduce context usage.

type ErrorSnapshot added in v0.1.0

type ErrorSnapshot struct {
	Kind      apperr.Kind
	Message   string
	Detail    string
	Timestamp time.Time
}

type ModelFactory

type ModelFactory func(prov, model, apiKey, baseURL string) (agentcore.ChatModel, error)

ModelFactory creates a chat model instance for a provider/model tuple.

type ReminderSnapshot added in v0.1.0

type ReminderSnapshot struct {
	Kind      RuntimeReminderKind
	Mode      string
	Timestamp time.Time
}

type RuntimeMetricsSnapshot added in v0.1.0

type RuntimeMetricsSnapshot struct {
	ReminderTotal         int
	ReminderByKind        map[RuntimeReminderKind]int
	CompactionTotal       int
	CompactionChanged     int
	CompactionSaved       int
	CompactionByKind      map[CompactionKind]int
	CompactionSavedByKind map[CompactionKind]int
	ErrorTotal            int
	ErrorByKind           map[apperr.Kind]int
}

type RuntimeReminderKind added in v0.1.0

type RuntimeReminderKind string
const (
	ReminderRepeatToolCall     RuntimeReminderKind = "repeat_tool_call"
	ReminderPostStopValidation RuntimeReminderKind = "post_stop_validation"
	ReminderSkillPaths         RuntimeReminderKind = "skill_paths"
	ReminderTaskManagement     RuntimeReminderKind = "task_management"
)

type Session

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

Session is the business-logic core that wraps Agent + session persistence. It is independent of any UI framework and drives interactive, print, and RPC modes.

func NewSession

func NewSession(cfg SessionConfig) *Session

NewSession creates a Session and wires auto-persist to the agent.

func (*Session) APIKey

func (s *Session) APIKey() string

func (*Session) Abort

func (s *Session) Abort()

func (*Session) AbortSilent

func (s *Session) AbortSilent()

func (*Session) ApplySkillDelta added in v0.1.0

func (s *Session) ApplySkillDelta(name string, delta skill.Delta) error

func (*Session) ApplySkillInvocation added in v0.1.0

func (s *Session) ApplySkillInvocation(result *skill.InvocationResult) error

func (*Session) BaseURL

func (s *Session) BaseURL() string

func (*Session) ClearConversation

func (s *Session) ClearConversation()

func (*Session) Close

func (s *Session) Close()

func (*Session) Compact

func (s *Session) Compact() (CompactionResult, error)

func (*Session) ContextBreakdown added in v0.1.0

func (s *Session) ContextBreakdown() ContextBreakdown

ContextBreakdown computes a per-category token breakdown of the current conversation messages. It does NOT include system prompt or tool definitions.

func (*Session) ContextSnapshot added in v0.1.0

func (s *Session) ContextSnapshot() (*agentcore.ContextSnapshot, bool)

func (*Session) ContextSuggestions added in v0.1.0

func (s *Session) ContextSuggestions() []ContextSuggestion

ContextSuggestions generates actionable suggestions based on context usage and the message breakdown.

func (*Session) ContextUsage

func (s *Session) ContextUsage() *agentcore.ContextUsage

func (*Session) CostEstimate

func (s *Session) CostEstimate() (inputTokens, outputTokens int, cost float64)

func (*Session) CurrentSessionInfo

func (s *Session) CurrentSessionInfo() (storage.SessionInfo, error)

func (*Session) GenerateSuggestion added in v0.0.4

func (s *Session) GenerateSuggestion(ctx context.Context) (string, error)

GenerateSuggestion calls the current model with a condensed conversation history plus a suggestion prompt to predict the user's next input. Returns "" when no suggestion is available (first turn, no model, etc.).

func (*Session) HandleOverflowRewrite added in v0.1.0

func (s *Session) HandleOverflowRewrite(info agentctx.RewriteEvent)

func (*Session) HandleProjectedRewrite added in v0.1.0

func (s *Session) HandleProjectedRewrite(info agentctx.RewriteEvent)

func (*Session) IsRunning

func (s *Session) IsRunning() bool

func (*Session) LastAssistantText

func (s *Session) LastAssistantText() string

func (*Session) LastCompaction added in v0.1.0

func (s *Session) LastCompaction() (CompactionSnapshot, bool)

func (*Session) LastReminder added in v0.1.0

func (s *Session) LastReminder() (ReminderSnapshot, bool)

func (*Session) LastRunSummary added in v0.1.0

func (s *Session) LastRunSummary() (agentcore.RunSummary, bool)

func (*Session) LastTurnOutcome added in v0.1.0

func (s *Session) LastTurnOutcome() TurnOutcomeSnapshot

func (*Session) ListSessions

func (s *Session) ListSessions() ([]storage.SessionInfo, error)

func (*Session) Messages added in v0.0.2

func (s *Session) Messages() []agentcore.AgentMessage

Messages returns the current agent message history.

func (*Session) ModelName

func (s *Session) ModelName() string

func (*Session) OverlayPrompt added in v0.1.1

func (s *Session) OverlayPrompt(key, text string)

OverlayPrompt registers or removes a named instructions overlay. Pass empty text to remove. Overlays are rendered in insertion order.

func (*Session) PostSummaryRecoveryHook added in v0.1.0

func (s *Session) PostSummaryRecoveryHook() agentctx.PostSummaryHook

func (*Session) Prompt

func (s *Session) Prompt(text string) error

func (*Session) PromptWithBlocks

func (s *Session) PromptWithBlocks(blocks []agentcore.ContentBlock) error

func (*Session) Provider

func (s *Session) Provider() string

func (*Session) RecentErrors added in v0.1.0

func (s *Session) RecentErrors(limit int) []ErrorSnapshot

func (*Session) RecentToolCalls added in v0.1.0

func (s *Session) RecentToolCalls(limit int) []ToolCallSnapshot

func (*Session) Registry

func (s *Session) Registry() *provider.ModelRegistry

func (*Session) Reload

func (s *Session) Reload()

func (*Session) ReplaceAllTools

func (s *Session) ReplaceAllTools(tools []agentcore.Tool)

func (*Session) ReplaceMCPTools added in v0.1.0

func (s *Session) ReplaceMCPTools(tools []agentcore.Tool)

func (*Session) Reset added in v0.1.1

func (s *Session) Reset() error

Reset closes the current session log and starts a fresh session in the same cwd. The in-memory conversation and harness state are cleared; the previous file is flushed.

func (*Session) ResetTaskList added in v0.1.0

func (s *Session) ResetTaskList() error

func (*Session) RestoreAllTools

func (s *Session) RestoreAllTools(extra ...agentcore.Tool)

func (*Session) RuntimeMetrics added in v0.1.0

func (s *Session) RuntimeMetrics() RuntimeMetricsSnapshot

func (*Session) SessionID added in v0.0.4

func (s *Session) SessionID() string

func (*Session) SetBeforePrompt

func (s *Session) SetBeforePrompt(fn func())

func (*Session) SetMCPInstructions added in v0.1.0

func (s *Session) SetMCPInstructions(text string)

func (*Session) SetModel

func (s *Session) SetModel(prov, model string) error

func (*Session) SetSkillCatalog added in v0.1.0

func (s *Session) SetSkillCatalog(catalog *skill.Catalog)

func (*Session) SetTaskNotifyFn added in v0.1.0

func (s *Session) SetTaskNotifyFn(fn storage.TaskNotifyFn)

func (*Session) SetThinkingLevel

func (s *Session) SetThinkingLevel(level agentcore.ThinkingLevel)

func (*Session) SetTools

func (s *Session) SetTools(tools ...agentcore.Tool)

func (*Session) Settings

func (s *Session) Settings() config.Resolved

func (*Session) SideQuestion added in v0.0.4

func (s *Session) SideQuestion(ctx context.Context, question string) (string, error)

SideQuestion sends a one-shot question to the current model using the full conversation context but without tool definitions or conversation history mutation. The answer is ephemeral — it never enters the session store. This powers the /btw side-chain Q&A feature.

func (*Session) SkillCatalog added in v0.1.0

func (s *Session) SkillCatalog() *skill.Catalog

func (*Session) Skills

func (s *Session) Skills() []skill.Spec

func (*Session) Steer

func (s *Session) Steer(text string)

func (*Session) Subscribe

func (s *Session) Subscribe(fn func(SessionEvent)) func()

func (*Session) SwitchSession

func (s *Session) SwitchSession(id string) error

func (*Session) TaskSnapshot added in v0.1.0

func (s *Session) TaskSnapshot() storage.TaskSnapshot

func (*Session) ToolsByName

func (s *Session) ToolsByName(names ...string) []agentcore.Tool

func (*Session) TotalTokens

func (s *Session) TotalTokens() int

type SessionConfig

type SessionConfig struct {
	Agent          *agentcore.Agent
	ContextManager agentcore.ContextManager
	Store          *storage.Store
	Manager        *storage.Manager
	Registry       *provider.ModelRegistry
	Settings       config.Resolved
	Cwd            string
	TaskStore      *storage.TaskStore
	// CreateModel allows tests/integrations to override model construction.
	// Defaults to provider.CreateModel when nil.
	CreateModel ModelFactory
	// LazyPersist buffers user messages and flushes them only when
	// an assistant response arrives. Disabled by default for safety.
	LazyPersist bool
	// ChatModel is the active ChatModel reference.
	ChatModel agentcore.ChatModel
	// HookRunner fires lifecycle hooks (notification, etc.). Nil when no hooks configured.
	HookRunner *hooks.Runner

	// Tools is the full set of tools registered with the agent.
	// Used by ToolsByName / RestoreAllTools for plan mode filtering.
	Tools []agentcore.Tool
	// ContextFiles holds loaded context files for dynamic system prompt rebuilding.
	// When tools change the prompt is regenerated from these inputs.
	ContextFiles config.ContextFiles
	// Skills holds loaded skills for system prompt injection and /skill: commands.
	Skills []skill.Spec
	// SkillCatalog provides indexed skill lookup and reload support.
	SkillCatalog *skill.Catalog
	// SkillUsage persists cross-session usage statistics for prompt ordering.
	SkillUsage *skill.UsageTracker
	// DeferredToolsPreamble is injected as the first user message (once).
	DeferredToolsPreamble string
	// Reminders are <system-reminder> fragments prepended to each user message.
	Reminders []string
	// PreambleInjected indicates the preamble was already in conversation history (resume).
	PreambleInjected bool
	// SkillAllowsSetter updates temporary tool allows for the active skill.
	SkillAllowsSetter func([]string)
}

SessionConfig configures a new Session.

type SessionEvent

type SessionEvent struct {
	Type       SessionEventType
	AgentEvent *agentcore.Event

	// Session-level fields (populated based on Type)
	ModelName    string
	Provider     string
	Level        agentcore.ThinkingLevel
	SessionID    string
	Error        error
	Reminder     string
	ReminderKind RuntimeReminderKind

	// Retry fields (populated for SEAutoRetryStart / SEAutoRetryEnd)
	RetryAttempt int
	RetryMax     int
	RetryDelay   time.Duration
	RetrySuccess bool

	// Compaction reason: "overflow" or "threshold"
	CompactionReason   string
	CompactionKind     CompactionKind
	CompactionStrategy string
	CompactionChanged  bool
	TokensBefore       int
	TokensAfter        int
	CompactedCount     int
	KeptCount          int
	SplitTurn          bool
}

SessionEvent extends agent events with session-level metadata. When Type == SEAgentEvent, AgentEvent is non-nil.

type SessionEventType

type SessionEventType string

SessionEventType identifies a session-level event.

const (
	// SEAgentEvent wraps an agentcore.Event transparently.
	SEAgentEvent SessionEventType = "agent_event"

	// Session lifecycle events
	SEAutoCompactionStart SessionEventType = "auto_compaction_start"
	SEAutoCompactionEnd   SessionEventType = "auto_compaction_end"
	SEAutoRetryStart      SessionEventType = "auto_retry_start"
	SEAutoRetryEnd        SessionEventType = "auto_retry_end"
	SEModelChanged        SessionEventType = "model_changed"
	SEThinkingChanged     SessionEventType = "thinking_changed"
	SESessionSwitched     SessionEventType = "session_switched"
	SERuntimeReminder     SessionEventType = "runtime_reminder"
	SEError               SessionEventType = "session_error"
)

type SessionMemory added in v0.1.1

type SessionMemory struct {
	Content   string
	UpdatedAt time.Time
}

SessionMemory is the on-disk shape of a memory file. We write the body as plain markdown (no frontmatter) so the file is readable and editable by a human. UpdatedAt comes from the filesystem mtime, not a stored field.

type ToolCallSnapshot added in v0.1.0

type ToolCallSnapshot struct {
	Tool      string
	ArgsHash  string
	Success   bool
	Timestamp time.Time
}

type ToolTokenUsage added in v0.1.0

type ToolTokenUsage struct {
	Name         string
	CallTokens   int
	ResultTokens int
	Total        int
}

ToolTokenUsage tracks token consumption for a single tool.

type TurnOutcomeSnapshot added in v0.1.0

type TurnOutcomeSnapshot struct {
	AssistantResponded bool
	ReadOnlyToolCalls  int
	WriteLikeToolCalls int
	TaskMutations      int
	CodeEditToolCalls  int
}

Jump to

Keyboard shortcuts

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