tools

package
v0.8.1 Latest Latest
Warning

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

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

Documentation

Overview

Package tools provides the tool registry and execution framework.

This file defines sentinel error types for tool execution.

Package tools provides file operation tools for the agent.

Package tools provides shell execution capabilities for the agent.

Package tools defines the tools available to the agent.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConversationIDFromContext added in v0.4.0

func ConversationIDFromContext(ctx context.Context) string

ConversationIDFromContext extracts the conversation ID from the context. Returns "default" if not set.

func FormatEntityState added in v0.7.0

func FormatEntityState(state *homeassistant.State) string

FormatEntityState formats a Home Assistant entity state for LLM consumption. Used by get_state, control_device post-action verification, and anticipation wake context injection.

func HintsFromContext added in v0.7.0

func HintsFromContext(ctx context.Context) map[string]string

HintsFromContext extracts routing hints from the context. Returns nil if no hints were set.

func IterationIndexFromContext added in v0.8.0

func IterationIndexFromContext(ctx context.Context) (int, bool)

IterationIndexFromContext extracts the loop iteration index from the context. Returns -1 and false if not set.

func SessionIDFromContext added in v0.8.0

func SessionIDFromContext(ctx context.Context) string

SessionIDFromContext extracts the archive session ID from the context. Returns an empty string if not set.

func ToolCallIDFromContext added in v0.8.0

func ToolCallIDFromContext(ctx context.Context) string

ToolCallIDFromContext extracts the tool call ID from the context. Returns an empty string if not set.

func WithConversationID added in v0.4.0

func WithConversationID(ctx context.Context, id string) context.Context

WithConversationID adds the conversation ID to the context.

func WithHints added in v0.7.0

func WithHints(ctx context.Context, hints map[string]string) context.Context

WithHints adds routing hints to the context. Nil hints are ignored (the original context is returned unchanged).

func WithIterationIndex added in v0.8.0

func WithIterationIndex(ctx context.Context, idx int) context.Context

WithIterationIndex adds the current loop iteration index to the context.

func WithSessionID added in v0.8.0

func WithSessionID(ctx context.Context, id string) context.Context

WithSessionID adds the archive session ID to the context. This allows downstream code (e.g. delegate executor) to discover its parent session.

func WithToolCallID added in v0.8.0

func WithToolCallID(ctx context.Context, id string) context.Context

WithToolCallID adds the tool call ID to the context. This allows downstream code (e.g. delegate executor) to discover which tool call triggered it.

Types

type CapabilityManager added in v0.7.0

type CapabilityManager interface {
	// RequestCapability activates a capability tag for the session.
	RequestCapability(tag string) error
	// DropCapability deactivates a capability tag for the session.
	DropCapability(tag string) error
	// ActiveTags returns the set of currently active tags.
	ActiveTags() map[string]bool
}

CapabilityManager controls per-session capability tag activation. Implemented by agent.Loop.

type CapabilityManifest added in v0.7.0

type CapabilityManifest struct {
	Tag          string
	Description  string
	Tools        []string
	Context      []string // resolved context file paths
	AlwaysActive bool
}

CapabilityManifest describes a capability tag for the manifest.

func BuildCapabilityManifest added in v0.7.0

func BuildCapabilityManifest(tags map[string][]string, descriptions map[string]string, alwaysActive map[string]bool, contextFiles map[string][]string) []CapabilityManifest

BuildCapabilityManifest creates a sorted list of capability descriptions from the config map. This is used both for the tool description and for generating the capability manifest talent. The contextFiles parameter maps tag names to resolved context file paths (may be nil).

type ContentResolver added in v0.8.0

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

ContentResolver resolves bare prefix references (temp:LABEL, kb:file.md, etc.) in tool argument values to file content. It is nil-safe: calling methods on a nil *ContentResolver is a no-op.

func NewContentResolver added in v0.8.0

func NewContentResolver(pr *paths.Resolver, tfs *TempFileStore, logger *slog.Logger) *ContentResolver

NewContentResolver creates a ContentResolver backed by the given path resolver and temp file store. The path resolver may be nil — resolution for path-based prefixes is silently skipped. If the temp file store is nil, any temp: references will return an error (they are always intentional). Returns nil if both dependencies are nil (no resolution possible).

func (*ContentResolver) ResolveArgs added in v0.8.0

func (cr *ContentResolver) ResolveArgs(ctx context.Context, args map[string]any) error

ResolveArgs recursively walks all values in args and replaces bare prefix references with file content. A "bare" reference is one where the entire string value is the prefix reference — no surrounding whitespace or text. Nested maps and arrays are traversed.

For temp: references, resolution failures are always treated as errors — these are intentional and a missing label (or unconfigured store) likely indicates a typo, stale reference, or misconfiguration. For path prefixes (kb:, scratchpad:, etc.), missing files pass through silently since a nonexistent file is valid state.

The method modifies args in place.

type ConversationResetter added in v0.4.0

type ConversationResetter interface {
	ResetConversation(conversationID string) error
}

ConversationResetter is the interface for resetting conversations. Implemented by agent.Loop.

type EntityMatch

type EntityMatch struct {
	EntityID     string
	FriendlyName string
	Score        float64
}

EntityMatch represents a fuzzy match result.

type ErrToolUnavailable added in v0.8.0

type ErrToolUnavailable struct {
	ToolName string
}

ErrToolUnavailable is returned when a tool call targets a tool that is not present in the effective registry. This indicates a capability mismatch (filtered by tags, excluded by request, or nonexistent), not a transient execution failure. Callers should break the iteration loop rather than retrying.

func (*ErrToolUnavailable) Error added in v0.8.0

func (e *ErrToolUnavailable) Error() string

Error implements the error interface.

type ExecResult

type ExecResult struct {
	Stdout   string `json:"stdout"`
	Stderr   string `json:"stderr"`
	ExitCode int    `json:"exitCode"`
	TimedOut bool   `json:"timedOut,omitempty"`
	Error    string `json:"error,omitempty"`
}

ExecResult contains the result of a command execution.

type FileTools

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

FileTools provides file read/write/edit capabilities within a workspace.

func NewFileTools

func NewFileTools(workspacePath string, readOnlyDirs []string) *FileTools

NewFileTools creates a new FileTools instance. If workspacePath is empty, file tools will be disabled.

func (*FileTools) Edit

func (ft *FileTools) Edit(ctx context.Context, path, oldText, newText string) error

Edit performs a surgical text replacement in a file.

func (*FileTools) Enabled

func (ft *FileTools) Enabled() bool

Enabled reports whether file tools are available.

func (*FileTools) Grep added in v0.5.1

func (ft *FileTools) Grep(ctx context.Context, dir, pattern string, maxDepth int, caseInsensitive bool) (string, error)

Grep searches file contents for a regular expression pattern. Results are formatted as path:line_number:matching_line.

func (*FileTools) List

func (ft *FileTools) List(ctx context.Context, path string) ([]string, error)

List lists files in a directory.

func (*FileTools) Read

func (ft *FileTools) Read(ctx context.Context, path string, offset, limit int) (string, error)

Read reads the contents of a file.

func (*FileTools) Search added in v0.5.1

func (ft *FileTools) Search(ctx context.Context, dir, pattern string, maxDepth int) (string, error)

Search finds files matching a glob pattern within a directory tree. Results are returned as workspace-relative paths, one per line.

func (*FileTools) SetResolver added in v0.8.0

func (ft *FileTools) SetResolver(r *paths.Resolver)

SetResolver configures the shared path prefix resolver for directory-based prefixes (kb:, scratchpad:, etc.). When set, prefixed paths are expanded to their configured directories before sandbox checks.

func (*FileTools) Stat added in v0.5.1

func (ft *FileTools) Stat(ctx context.Context, paths string) (string, error)

Stat returns detailed information about one or more files or directories. Paths should be comma-separated. Each path is resolved through the workspace sandbox.

func (*FileTools) Tree added in v0.5.1

func (ft *FileTools) Tree(ctx context.Context, dir string, maxDepth int) (string, error)

Tree renders a directory tree with indentation. The output includes a summary of total directories and files.

func (*FileTools) WorkspacePath

func (ft *FileTools) WorkspacePath() string

WorkspacePath returns the configured workspace path.

func (*FileTools) Write

func (ft *FileTools) Write(ctx context.Context, path, content string) error

Write writes content to a file, creating directories as needed.

type FindEntityArgs

type FindEntityArgs struct {
	Description string `json:"description"`      // e.g., "access point LED", "ceiling fan"
	Area        string `json:"area,omitempty"`   // e.g., "office", "Nugget's Office"
	Domain      string `json:"domain,omitempty"` // e.g., "light", "switch", "fan"
}

FindEntityArgs represents the arguments for the find_entity tool.

type FindEntityResult

type FindEntityResult struct {
	Found        bool     `json:"found"`
	EntityID     string   `json:"entity_id,omitempty"`
	FriendlyName string   `json:"friendly_name,omitempty"`
	AreaName     string   `json:"area_name,omitempty"`
	Confidence   float64  `json:"confidence,omitempty"`
	Error        string   `json:"error,omitempty"`
	Candidates   []string `json:"candidates,omitempty"` // When ambiguous or not found
}

FindEntityResult represents the result of entity discovery.

type Registry

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

Registry holds available tools.

func NewEmptyRegistry added in v0.5.0

func NewEmptyRegistry() *Registry

NewEmptyRegistry creates an empty tool registry with no built-in tools. Use this for testing or when constructing a registry manually.

func NewRegistry

func NewRegistry(ha *homeassistant.Client, sched *scheduler.Scheduler) *Registry

NewRegistry creates a tool registry with HA integration.

func (*Registry) AllToolNames added in v0.5.0

func (r *Registry) AllToolNames() []string

AllToolNames returns the names of all registered tools.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, name string, argsJSON string) (string, error)

Execute runs a tool by name with given arguments.

func (*Registry) FilterByTags added in v0.7.0

func (r *Registry) FilterByTags(tags []string) *Registry

FilterByTags creates a new Registry containing only the tools that belong to at least one of the given tags, plus any tools marked as AlwaysAvailable. If tags is empty or the tag index is nil, returns a copy of the full registry.

func (*Registry) FilteredCopy added in v0.5.0

func (r *Registry) FilteredCopy(names []string) *Registry

FilteredCopy creates a new Registry containing only the named tools. Tools not found in the source are silently skipped. The returned registry shares tool handlers with the source but has its own map.

func (*Registry) FilteredCopyExcluding added in v0.5.0

func (r *Registry) FilteredCopyExcluding(exclude []string) *Registry

FilteredCopyExcluding creates a new Registry containing all tools except those in the exclude list.

func (*Registry) Get

func (r *Registry) Get(name string) *Tool

Get retrieves a tool by name.

func (*Registry) List

func (r *Registry) List() []map[string]any

List returns all tools for the LLM.

func (*Registry) Register

func (r *Registry) Register(t *Tool)

Register adds a tool to the registry.

func (*Registry) SetAnticipationTools

func (r *Registry) SetAnticipationTools(at *scheduler.AnticipationTools)

SetAnticipationTools adds anticipation management tools to the registry.

func (*Registry) SetArchiveStore added in v0.3.0

func (r *Registry) SetArchiveStore(store *memory.ArchiveStore)

SetArchiveStore adds conversation archive tools to the registry.

func (*Registry) SetCapabilityTools added in v0.7.0

func (r *Registry) SetCapabilityTools(mgr CapabilityManager, manifest []CapabilityManifest)

SetCapabilityTools adds request_capability and drop_capability tools to the registry. These tools let the agent dynamically activate or deactivate capability tags mid-session.

These tools are intentionally not assigned to any tag group. They live in the base registry and survive all tag filtering, ensuring the agent can always request or shed capabilities regardless of which tags are currently active.

func (*Registry) SetContactTools added in v0.7.0

func (r *Registry) SetContactTools(ct *contacts.Tools)

SetContactTools adds contact management tools to the registry.

func (*Registry) SetContentResolver added in v0.8.0

func (r *Registry) SetContentResolver(cr *ContentResolver)

SetContentResolver configures universal prefix-to-content resolution for tool arguments. When set, string arguments matching a registered prefix (temp:, kb:, scratchpad:, etc.) are replaced with file content before the handler runs. Tools with SkipContentResolve=true are exempt.

func (*Registry) SetConversationResetter added in v0.4.0

func (r *Registry) SetConversationResetter(resetter ConversationResetter)

SetConversationResetter adds conversation management tools to the registry.

func (*Registry) SetEmailTools added in v0.7.0

func (r *Registry) SetEmailTools(et *email.Tools)

SetEmailTools adds email tools to the registry.

func (*Registry) SetFactTools

func (r *Registry) SetFactTools(ft *knowledge.Tools)

SetFactTools adds fact management tools to the registry.

func (*Registry) SetFetcher added in v0.2.3

func (r *Registry) SetFetcher(f *search.Fetcher)

SetFetcher adds the web_fetch tool to the registry.

func (*Registry) SetFileTools

func (r *Registry) SetFileTools(ft *FileTools)

SetFileTools adds file operation tools to the registry.

func (*Registry) SetForgeTools added in v0.7.1

func (r *Registry) SetForgeTools(ft forgeHandler)

SetForgeTools adds code forge tools to the registry. The handler must implement all forge tool operations — in practice this is *forge.Tools.

func (*Registry) SetHANotifier added in v0.8.0

func (r *Registry) SetHANotifier(s *notifications.Sender)

SetHANotifier adds the ha_notify tool to the registry.

func (*Registry) SetMediaAnalysisTools added in v0.8.0

func (r *Registry) SetMediaAnalysisTools(at *media.AnalysisTools)

SetMediaAnalysisTools adds the media analysis persistence tool to the registry. The tool lets the agent save structured analysis to an Obsidian-compatible vault and track engagement.

func (*Registry) SetMediaClient added in v0.7.1

func (r *Registry) SetMediaClient(c *media.Client)

SetMediaClient adds the media_transcript tool to the registry.

func (*Registry) SetMediaFeedTools added in v0.8.0

func (r *Registry) SetMediaFeedTools(ft *media.FeedTools)

SetMediaFeedTools adds RSS/Atom feed management tools to the registry.

func (*Registry) SetNotificationRecords added in v0.8.0

func (r *Registry) SetNotificationRecords(rs *notifications.RecordStore)

SetNotificationRecords configures the notification record store used by the ha_notify tool to track actionable notifications.

func (*Registry) SetNotificationRouter added in v0.8.0

func (r *Registry) SetNotificationRouter(router *notifications.NotificationRouter)

SetNotificationRouter adds the provider-agnostic send_notification and request_human_decision tools to the registry.

func (*Registry) SetSearchManager added in v0.2.3

func (r *Registry) SetSearchManager(mgr *search.Manager)

SetSearchManager adds the web_search tool to the registry.

func (*Registry) SetSessionManager added in v0.7.0

func (r *Registry) SetSessionManager(mgr SessionManager)

SetSessionManager adds granular session management tools to the registry.

func (*Registry) SetShellExec

func (r *Registry) SetShellExec(se *ShellExec)

SetShellExec adds shell execution tools to the registry.

func (*Registry) SetTagIndex added in v0.7.0

func (r *Registry) SetTagIndex(tags map[string][]string)

SetTagIndex builds the tag-to-tool mapping from config. Each tag name maps to a list of tool names. Tools not found in the registry are silently skipped (they may not be registered yet or the MCP server may be down).

func (*Registry) SetTempFileStore added in v0.7.1

func (r *Registry) SetTempFileStore(tfs *TempFileStore)

SetTempFileStore adds the create_temp_file tool to the registry and stores the reference for label expansion and cleanup.

func (*Registry) SetUsageStore added in v0.7.1

func (r *Registry) SetUsageStore(store *usage.Store)

SetUsageStore adds the cost_summary tool to the registry so the agent can query its own token usage and API costs.

func (*Registry) SetWatchlistStore added in v0.7.0

func (r *Registry) SetWatchlistStore(store *awareness.WatchlistStore)

SetWatchlistStore adds the add_context_entity and remove_context_entity tools to the registry.

func (*Registry) SetWorkingMemoryStore added in v0.5.0

func (r *Registry) SetWorkingMemoryStore(store *memory.WorkingMemoryStore)

SetWorkingMemoryStore adds the session_working_memory tool to the registry. This tool allows the agent to read and write free-form experiential notes for the current conversation, capturing texture that mechanical compaction destroys.

func (*Registry) TaggedToolNames added in v0.7.0

func (r *Registry) TaggedToolNames(tag string) []string

TaggedToolNames returns the tool names belonging to a tag. Returns nil for unknown tags.

func (*Registry) TempFileStore added in v0.7.1

func (r *Registry) TempFileStore() *TempFileStore

TempFileStore returns the temp file store, or nil if not configured. Used by the delegate executor for label expansion and by the agent loop for cleanup.

type SessionManager added in v0.7.0

type SessionManager interface {
	// CloseSession gracefully closes the current session, archives messages,
	// injects a carry-forward handoff into the new session, and starts fresh.
	CloseSession(conversationID, reason, carryForward string) error
	// CheckpointSession snapshots current conversation state without ending
	// the session. A safety net against crashes or compaction losing state.
	CheckpointSession(conversationID, label string) error
	// SplitSession retroactively splits the current session at a past message
	// boundary. Everything before the split point is archived; everything
	// after becomes the current session. Exactly one of atIndex or atMessage
	// must be provided (atIndex is a negative offset from the end).
	SplitSession(conversationID string, atIndex int, atMessage string) error
}

SessionManager provides granular session lifecycle control beyond the nuclear conversation_reset. Implemented by agent.Loop.

type ShellExec

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

ShellExec provides command execution capabilities.

func NewShellExec

func NewShellExec(cfg ShellExecConfig) *ShellExec

NewShellExec creates a new shell executor.

func (*ShellExec) Enabled

func (s *ShellExec) Enabled() bool

Enabled reports whether shell execution is available.

func (*ShellExec) Exec

func (s *ShellExec) Exec(ctx context.Context, command string, timeoutSec int) (*ExecResult, error)

Exec executes a shell command.

type ShellExecConfig

type ShellExecConfig struct {
	Enabled        bool
	WorkingDir     string
	AllowedCmds    []string
	DeniedCmds     []string
	DefaultTimeout time.Duration
	MaxOutputBytes int
}

ShellExecConfig configures the shell executor.

func DefaultShellExecConfig

func DefaultShellExecConfig() ShellExecConfig

DefaultShellExecConfig returns safe defaults.

type TempFileStore added in v0.7.1

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

TempFileStore manages temporary files created for orchestrator-delegate data passing. Files are written to a workspace subdirectory and tracked via opstate so labels can be expanded to paths and cleaned up when the conversation ends.

func NewTempFileStore added in v0.7.1

func NewTempFileStore(baseDir string, state *opstate.Store, logger *slog.Logger) *TempFileStore

NewTempFileStore creates a TempFileStore rooted at baseDir. The directory is created on first write, not at construction time.

func (*TempFileStore) Cleanup added in v0.7.1

func (s *TempFileStore) Cleanup(convID string) error

Cleanup removes all temp files and opstate entries for a conversation. Errors on individual file removals are logged but do not prevent cleanup of remaining files.

func (*TempFileStore) Create added in v0.7.1

func (s *TempFileStore) Create(ctx context.Context, convID, label, content string) (string, error)

Create writes content to a temp file and maps the label to its path. The returned string is the label itself (not the path). If a label already exists for this conversation, the old file is removed and the mapping updated.

func (*TempFileStore) ExpandLabels added in v0.7.1

func (s *TempFileStore) ExpandLabels(convID, text string) string

ExpandLabels replaces all occurrences of "temp:LABEL" in text with the corresponding file path for the given conversation. Unknown labels are left as-is.

func (*TempFileStore) Resolve added in v0.7.1

func (s *TempFileStore) Resolve(convID, label string) string

Resolve returns the filesystem path for a label in the given conversation. Returns empty string if the label does not exist.

type Tool

type Tool struct {
	Name               string                                                         `json:"name"`
	Description        string                                                         `json:"description"`
	Parameters         map[string]any                                                 `json:"parameters"`
	Handler            func(ctx context.Context, args map[string]any) (string, error) `json:"-"`
	AlwaysAvailable    bool                                                           `json:"-"` // Survives capability tag filtering.
	SkipContentResolve bool                                                           `json:"-"` // Exempt from prefix-to-content resolution.
}

Tool represents a callable tool.

Jump to

Keyboard shortcuts

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