Documentation
¶
Overview ¶
Package agent implements the core agent loop.
Index ¶
- Constants
- type CapabilityTagStore
- type ChannelProvider
- type Compactor
- type CompositeContextProvider
- type ContactContext
- type ContactLookup
- type ContextProvider
- type FailoverHandler
- type IncompatibleModelError
- type InteractionRef
- type KBMenuHint
- type Loop
- func (l *Loop) ActiveTags(ctx context.Context) map[string]bool
- func (l *Loop) CheckpointSession(conversationID, label string) error
- func (l *Loop) CloseSession(conversationID, reason, carryForward string) error
- func (l *Loop) ConversationTranscript(conversationID string) string
- func (l *Loop) DropCapability(ctx context.Context, tag string) error
- func (l *Loop) GetContextWindow() int
- func (l *Loop) GetHistory(conversationID string) []memory.Message
- func (l *Loop) GetTokenCount(conversationID string) int
- func (l *Loop) HAInject() homeassistant.StateFetcher
- func (l *Loop) LastRunTags() map[string]bool
- func (l *Loop) MemoryStats() map[string]any
- func (l *Loop) Process(ctx context.Context, conversationID, message string) (string, error)
- func (l *Loop) RegisterTagContextProvider(tag string, p TagContextProvider)
- func (l *Loop) RequestCapability(ctx context.Context, tag string) error
- func (l *Loop) ResetCapabilities(ctx context.Context) ([]string, error)
- func (l *Loop) ResetConversation(conversationID string) error
- func (l *Loop) Router() *router.Router
- func (l *Loop) Run(ctx context.Context, req *Request, stream StreamCallback) (resp *Response, err error)
- func (l *Loop) SetArchiver(archiver SessionArchiver)
- func (l *Loop) SetCapabilityTagStore(store CapabilityTagStore)
- func (l *Loop) SetCapabilityTags(capTags map[string]config.CapabilityTagConfig, parsedTalents []talents.Talent)
- func (l *Loop) SetChannelTags(ct map[string][]string)
- func (l *Loop) SetContextProvider(provider ContextProvider)
- func (l *Loop) SetEgoFile(path string)
- func (l *Loop) SetExtractor(e *memory.Extractor)
- func (l *Loop) SetFailoverHandler(handler FailoverHandler)
- func (l *Loop) SetHAInject(fetcher homeassistant.StateFetcher)
- func (l *Loop) SetInjectFiles(paths []string)
- func (l *Loop) SetLensProvider(fn func() []string)
- func (l *Loop) SetOrchestratorTools(names []string)
- func (l *Loop) SetProvenanceStore(store *provenance.Store)
- func (l *Loop) SetRecoveryModel(model string)
- func (l *Loop) SetRequestRecorder(recorder logging.RequestRecordFunc)
- func (l *Loop) SetTagContextAssembler(a *TagContextAssembler)
- func (l *Loop) SetTimezone(tz string)
- func (l *Loop) SetUsageRecorder(store *usage.Store, pricing map[string]config.PricingEntry, ...)
- func (l *Loop) ShutdownArchive(conversationID string)
- func (l *Loop) SplitSession(conversationID string, atIndex int, atMessage string) error
- func (l *Loop) TagContextProviders() map[string]TagContextProvider
- func (l *Loop) Tools() *tools.Registry
- func (l *Loop) ToolsJSON() string
- func (l *Loop) TriggerCompaction(ctx context.Context, conversationID string) error
- func (l *Loop) UseCapabilitySurface(surface []toolcatalog.CapabilitySurface)
- func (l *Loop) UseLiveRequestRecorder(recorder logging.RequestRecordFunc)
- func (l *Loop) UseModelRegistry(registry *models.Registry)
- func (l *Loop) UseModelRuntime(runtime *models.Runtime)
- type MemoryStore
- type Message
- type NoEligibleModelError
- type OpstateCapabilityTagStore
- type RelatedContact
- type Request
- type Response
- type SessionArchiver
- type StreamCallback
- type StreamEvent
- type TagContextAssembler
- type TagContextAssemblerConfig
- type TagContextProvider
- type ToolCallRecorder
- type TrustPolicyView
Constants ¶
const ( KindToken = llm.KindToken KindToolCallStart = llm.KindToolCallStart KindToolCallDone = llm.KindToolCallDone KindDone = llm.KindDone KindLLMResponse = llm.KindLLMResponse KindLLMStart = llm.KindLLMStart )
Stream event kinds re-exported for consumers.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CapabilityTagStore ¶ added in v0.9.1
type CapabilityTagStore interface {
// LoadTags returns the previously activated tags for a conversation.
// Returns nil on missing/empty.
LoadTags(conversationID string) ([]string, error)
// SaveTags persists the active tags for a conversation. Pass nil
// or empty to clear.
SaveTags(conversationID string, tags []string) error
}
CapabilityTagStore persists activated capability tags per conversation. Tags activated via activate_capability are saved at the end of each Run and restored at the start of the next Run for the same conversation.
type ChannelProvider ¶ added in v0.7.0
type ChannelProvider struct {
// contains filtered or unexported fields
}
ChannelProvider is a ContextProvider that injects channel-specific context into the system prompt based on the "source" routing hint attached to the request context. When a ContactLookup is configured, it resolves sender names to contact records and injects a structured JSON contact profile alongside the channel notes.
func NewChannelProvider ¶ added in v0.7.0
func NewChannelProvider(contacts ContactLookup) *ChannelProvider
NewChannelProvider creates a channel awareness context provider. The contacts parameter is optional — pass nil to disable contact resolution (the provider will still emit channel notes).
func (*ChannelProvider) GetContext ¶ added in v0.7.0
GetContext returns a channel context block if the request context carries a "source" hint that matches a known channel. When a contact lookup is available and the sender resolves to a known contact, the block includes a structured JSON contact profile with trust policy, communication channels, and interaction history. Returns an empty string for unrecognized sources or missing hints.
type Compactor ¶
type Compactor interface {
NeedsCompaction(conversationID string) bool
Compact(ctx context.Context, conversationID string) error
// CompactionThreshold returns the token count at which compaction
// triggers.
CompactionThreshold() int
}
Compactor handles conversation compaction.
type CompositeContextProvider ¶
type CompositeContextProvider struct {
// contains filtered or unexported fields
}
CompositeContextProvider combines multiple context providers. Each provider's output is concatenated with newlines.
func NewCompositeContextProvider ¶
func NewCompositeContextProvider(providers ...ContextProvider) *CompositeContextProvider
NewCompositeContextProvider creates a composite from multiple providers.
func (*CompositeContextProvider) Add ¶
func (c *CompositeContextProvider) Add(provider ContextProvider)
Add appends a provider to the composite.
func (*CompositeContextProvider) GetContext ¶
func (c *CompositeContextProvider) GetContext(ctx context.Context, userMessage string) (string, error)
GetContext calls all providers and combines their output.
type ContactContext ¶ added in v0.8.0
type ContactContext struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
TrustZone string `json:"trust_zone"`
TrustPolicy *TrustPolicyView `json:"trust_policy"`
Groups []string `json:"groups,omitempty"`
Org *string `json:"org,omitempty"`
Title *string `json:"title,omitempty"`
Role *string `json:"role,omitempty"`
Summary string `json:"summary,omitempty"`
Related []RelatedContact `json:"related,omitempty"`
Channels map[string]any `json:"channels,omitempty"`
LastInteraction *InteractionRef `json:"last_interaction,omitempty"`
ContactSince string `json:"contact_since,omitempty"`
}
ContactContext holds the rich contact profile injected into the system prompt as structured JSON. Fields are populated by the ContactLookup implementation and gated by the contact's trust zone — lower-trust zones receive fewer fields.
type ContactLookup ¶ added in v0.7.0
type ContactLookup interface {
LookupContact(name string, source string) *ContactContext
}
ContactLookup resolves a contact name to a rich context profile for system prompt injection. The source parameter identifies the channel (e.g., "signal", "email") so the implementation can gate fields by trust zone. Returns nil when no matching contact is found.
type ContextProvider ¶
type ContextProvider interface {
// GetContext returns context to inject into the system prompt.
// The userMessage is provided to enable semantic search for relevant knowledge.
GetContext(ctx context.Context, userMessage string) (string, error)
}
ContextProvider supplies dynamic context for the system prompt.
type FailoverHandler ¶
type FailoverHandler interface {
// OnFailover is called when switching from one model to another due to failure.
// Returns an error if failover should be aborted.
OnFailover(ctx context.Context, fromModel, toModel, reason string) error
}
FailoverHandler is called before model failover to allow checkpointing.
type IncompatibleModelError ¶ added in v0.9.1
IncompatibleModelError reports that an explicit deployment cannot satisfy the request's required capabilities.
func (*IncompatibleModelError) Error ¶ added in v0.9.1
func (e *IncompatibleModelError) Error() string
type InteractionRef ¶ added in v0.8.0
type InteractionRef struct {
AgoSeconds int64 `json:"ago_seconds"`
Channel string `json:"channel,omitempty"`
SessionID string `json:"session_id,omitempty"`
Topics []string `json:"topics,omitempty"`
}
InteractionRef summarizes the contact's most recent interaction for temporal context. AgoSeconds is negative for past interactions.
type KBMenuHint ¶ added in v0.9.1
type KBMenuHint struct {
NextTags []string
}
KBMenuHint captures entry-point metadata that can be surfaced in the capability menu before a tag is activated.
type Loop ¶
type Loop struct {
// contains filtered or unexported fields
}
Loop is the core agent execution loop.
func NewLoop ¶
func NewLoop(logger *slog.Logger, mem MemoryStore, compactor Compactor, rtr *router.Router, ha *homeassistant.Client, sched *scheduler.Scheduler, llmClient llm.Client, defaultModel string, parsedTalents []talents.Talent, persona string, contextWindow int) *Loop
NewLoop creates a new agent loop.
func (*Loop) ActiveTags ¶ added in v0.7.0
ActiveTags returns a snapshot of the currently active capability tags. ActiveTags returns the active tags from the context-scoped capability scope when available, falling back to the most recent Run()'s snapshot. This satisfies the tools.CapabilityManager interface.
func (*Loop) CheckpointSession ¶ added in v0.7.0
CheckpointSession archives a snapshot of the current conversation state without ending the session. The active session continues uninterrupted.
func (*Loop) CloseSession ¶ added in v0.7.0
CloseSession gracefully closes the current session, archives messages, injects a carry-forward handoff into the new session, and starts a fresh session. Unlike ResetConversation, the carry-forward summary provides continuity across the session boundary.
func (*Loop) ConversationTranscript ¶ added in v0.7.1
ConversationTranscript returns a formatted text transcript of the current in-memory conversation for the given ID. System and tool messages are excluded to focus on user/assistant dialogue. Returns an empty string if no user/assistant messages exist after filtering (for example, when there are no messages or only system/tool messages). The output is capped at [maxTranscriptBytes] to keep downstream LLM prompts within reasonable context limits.
func (*Loop) DropCapability ¶ added in v0.7.0
DropCapability deactivates a capability tag for the current Run. Delegates to the context-scoped capabilityScope. Always-active and channel-pinned tags cannot be dropped.
func (*Loop) GetContextWindow ¶
GetContextWindow returns the context window size of the default model.
func (*Loop) GetHistory ¶
GetHistory returns the conversation messages for a given conversation.
func (*Loop) GetTokenCount ¶
func (*Loop) HAInject ¶ added in v0.9.1
func (l *Loop) HAInject() homeassistant.StateFetcher
HAInject returns the HA entity state fetcher used for resolving ha-inject directives in context files. May be nil when HA is not configured.
func (*Loop) LastRunTags ¶ added in v0.9.1
LastRunTags returns a snapshot of the most recent Run()'s active tags. Used by the dashboard callback which has no Run context.
func (*Loop) MemoryStats ¶
MemoryStats returns current memory statistics.
func (*Loop) RegisterTagContextProvider ¶ added in v0.9.1
func (l *Loop) RegisterTagContextProvider(tag string, p TagContextProvider)
RegisterTagContextProvider registers a live context provider for a capability tag. The provider's TagContext method is called during system prompt assembly for each turn where the tag is active. Only one provider per tag is supported; a second registration for the same tag replaces the previous provider.
func (*Loop) RequestCapability ¶ added in v0.7.0
RequestCapability activates a capability tag for the current Run. Delegates to the context-scoped capabilityScope. Both configured tags and ad-hoc tags are accepted.
func (*Loop) ResetCapabilities ¶ added in v0.9.1
ResetCapabilities returns the current Run to baseline capability state by dropping all user-activated tags while preserving always-active, protected, and pinned tags.
func (*Loop) ResetConversation ¶
ResetConversation archives and then clears the conversation history.
func (*Loop) Router ¶ added in v0.6.0
Router returns the model router, or nil if no router is configured.
func (*Loop) Run ¶
func (l *Loop) Run(ctx context.Context, req *Request, stream StreamCallback) (resp *Response, err error)
Run executes one iteration of the agent loop. If stream is non-nil, tokens are pushed to it as they arrive.
func (*Loop) SetArchiver ¶ added in v0.3.0
func (l *Loop) SetArchiver(archiver SessionArchiver)
SetArchiver configures the session archiver for preserving conversations.
func (*Loop) SetCapabilityTagStore ¶ added in v0.9.1
func (l *Loop) SetCapabilityTagStore(store CapabilityTagStore)
SetCapabilityTagStore configures persistent storage for per-conversation capability tags. When set, tags activated via activate_capability are saved at the end of each Run and restored at the start of the next Run for the same conversation.
func (*Loop) SetCapabilityTags ¶ added in v0.7.0
func (l *Loop) SetCapabilityTags(capTags map[string]config.CapabilityTagConfig, parsedTalents []talents.Talent)
SetCapabilityTags configures tag-driven tool and talent filtering. Tags marked always_active are activated immediately. The method also builds the tool registry's tag index and stores parsed talents for per-run filtering. When capTags is nil or empty, capability tagging is disabled and all tools/talents load unconditionally.
func (*Loop) SetChannelTags ¶ added in v0.8.0
SetChannelTags configures channel-pinned tag activation. When a Run() request carries a "source" hint matching a key in channelTags, the listed capability tags are activated for that run in addition to any always-active or agent-requested tags. Channel-pinned tags are ref-counted per concurrent Run() call and cannot be dropped via DropCapability. They are removed on return to prevent cross-channel bleed.
func (*Loop) SetContextProvider ¶
func (l *Loop) SetContextProvider(provider ContextProvider)
SetContextProvider configures a provider for dynamic system prompt context.
func (*Loop) SetEgoFile ¶ added in v0.7.0
SetEgoFile sets the path to ego.md. When set, the file is read fresh on each turn and its content is injected into the system prompt.
func (*Loop) SetExtractor ¶ added in v0.5.0
SetExtractor configures the automatic fact extractor.
func (*Loop) SetFailoverHandler ¶
func (l *Loop) SetFailoverHandler(handler FailoverHandler)
SetFailoverHandler configures a handler to be called before model failover.
func (*Loop) SetHAInject ¶ added in v0.8.0
func (l *Loop) SetHAInject(fetcher homeassistant.StateFetcher)
SetHAInject configures the HA entity state resolver for tag context documents. When set, <!-- ha-inject: ... --> directives in context files are resolved to live entity state on each turn.
func (*Loop) SetInjectFiles ¶ added in v0.7.0
SetInjectFiles sets the file paths whose content is re-read and injected into the system prompt on every turn. Paths should already have tilde expansion applied. Missing or unreadable files are silently skipped at read time.
func (*Loop) SetLensProvider ¶ added in v0.9.1
SetLensProvider configures a function that returns the currently active global lenses. These are merged into every Run's capability scope alongside always-active and channel-pinned tags.
func (*Loop) SetOrchestratorTools ¶ added in v0.7.0
SetOrchestratorTools configures the restricted tool set for all iterations of the agent loop. When set, only the named tools are advertised on every LLM call, keeping the primary model in orchestrator mode and steering it toward delegation. If thane_delegate is not registered in the tool registry, gating is silently disabled to avoid leaving the agent without actionable tools.
func (*Loop) SetProvenanceStore ¶ added in v0.8.4
func (l *Loop) SetProvenanceStore(store *provenance.Store)
SetProvenanceStore sets the provenance store for ego.md. When set, ego.md content is read from the store and delta-relative metadata (last modified time, revision count) is prepended to the system prompt section.
func (*Loop) SetRecoveryModel ¶ added in v0.9.1
SetRecoveryModel configures a fast, cheap model used to generate summaries when the primary model times out after completing tool calls. When empty, timeout recovery falls back to a static message. Only wired in the serve path — CLI one-shot requests don't need timeout recovery because they have no multi-turn tool loops.
func (*Loop) SetRequestRecorder ¶ added in v0.9.1
func (l *Loop) SetRequestRecorder(recorder logging.RequestRecordFunc)
SetRequestRecorder configures request detail recording. When set, completed requests are captured for live inspection and optional persistent retention.
func (*Loop) SetTagContextAssembler ¶ added in v0.9.1
func (l *Loop) SetTagContextAssembler(a *TagContextAssembler)
SetTagContextAssembler configures the shared assembler that builds the Capability Context section of the system prompt from static files, tagged KB articles, and live providers.
func (*Loop) SetTimezone ¶ added in v0.5.0
SetTimezone configures the IANA timezone for the Current Conditions section of the system prompt (e.g., "America/Chicago").
func (*Loop) SetUsageRecorder ¶ added in v0.7.1
func (l *Loop) SetUsageRecorder(store *usage.Store, pricing map[string]config.PricingEntry, cat *models.Catalog)
SetUsageRecorder configures persistent token usage recording. When set, every LLM completion in the agent loop is persisted for cost attribution and analysis.
func (*Loop) ShutdownArchive ¶ added in v0.3.0
ShutdownArchive archives the current conversation state before shutdown.
func (*Loop) SplitSession ¶ added in v0.7.0
SplitSession retroactively splits the current session at a past message boundary. Messages before the split point are archived as a completed session; messages at and after the split point are retained as the current session. Exactly one of atIndex (negative offset from end) or atMessage (substring match) must be non-zero.
func (*Loop) TagContextProviders ¶ added in v0.9.1
func (l *Loop) TagContextProviders() map[string]TagContextProvider
TagContextProviders returns a snapshot of the registered tag context providers. The returned map is safe for concurrent use by callers (e.g., delegate executors) since each value is read-only after registration.
func (*Loop) TriggerCompaction ¶
TriggerCompaction manually triggers conversation compaction.
func (*Loop) UseCapabilitySurface ¶ added in v0.9.1
func (l *Loop) UseCapabilitySurface(surface []toolcatalog.CapabilitySurface)
UseCapabilitySurface stores the resolved capability surface used by shared model-facing renderers such as prompt summaries and capability manifest/help generation.
func (*Loop) UseLiveRequestRecorder ¶ added in v0.9.1
func (l *Loop) UseLiveRequestRecorder(recorder logging.RequestRecordFunc)
UseLiveRequestRecorder configures live request detail recording for in-flight turns. This is typically a lightweight in-memory sink.
func (*Loop) UseModelRegistry ¶ added in v0.9.1
UseModelRegistry configures the live model registry used for explicit model resolution and runtime usage attribution.
func (*Loop) UseModelRuntime ¶ added in v0.9.1
UseModelRuntime configures the live model runtime used for explicit runner preparation flows such as LM Studio context expansion.
type MemoryStore ¶
type MemoryStore interface {
GetMessages(conversationID string) []memory.Message
AddMessage(conversationID, role, content string) error
GetTokenCount(conversationID string) int
Clear(conversationID string) error
Stats() map[string]any
}
MemoryStore is the conversation memory backend required by the agent loop. It manages per-conversation message history and token accounting so the loop can build prompts and enforce context-window limits.
type Message ¶
type Message struct {
Role string `json:"role"` // system, user, assistant
Content string `json:"content"`
Images []llm.ImageContent `json:"-"`
}
Message represents a chat message.
type NoEligibleModelError ¶ added in v0.9.1
NoEligibleModelError reports that automatic routing could not find any deployment capable of satisfying the request.
func (*NoEligibleModelError) Error ¶ added in v0.9.1
func (e *NoEligibleModelError) Error() string
type OpstateCapabilityTagStore ¶ added in v0.9.1
type OpstateCapabilityTagStore struct {
// contains filtered or unexported fields
}
OpstateCapabilityTagStore implements CapabilityTagStore using opstate for persistence. Tags are stored as a JSON array per conversation ID.
func NewOpstateCapabilityTagStore ¶ added in v0.9.1
func NewOpstateCapabilityTagStore(state *opstate.Store) *OpstateCapabilityTagStore
NewOpstateCapabilityTagStore creates a capability tag store backed by opstate.
type RelatedContact ¶ added in v0.8.0
RelatedContact represents a RELATED vCard entry on a contact.
type Request ¶
type Request struct {
Messages []Message `json:"messages"`
Model string `json:"model,omitempty"`
ConversationID string `json:"conversation_id,omitempty"`
ChannelBinding *memory.ChannelBinding `json:"channel_binding,omitempty"`
Hints map[string]string `json:"hints,omitempty"` // Routing hints (channel, mission, etc.)
SkipContext bool `json:"-"` // Skip memory, tools, and context injection (for lightweight completions)
AllowedTools []string `json:"-"` // Optional allowlist of tools visible for this run
ExcludeTools []string `json:"-"` // Tool names to exclude from this run (e.g., lifecycle tools for recurring wakes)
SkipTagFilter bool `json:"-"` // Bypass capability tag filtering (for self-scoping contexts like metacognitive)
InitialTags []string `json:"-"` // Tags to activate at Run start (carried forward from previous loop iterations)
MaxIterations int `json:"-"` // Optional per-request iteration cap (0 = default)
MaxOutputTokens int `json:"-"` // Optional output-token budget across all iterations (0 = unlimited)
ToolTimeout time.Duration `json:"-"` // Optional per-tool timeout (0 = no extra timeout)
UsageRole string `json:"-"` // Optional usage role override (e.g., "delegate")
UsageTaskName string `json:"-"` // Optional usage task name override
FallbackContent string `json:"-"` // Optional static fallback text when the run yields no content
// SystemPrompt, when non-empty, replaces the output of
// buildSystemPrompt(). Used by callers that assemble their own
// prompt context externally.
SystemPrompt string `json:"-"`
}
Request represents an incoming agent request.
type Response ¶
type Response struct {
Content string `json:"content"`
Model string `json:"model"`
FinishReason string `json:"finish_reason"`
InputTokens int `json:"input_tokens,omitempty"`
OutputTokens int `json:"output_tokens,omitempty"`
CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`
ToolsUsed map[string]int `json:"tools_used,omitempty"` // tool name → call count
EffectiveTools []string `json:"effective_tools,omitempty"`
LoadedCapabilities []toolcatalog.LoadedCapabilityEntry `json:"loaded_capabilities,omitempty"`
Iterations int `json:"iterations,omitempty"`
Exhausted bool `json:"exhausted,omitempty"`
// SessionID and RequestID are set by Run() so callers can
// correlate post-run log lines with the agent loop's context.
SessionID string `json:"session_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
// ActiveTags is the set of capability tags active at the end of
// the Run. Used by loops to carry forward activations.
ActiveTags []string `json:"-"`
}
Response is the result of a single agent Run() call. It contains the model's final content, token usage counters, and metadata about which tools and capability tags were active during execution.
type SessionArchiver ¶ added in v0.3.0
type SessionArchiver interface {
// ArchiveConversation archives all messages from a conversation before clearing.
ArchiveConversation(conversationID string, messages []memory.Message, reason string) error
// StartSession begins a new session for a conversation.
StartSession(conversationID string) (sessionID string, err error)
// EndSession ends the current session.
EndSession(sessionID string, reason string) error
// ActiveSessionID returns the current session ID, or empty if none.
ActiveSessionID(conversationID string) string
// EnsureSession starts a session if none is active, returns the session ID.
EnsureSession(conversationID string) string
// ArchiveIterations copies iteration records to the immutable archive.
ArchiveIterations(iterations []memory.ArchivedIteration) error
// LinkPendingIterationToolCalls links archived tool calls to their
// parent iterations using stored tool_call_ids.
LinkPendingIterationToolCalls(sessionID string) error
// OnMessage is called after each message to track session stats.
OnMessage(conversationID string)
// ActiveSessionStartedAt returns when the active session began,
// or the zero time if there is no active session.
ActiveSessionStartedAt(conversationID string) time.Time
}
SessionArchiver handles session lifecycle and message archiving.
type StreamCallback ¶
type StreamCallback = llm.StreamCallback
StreamCallback receives streaming events. Alias to llm.StreamCallback for compatibility.
func BuildProgressStream ¶ added in v0.9.1
func BuildProgressStream(progressFn func(string, map[string]any)) StreamCallback
BuildProgressStream converts a loop progress func into a StreamCallback that forwards in-flight LLM and tool events to the event bus for dashboard visibility. Returns nil if progressFn is nil.
This is the canonical bridge between the agent's streaming events and the loop infrastructure's progress reporting. Handlers that call Loop.Run inside a handler-only loop should use this to wire the loop's loop.ProgressFunc into the agent stream:
stream := agent.BuildProgressStream(loop.ProgressFunc(hCtx)) resp, err := runner.Run(hCtx, req, stream)
type StreamEvent ¶
type StreamEvent = llm.StreamEvent
StreamEvent is a single event in a streaming response. Alias to llm.StreamEvent for use by consumers.
type TagContextAssembler ¶ added in v0.9.1
type TagContextAssembler struct {
// contains filtered or unexported fields
}
TagContextAssembler builds the Capability Context section from two sources for each active tag:
- Tagged KB articles — markdown files with tags: frontmatter in the knowledge base directory (same pattern as talents)
- Live providers — TagContextProvider implementations producing fresh context each turn
Both the main agent loop and delegate executor share a single assembler to avoid duplicating the assembly logic. The assembler is safe for concurrent use after construction.
func NewTagContextAssembler ¶ added in v0.9.1
func NewTagContextAssembler(cfg TagContextAssemblerConfig) *TagContextAssembler
NewTagContextAssembler creates an assembler, scanning the KB directory for tagged articles at construction time. KB scan errors are logged but do not prevent construction.
func (*TagContextAssembler) Build ¶ added in v0.9.1
func (a *TagContextAssembler) Build(ctx context.Context, activeTags map[string]bool, providers map[string]TagContextProvider) string
Build assembles tag context for the given active tags. Providers supply live-computed context and must be passed per-call (typically a snapshot from Loop.TagContextProviders) to avoid data races. The ctx should carry any timeout (e.g., the 2-second HA deadline). Returns empty string when no content is produced.
func (*TagContextAssembler) KBArticleTags ¶ added in v0.9.1
func (a *TagContextAssembler) KBArticleTags() map[string]int
KBArticleTags returns the tag→article count index, useful for enriching the capability manifest with KB article counts.
func (*TagContextAssembler) KBMenuHints ¶ added in v0.9.1
func (a *TagContextAssembler) KBMenuHints() map[string]KBMenuHint
KBMenuHints returns one root-menu hint per tag, sourced from tagged KB entry-point documents. The first teaser encountered for a tag wins, with deterministic ordering provided by scanKBArticles.
type TagContextAssemblerConfig ¶ added in v0.9.1
type TagContextAssemblerConfig struct {
CapTags map[string]config.CapabilityTagConfig
KBDir string // resolved kb: directory; empty skips scanning
HAInject homeassistant.StateFetcher // nil-safe
Logger *slog.Logger
}
TagContextAssemblerConfig holds the construction parameters for a TagContextAssembler.
type TagContextProvider ¶ added in v0.9.1
type TagContextProvider interface {
// TagContext returns context to inject when the associated tag is active.
// The ctx carries the shared HA timeout from prompt assembly.
TagContext(ctx context.Context) (string, error)
}
TagContextProvider supplies live-computed context for a capability tag. Unlike static context files in config.CapabilityTagConfig.Context, providers generate fresh output each turn. Output should follow #458 conventions: delta-annotated timestamps via awareness.FormatDelta, machine-first format, pre-computed relationships.
type ToolCallRecorder ¶
type ToolCallRecorder interface {
RecordToolCall(conversationID, messageID, toolCallID, toolName, arguments string) error
CompleteToolCall(toolCallID, result, errMsg string) error
}
ToolCallRecorder records tool call lifecycle events for observability. When the memory store also implements this interface, the agent loop calls RecordToolCall before execution and CompleteToolCall after, enabling auditing and debugging of tool interactions.
type TrustPolicyView ¶ added in v0.8.0
type TrustPolicyView struct {
FrontierModel bool `json:"frontier_model"`
ProactiveOutreach string `json:"proactive_outreach"`
ToolAccess string `json:"tool_access"`
SendGating string `json:"send_gating"`
}
TrustPolicyView is the JSON-serializable view of a trust zone's capability matrix. It exposes the policy dimensions that the agent needs to adapt its behavior.