tools

package
v0.9.1 Latest Latest
Warning

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

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

Documentation

Overview

Package tools defines the tools available to the agent.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ChannelBindingFromContext added in v0.9.1

func ChannelBindingFromContext(ctx context.Context) *memory.ChannelBinding

ChannelBindingFromContext extracts the typed channel binding from the context. Returns nil when unset.

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 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 LoopCompletionTargetFromContext added in v0.9.1

func LoopCompletionTargetFromContext(ctx context.Context) (looppkg.Completion, string, *looppkg.CompletionChannelTarget)

LoopCompletionTargetFromContext derives the most natural detached completion target for the current tool call context. The returned conversation ID always reflects the current live conversation when one is available, even when the preferred detached delivery target is a channel target such as Signal or OWU.

func LoopIDFromContext added in v0.8.4

func LoopIDFromContext(ctx context.Context) string

LoopIDFromContext extracts the calling loop's ID from the context. Returns an empty string if not set (e.g. non-loop API requests).

func NotificationSource added in v0.9.1

func NotificationSource(ctx context.Context) string

NotificationSource builds a source identifier from the request context for notification history logging. Returns a string like "metacognitive", "signal/+15125551234", or "agent".

func RegisterDocumentTools added in v0.9.1

func RegisterDocumentTools(r *Registry, dt *documents.Tools)

RegisterDocumentTools adds indexed document navigation tools to the registry.

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 WithChannelBinding added in v0.9.1

func WithChannelBinding(ctx context.Context, binding *memory.ChannelBinding) context.Context

WithChannelBinding adds a typed channel binding to the context. Nil bindings are ignored.

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 WithLoopID added in v0.8.4

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

WithLoopID adds the calling loop's ID to the context. This allows tool handlers (e.g. delegate executor) to discover which loop invoked them for parent-child relationship tracking.

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 CallbackDispatcher added in v0.9.1

type CallbackDispatcher interface {
	DispatchAction(record *notifications.Record, actionID string)
}

CallbackDispatcher routes notification responses to originating sessions. Implemented by notifications.CallbackDispatcher.

type CapabilityManager added in v0.7.0

type CapabilityManager interface {
	// RequestCapability activates a capability tag for the current Run.
	RequestCapability(ctx context.Context, tag string) error
	// DropCapability deactivates a capability tag for the current Run.
	DropCapability(ctx context.Context, tag string) error
	// ResetCapabilities drops all voluntary tags for the current Run,
	// returning the tags that were removed.
	ResetCapabilities(ctx context.Context) ([]string, error)
	// ActiveTags returns the set of currently active tags for the Run.
	ActiveTags(ctx context.Context) map[string]bool
}

CapabilityManager controls per-Run capability tag activation. Implemented by agent.Loop. All methods operate on the context-scoped capability scope created at the start of each Run().

type CapabilityManifest added in v0.7.0

type CapabilityManifest = toolcatalog.CapabilitySurface

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, protected map[string]bool) []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.

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 ErrUnavailable added in v0.9.1

type ErrUnavailable struct {
	// Tool is the name of the tool that was invoked.
	Tool string
	// Reason is a short human-readable explanation suitable for
	// surfacing to the model or operator (e.g., "signal-cli not
	// connected", "mqtt broker not yet configured").
	Reason string
}

ErrUnavailable is the canonical error returned by a Provider's handler when the tool is declared but its backing runtime is not currently ready to serve invocations. Capability-tag resolution and the model-facing manifest treat declared-but-unavailable tools as present; only invocation fails with this error.

func (ErrUnavailable) Error added in v0.9.1

func (e ErrUnavailable) Error() string

Error implements the error interface with a consistent shape so callers can scan logs for unavailable-tool invocations.

type EscalationDeps added in v0.9.1

type EscalationDeps struct {
	Router     *notifications.NotificationRouter
	Records    *notifications.RecordStore
	Dispatcher *notifications.CallbackDispatcher
	Waiter     *notifications.ResponseWaiter
}

EscalationDeps holds the dependencies for escalation tools.

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 LensStore added in v0.9.1

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

LensStore manages persistent behavioral lenses via opstate. Lenses are global — they apply to all conversations and survive restarts. Use activate_capability for per-conversation tool access.

func NewLensStore added in v0.9.1

func NewLensStore(state *opstate.Store) *LensStore

NewLensStore creates a lens store backed by opstate.

func (*LensStore) ActiveLenses added in v0.9.1

func (s *LensStore) ActiveLenses() ([]string, error)

ActiveLenses returns the currently active lens tags.

func (*LensStore) Add added in v0.9.1

func (s *LensStore) Add(lens string) error

Add activates a lens. Duplicates are ignored.

func (*LensStore) Remove added in v0.9.1

func (s *LensStore) Remove(lens string) error

Remove deactivates a lens.

type LoopDefinitionToolDeps added in v0.9.1

type LoopDefinitionToolDeps struct {
	Registry         *looppkg.DefinitionRegistry
	View             func() *looppkg.DefinitionRegistryView
	PersistSpec      func(looppkg.Spec, time.Time) error
	DeleteSpec       func(string) error
	PersistPolicy    func(string, looppkg.DefinitionPolicy) error
	DeletePolicy     func(string) error
	Reconcile        func(context.Context, string) error
	LaunchDefinition func(context.Context, string, looppkg.Launch) (looppkg.LaunchResult, error)
}

LoopDefinitionToolDeps wires the live loop-definition registry into the tool registry so the model can inspect and mutate the persistent loops-ng definition overlay.

type LoopRuntimeToolDeps added in v0.9.1

type LoopRuntimeToolDeps struct {
	Registry   *looppkg.Registry
	LaunchLoop func(context.Context, looppkg.Launch) (looppkg.LaunchResult, error)
}

LoopRuntimeToolDeps wires the live loop registry and ad hoc launch path into the tool registry so the model can inspect and control currently running loops.

type MessageToolDeps added in v0.9.1

type MessageToolDeps struct {
	Bus *messages.Bus
}

MessageToolDeps wires the shared envelope bus into the tool registry.

type ModelRegistryToolDeps added in v0.9.1

type ModelRegistryToolDeps struct {
	Registry                *models.Registry
	Router                  *routepkg.Router
	SyncRouter              func()
	PersistDeploymentPolicy func(string, models.DeploymentPolicy) error
	DeleteDeploymentPolicy  func(string) error
	PersistResourcePolicy   func(string, models.ResourcePolicy) error
	DeleteResourcePolicy    func(string) error
}

ModelRegistryToolDeps wires the live model-registry and router state into the tool registry so model-facing operator tools can act on the same runtime machinery as the API surface.

type Provider added in v0.9.1

type Provider interface {
	// Name is a stable identifier for logging and deduplication. It
	// does not have to match any tool name; typical values are the
	// owning subsystem ("awareness", "mqtt", "signal").
	Name() string

	// Tools returns the tool declarations this provider contributes.
	// Each returned tool must have a non-nil Handler — providers
	// signal "runtime not ready" by returning [ErrUnavailable] from
	// the handler, not by omitting the tool from this list.
	Tools() []*Tool
}

Provider is the uniform contract for subsystems that contribute tools to the registry. One subsystem owns one Provider (awareness, mqtt, signal, documents, …), and registration flows through Registry.RegisterProvider.

Why Provider exists

Before Provider, every new subsystem landed via a bespoke SetX/ConfigureX method on Registry, wired into some init phase, and sometimes required a deferredTools exemption when its handler bound asynchronously. The pattern worked but proliferated as subsystems grew, and it produced the init-order drift class described in #733.

Provider replaces that pattern with a single method per subsystem. Tool declarations live with the subsystem (in internal/<subsystem>/provider.go), not in internal/tools/, so ownership is obvious and subsystems do not reach into Registry internals.

Async-binding pattern

Tools whose handlers depend on a runtime that starts asynchronously (signal-cli, a WebSocket connection, a slow-initializing client) should *still* be declared at init time. The handler should check readiness internally and return ErrUnavailable until the runtime is ready. This keeps the tool visible to capability-tag resolution from the start, eliminating the "deferredTools" escape hatch that existed pre-#733:

func (p *signalProvider) Tools() []*Tool {
    return []*Tool{{
        Name: "signal_send_message",
        ...
        Handler: func(ctx context.Context, args map[string]any) (string, error) {
            p.mu.RLock(); c := p.client; p.mu.RUnlock()
            if c == nil {
                return "", ErrUnavailable{
                    Tool:   "signal_send_message",
                    Reason: "signal-cli not connected",
                }
            }
            return sendMessage(ctx, c, args)
        },
    }}
}

Migration status

Not every existing subsystem has been migrated yet. New subsystems (iMessage, Calendar, Notes, container orchestration, …) should use Provider from day one. Remaining SetX/ConfigureX migrations are tracked as follow-ups to #733.

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) ConfigureLoopDefinitionTools added in v0.9.1

func (r *Registry) ConfigureLoopDefinitionTools(deps LoopDefinitionToolDeps)

ConfigureLoopDefinitionTools stores the runtime dependencies needed by the loop-definition tool family and registers the tools.

func (*Registry) ConfigureLoopRuntimeTools added in v0.9.1

func (r *Registry) ConfigureLoopRuntimeTools(deps LoopRuntimeToolDeps)

ConfigureLoopRuntimeTools stores the runtime dependencies needed by the live loop tool family and registers the tools.

func (*Registry) ConfigureMessageTools added in v0.9.1

func (r *Registry) ConfigureMessageTools(deps MessageToolDeps)

ConfigureMessageTools registers thin envelope-construction tools over the shared message bus.

func (*Registry) ConfigureModelRegistryTools added in v0.9.1

func (r *Registry) ConfigureModelRegistryTools(deps ModelRegistryToolDeps)

ConfigureModelRegistryTools stores the runtime dependencies needed by the model-registry tool family and registers the tools.

func (*Registry) EnablePlatformTools added in v0.9.1

func (r *Registry) EnablePlatformTools(caller platformCallFunc)

EnablePlatformTools adds native platform-host tools to the registry.

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) MetadataTagIndex added in v0.9.1

func (r *Registry) MetadataTagIndex() map[string][]string

MetadataTagIndex builds a tag-to-tool mapping from per-tool default metadata. Tags with no registered tools are omitted.

func (*Registry) Register

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

Register adds a tool to the registry.

func (*Registry) RegisterProvider added in v0.9.1

func (r *Registry) RegisterProvider(p Provider)

RegisterProvider registers every tool contributed by p through the standard Registry.Register path. Tools with nil handlers are rejected — Provider handlers must be non-nil even when the backing runtime is unavailable (return ErrUnavailable instead).

Registration is idempotent at the tool-name level: re-registering the same name replaces the prior tool. This matches the existing Register semantics; providers should not contribute duplicate names across subsystems.

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) SetAttachmentTools added in v0.8.4

func (r *Registry) SetAttachmentTools(at *attachments.Tools)

SetAttachmentTools adds attachment query and analysis tools to the registry.

func (*Registry) SetCallbackDispatcher added in v0.9.1

func (r *Registry) SetCallbackDispatcher(d CallbackDispatcher)

SetCallbackDispatcher configures callback routing for the resolve_actionable tool.

func (*Registry) SetCapabilityTools added in v0.7.0

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

SetCapabilityTools adds activate_capability, deactivate_capability, reset_capabilities, and list_loaded_capabilities tools to the registry. These tools let the agent inspect and mutate capability tags mid-conversation.

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 activate or deactivate 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) SetEscalationTools added in v0.9.1

func (r *Registry) SetEscalationTools(deps EscalationDeps)

SetEscalationTools registers the request_human_escalation and request_ai_escalation tools. Requires notification routing, record tracking, callback dispatch, and synchronous response waiting.

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) SetLensTools added in v0.9.1

func (r *Registry) SetLensTools(store *LensStore)

SetLensTools registers activate_lens, deactivate_lens, and list_lenses tools. These manage persistent behavioral lenses that apply globally across all conversations. Lenses use the same tag system as capabilities — when a lens is active, KB articles and talents tagged with that lens name are loaded into every conversation.

func (*Registry) SetLogIndexDB added in v0.8.3

func (r *Registry) SetLogIndexDB(db *sql.DB)

SetLogIndexDB adds the logs_query tool to the registry so the agent can query its own structured log index for self-diagnostics. If db is nil (log indexing disabled), the tool is not registered.

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) 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.
	ContentResolveExempt []string                                                       `json:"-"` // Top-level arg keys that must remain literal during content resolution.
	CanonicalID          string                                                         `json:"-"`
	Source               string                                                         `json:"-"`
	Origin               string                                                         `json:"-"`
	DefaultTags          []string                                                       `json:"-"`
}

Tool represents a callable tool.

Jump to

Keyboard shortcuts

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