tools

package
v0.0.82 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 43 Imported by: 0

Documentation

Overview

Package tools provides a permission-aware local tool system for term-llm.

Index

Constants

View Source
const (
	ReadFileToolName       = "read_file"
	WriteFileToolName      = "write_file"
	EditFileToolName       = "edit_file"
	UnifiedDiffToolName    = "unified_diff"
	ShellToolName          = "shell"
	GrepToolName           = "grep"
	GlobToolName           = "glob"
	ViewImageToolName      = "view_image"
	ShowImageToolName      = "show_image"
	ImageGenerateToolName  = "image_generate"
	AskUserToolName        = "ask_user"
	SpawnAgentToolName     = "spawn_agent"
	RunAgentScriptToolName = "run_agent_script"
)

Tool specification names

View Source
const ActivateSkillToolName = "activate_skill"

ActivateSkillToolName is the tool spec name.

Variables

View Source
var (
	OnApprovalStart func() // Called before showing prompt (pause TUI)
	OnApprovalEnd   func() // Called after prompt answered (resume TUI)
)

ApprovalUIHooks allows the TUI to coordinate with approval prompts. Set these callbacks before running the ask command to pause/resume the UI.

View Source
var (
	OnAskUserStart func() // Called before showing ask_user UI (pause TUI)
	OnAskUserEnd   func() // Called after ask_user UI answered (resume TUI)

	// AskUserUIFunc allows custom UI rendering for ask_user prompts.
	// When set, this function is called instead of RunAskUser.
	// This is used for inline rendering in alt screen mode.
	AskUserUIFunc func(questions []AskUserQuestion) ([]AskUserAnswer, error)
)

AskUserUIHooks allows the TUI to coordinate with ask_user tool prompts.

View Source
var MutatorKinds = []ToolKind{KindEdit, KindExecute}

MutatorKinds are tool kinds that can modify the filesystem.

Functions

func AllToolNames

func AllToolNames() []string

AllToolNames returns all standard tool spec names that can be registered directly. Note: activate_skill is excluded as it requires a skills registry and is registered separately.

func ClearApprovalHooks

func ClearApprovalHooks()

ClearApprovalHooks removes the approval hooks.

func ClearAskUserHooks added in v0.0.30

func ClearAskUserHooks()

ClearAskUserHooks removes the ask_user hooks.

func ClearAskUserUIFunc added in v0.0.50

func ClearAskUserUIFunc()

ClearAskUserUIFunc removes the custom ask_user UI function.

func CreateTUIHooks added in v0.0.35

func CreateTUIHooks(prog *tea.Program, flushAndWait func()) (start, end func())

CreateTUIHooks creates start/end hook functions for TUI coordination. flushAndWait is called to flush content before releasing terminal. prog is the tea.Program to release/restore.

func ExtractCommandPrefix

func ExtractCommandPrefix(cmd string) string

ExtractCommandPrefix extracts a shell command prefix for policy learning.

func FindBestMatch added in v0.0.52

func FindBestMatch(lines []string, searchText string) int

FindBestMatch finds the line index that best matches the given text. Returns -1 if no reasonable match is found.

func GenerateDiff

func GenerateDiff(oldContent, newContent, filePath string) string

GenerateDiff creates a unified diff between old and new content.

func GenerateShellPattern added in v0.0.35

func GenerateShellPattern(command string) string

GenerateShellPattern creates a glob pattern from a command. For example: "go test ./..." -> "go test *"

func GetAndClearAskUserResult added in v0.0.37

func GetAndClearAskUserResult() string

GetAndClearAskUserResult retrieves and clears the last ask_user summary. Returns empty string if no result was stored.

func GetGitRepoID added in v0.0.35

func GetGitRepoID(root string) string

GetGitRepoID returns a unique identifier for a git repository. The ID is a SHA256 hash of the absolute root path, suitable for use as a filename.

func GetRelativePath added in v0.0.35

func GetRelativePath(path, repoRoot string) string

GetRelativePath returns the path relative to the repo root, or the original path if not in repo.

func IsPathInRepo added in v0.0.35

func IsPathInRepo(path, repoRoot string) bool

IsPathInRepo checks if the given path is under the specified repository root.

func ParseToolsFlag

func ParseToolsFlag(value string) []string

ParseToolsFlag parses a comma-separated list of tool names. Special values: "all" or "*" expand to all available tools.

func SetApprovalHooks

func SetApprovalHooks(onStart, onEnd func())

SetApprovalHooks sets callbacks for TUI coordination during approval prompts.

func SetAskUserHooks added in v0.0.30

func SetAskUserHooks(onStart, onEnd func())

SetAskUserHooks sets callbacks for TUI coordination during ask_user prompts.

func SetAskUserUIFunc added in v0.0.50

func SetAskUserUIFunc(fn func(questions []AskUserQuestion) ([]AskUserAnswer, error))

SetAskUserUIFunc sets the function to call for ask_user prompts. When set, this replaces the default RunAskUser with custom rendering.

func SetLastAskUserResult added in v0.0.37

func SetLastAskUserResult(summary string)

SetLastAskUserResult stores the summary from the last ask_user execution. This should be called by the ask_user UI before signaling completion.

func ValidToolName

func ValidToolName(name string) bool

ValidToolName checks if a name is a valid tool spec name.

Types

type ActivateSkillArgs added in v0.0.37

type ActivateSkillArgs struct {
	Name   string `json:"name"`
	Prompt string `json:"prompt,omitempty"`
}

ActivateSkillArgs are the arguments for the activate_skill tool.

type ActivateSkillTool added in v0.0.37

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

ActivateSkillTool implements the activate_skill tool.

func NewActivateSkillTool added in v0.0.37

func NewActivateSkillTool(registry *skills.Registry, approval *ApprovalManager) *ActivateSkillTool

NewActivateSkillTool creates a new activate_skill tool.

func (*ActivateSkillTool) Execute added in v0.0.37

Execute runs the activate_skill tool.

func (*ActivateSkillTool) Preview added in v0.0.37

func (t *ActivateSkillTool) Preview(args json.RawMessage) string

Preview returns a short description of the tool call.

func (*ActivateSkillTool) SetOnActivated added in v0.0.37

func (t *ActivateSkillTool) SetOnActivated(cb SkillActivatedCallback)

SetOnActivated sets a callback that's called when a skill is activated. If the skill has allowed-tools, the callback receives the list for enforcement.

func (*ActivateSkillTool) Spec added in v0.0.37

func (t *ActivateSkillTool) Spec() llm.ToolSpec

Spec returns the tool specification.

type ApprovalCache

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

ApprovalCache provides session-scoped caching for tool+path decisions.

func NewApprovalCache

func NewApprovalCache() *ApprovalCache

NewApprovalCache creates a new ApprovalCache.

func (*ApprovalCache) Clear

func (c *ApprovalCache) Clear()

Clear removes all cached approvals.

func (*ApprovalCache) Get

func (c *ApprovalCache) Get(toolName, path string) (ConfirmOutcome, bool)

Get retrieves a cached approval decision.

func (*ApprovalCache) GetForDirectory

func (c *ApprovalCache) GetForDirectory(toolName, dir string) (ConfirmOutcome, bool)

GetForDirectory checks if there's an approval for a directory.

func (*ApprovalCache) Set

func (c *ApprovalCache) Set(toolName, path string, outcome ConfirmOutcome)

Set stores an approval decision.

func (*ApprovalCache) SetForDirectory

func (c *ApprovalCache) SetForDirectory(toolName, dir string, outcome ConfirmOutcome)

SetForDirectory stores an approval for all paths under a directory. This is used when user approves "always" for a directory.

type ApprovalChoice added in v0.0.35

type ApprovalChoice int

ApprovalChoice represents a user's approval selection.

const (
	ApprovalChoiceDeny      ApprovalChoice = iota // Deny the request
	ApprovalChoiceOnce                            // Allow once, no memory
	ApprovalChoiceFile                            // Allow this file only (session)
	ApprovalChoiceDirectory                       // Allow this directory (session)
	ApprovalChoiceRepoRead                        // Allow read for entire repo (remembered)
	ApprovalChoiceRepoWrite                       // Allow write for entire repo (remembered)
	ApprovalChoicePattern                         // Allow shell pattern in repo (remembered)
	ApprovalChoiceCommand                         // Allow this specific command (session)
	ApprovalChoiceCancelled                       // User cancelled with esc/ctrl+c
)

type ApprovalManager

type ApprovalManager struct {

	// YoloMode when true, auto-approves all tool executions without prompting.
	// Intended for CI/container environments where interactive approval isn't possible.
	YoloMode bool

	// Callback for prompting user (set by TUI or CLI)
	// Legacy callback - will be replaced by PromptUIFunc
	PromptFunc func(req *ApprovalRequest) (ConfirmOutcome, string)

	// New UI callback for improved approval prompts
	// Takes path/command, isWrite (for files), and returns ApprovalResult
	// If nil, falls back to PromptFunc
	PromptUIFunc func(path string, isWrite bool, isShell bool) (ApprovalResult, error)
	// contains filtered or unexported fields
}

ApprovalManager coordinates approval requests and caching.

func NewApprovalManager

func NewApprovalManager(perms *ToolPermissions) *ApprovalManager

NewApprovalManager creates a new ApprovalManager.

func (*ApprovalManager) ApproveDirectory

func (m *ApprovalManager) ApproveDirectory(toolName, dir string, outcome ConfirmOutcome)

ApproveDirectory adds a directory approval to the session cache.

func (*ApprovalManager) ApprovePath

func (m *ApprovalManager) ApprovePath(toolName, path string, outcome ConfirmOutcome)

ApprovePath adds a path/directory approval to the session cache.

func (*ApprovalManager) ApproveShellPattern

func (m *ApprovalManager) ApproveShellPattern(pattern string)

ApproveShellPattern adds a pattern to the session cache.

func (*ApprovalManager) CheckPathApproval

func (m *ApprovalManager) CheckPathApproval(toolName, path, toolInfo string, isWrite bool) (ConfirmOutcome, error)

CheckPathApproval checks if a path is approved for the given tool. Approvals are directory-scoped and tool-agnostic - approving a directory for one tool allows all tools to access files within it. toolInfo is optional context for display (e.g., filename being accessed).

func (*ApprovalManager) CheckShellApproval

func (m *ApprovalManager) CheckShellApproval(command string) (ConfirmOutcome, error)

CheckShellApproval checks if a shell command is approved.

func (*ApprovalManager) PromptLock added in v0.0.44

func (m *ApprovalManager) PromptLock() *sync.Mutex

PromptLock returns the mutex used to serialize prompts. When a parent is set, returns the parent's lock to ensure all sub-agents share the same serialization.

func (*ApprovalManager) SetParent added in v0.0.44

func (m *ApprovalManager) SetParent(parent *ApprovalManager) error

SetParent sets the parent ApprovalManager for inheritance. When set, this manager will check parent's session caches (dirCache, shellCache) and use parent's PromptUIFunc if local is nil. Also shares the parent's promptMu to serialize prompts across all sub-agents. Returns an error if setting parent would create a cycle.

func (*ApprovalManager) SetYoloMode added in v0.0.35

func (m *ApprovalManager) SetYoloMode(enabled bool)

SetYoloMode enables or disables yolo mode and prints a warning when enabled. Yolo mode auto-approves all tool executions without prompting.

type ApprovalModel added in v0.0.50

type ApprovalModel struct {
	Done bool // Prompt completed
	// contains filtered or unexported fields
}

ApprovalModel is the bubbletea model for approval prompts. It can be embedded in a parent TUI for inline rendering.

func NewEmbeddedApprovalModel added in v0.0.50

func NewEmbeddedApprovalModel(path string, isWrite bool, width int) *ApprovalModel

NewEmbeddedApprovalModel creates an approval model for file access that can be embedded in a parent TUI.

func NewEmbeddedShellApprovalModel added in v0.0.50

func NewEmbeddedShellApprovalModel(command string, width int) *ApprovalModel

NewEmbeddedShellApprovalModel creates an approval model for shell commands that can be embedded in a parent TUI.

func (*ApprovalModel) Init added in v0.0.50

func (m *ApprovalModel) Init() tea.Cmd

func (*ApprovalModel) IsDone added in v0.0.50

func (m *ApprovalModel) IsDone() bool

IsDone returns true if the user has made a selection.

func (*ApprovalModel) RenderSummary added in v0.0.50

func (m *ApprovalModel) RenderSummary() string

RenderSummary returns a summary of the user's choice for display after the UI closes.

func (*ApprovalModel) Result added in v0.0.50

func (m *ApprovalModel) Result() ApprovalResult

Result returns the user's selection after the prompt is done.

func (*ApprovalModel) SetWidth added in v0.0.50

func (m *ApprovalModel) SetWidth(width int)

SetWidth updates the width for rendering.

func (*ApprovalModel) Update added in v0.0.50

func (m *ApprovalModel) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update handles messages for standalone tea.Program use (calls tea.Quit on completion).

func (*ApprovalModel) UpdateEmbedded added in v0.0.50

func (m *ApprovalModel) UpdateEmbedded(msg tea.Msg) bool

UpdateEmbedded handles messages for embedded use (does not call tea.Quit). Returns true if the model finished (user made a selection or cancelled).

func (*ApprovalModel) View added in v0.0.50

func (m *ApprovalModel) View() string

type ApprovalOption added in v0.0.35

type ApprovalOption struct {
	Label       string         // Display text
	Description string         // Explanation text
	Choice      ApprovalChoice // The choice this option represents
	Path        string         // Path for directory/file choices
	Pattern     string         // Pattern for shell choices
	SaveToRepo  bool           // Whether this saves to project
}

ApprovalOption represents a single option in the approval UI.

type ApprovalRequest

type ApprovalRequest struct {
	ToolName    string
	Path        string   // For file tools
	Command     string   // For shell tool
	Description string   // Human-readable description
	Options     []string // Directory options for file tools
	ToolInfo    string   // Preview info for display (filename, URL, etc.)

	// Callbacks
	OnApprove func(choice string, saveToConfig bool) // choice is dir path or pattern
	OnDeny    func()
}

ApprovalRequest represents a pending approval request.

type ApprovalResult added in v0.0.35

type ApprovalResult struct {
	Choice     ApprovalChoice
	Path       string // Selected path (for file/directory)
	Pattern    string // Selected pattern (for shell)
	SaveToRepo bool   // Whether to save to project approvals
	Cancelled  bool   // Whether user cancelled
}

ApprovalResult contains the result of an approval prompt.

func RunFileApprovalUI added in v0.0.35

func RunFileApprovalUI(path string, isWrite bool) (ApprovalResult, error)

RunFileApprovalUI displays the approval UI for file access and returns the result.

func RunShellApprovalUI added in v0.0.35

func RunShellApprovalUI(command string) (ApprovalResult, error)

RunShellApprovalUI displays the approval UI for shell commands and returns the result.

type AskUserAnswer added in v0.0.30

type AskUserAnswer struct {
	QuestionIndex int      `json:"question_index"`
	Header        string   `json:"header"`
	Selected      string   `json:"selected"`
	SelectedList  []string `json:"selected_list,omitempty"`
	IsCustom      bool     `json:"is_custom"`
	IsMultiSelect bool     `json:"is_multi_select,omitempty"`
}

AskUserAnswer represents the user's answer to a question.

func RunAskUser added in v0.0.30

func RunAskUser(questions []AskUserQuestion) ([]AskUserAnswer, error)

RunAskUser presents the questions to the user and returns their answers.

type AskUserArgs added in v0.0.30

type AskUserArgs struct {
	Questions []AskUserQuestion `json:"questions"`
}

AskUserArgs are the arguments passed to the ask_user tool.

type AskUserModel added in v0.0.50

type AskUserModel struct {
	Done      bool
	Cancelled bool
	// contains filtered or unexported fields
}

AskUserModel is the bubbletea model for the ask_user UI. It can be embedded in a parent TUI for inline rendering.

func NewEmbeddedAskUserModel added in v0.0.50

func NewEmbeddedAskUserModel(questions []AskUserQuestion, width int) *AskUserModel

NewEmbeddedAskUserModel creates an ask_user model for embedding in a parent TUI.

func (*AskUserModel) Answers added in v0.0.50

func (m *AskUserModel) Answers() []AskUserAnswer

Answers returns the collected answers after the user completes the dialog.

func (*AskUserModel) Init added in v0.0.50

func (m *AskUserModel) Init() tea.Cmd

func (*AskUserModel) IsCancelled added in v0.0.50

func (m *AskUserModel) IsCancelled() bool

IsCancelled returns true if the user cancelled the dialog.

func (*AskUserModel) IsDone added in v0.0.50

func (m *AskUserModel) IsDone() bool

IsDone returns true if the user has completed all questions.

func (*AskUserModel) RenderPlainSummary added in v0.0.50

func (m *AskUserModel) RenderPlainSummary() string

RenderPlainSummary returns a plain text summary (styling applied at display time).

func (*AskUserModel) RenderSummary added in v0.0.50

func (m *AskUserModel) RenderSummary() string

RenderSummary returns a styled summary of the user's choices.

func (*AskUserModel) SetWidth added in v0.0.50

func (m *AskUserModel) SetWidth(width int)

SetWidth updates the width for rendering.

func (*AskUserModel) Update added in v0.0.50

func (m *AskUserModel) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update handles messages for standalone tea.Program use (calls tea.Quit on completion).

func (*AskUserModel) UpdateEmbedded added in v0.0.50

func (m *AskUserModel) UpdateEmbedded(msg tea.Msg) tea.Cmd

UpdateEmbedded handles messages for embedded use (does not call tea.Quit). Returns a tea.Cmd if one is needed (e.g., for text input blinking).

func (*AskUserModel) View added in v0.0.50

func (m *AskUserModel) View() string

type AskUserOption added in v0.0.30

type AskUserOption struct {
	Label       string `json:"label"`
	Description string `json:"description"`
}

AskUserOption represents a choice for a question.

type AskUserQuestion added in v0.0.30

type AskUserQuestion struct {
	Header      string          `json:"header"`
	Question    string          `json:"question"`
	Options     []AskUserOption `json:"options"`
	MultiSelect bool            `json:"multi_select"`
}

AskUserQuestion represents a question to present to the user.

type AskUserResult added in v0.0.30

type AskUserResult struct {
	Answers []AskUserAnswer `json:"answers,omitempty"`
	Error   string          `json:"error,omitempty"`
	Type    string          `json:"type,omitempty"`
}

AskUserResult is the complete result returned by the tool.

type AskUserTool added in v0.0.30

type AskUserTool struct{}

AskUserTool implements the ask_user tool.

func NewAskUserTool added in v0.0.30

func NewAskUserTool() *AskUserTool

NewAskUserTool creates a new ask_user tool.

func (*AskUserTool) Execute added in v0.0.30

func (t *AskUserTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

Execute runs the ask_user tool.

func (*AskUserTool) Preview added in v0.0.30

func (t *AskUserTool) Preview(args json.RawMessage) string

Preview returns a short description of the tool call.

func (*AskUserTool) Spec added in v0.0.30

func (t *AskUserTool) Spec() llm.ToolSpec

Spec returns the tool specification.

type Attachment

type Attachment struct {
	Path     string `json:"path"`
	MimeType string `json:"mime_type,omitempty"`
	Data     []byte `json:"data,omitempty"`
}

Attachment represents a file attachment in tool results.

type ConfirmOutcome

type ConfirmOutcome string

ConfirmOutcome represents the result of a user confirmation prompt.

const (
	ProceedOnce          ConfirmOutcome = "once"        // Single approval
	ProceedAlways        ConfirmOutcome = "always"      // Session-scoped approval
	ProceedAlwaysAndSave ConfirmOutcome = "always_save" // Persist to config
	Cancel               ConfirmOutcome = "cancel"      // User denied
)

func HuhApprovalPrompt

func HuhApprovalPrompt(req *ApprovalRequest) (ConfirmOutcome, string)

HuhApprovalPrompt prompts the user for approval using a huh form. This provides a nicer UI than the TTY-based prompt.

func TTYApprovalPrompt

func TTYApprovalPrompt(req *ApprovalRequest) (ConfirmOutcome, string)

TTYApprovalPrompt prompts the user for directory access approval via /dev/tty. This allows prompting even when stdin is piped.

type DirCache

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

DirCache provides tool-agnostic directory approval caching. When a directory is approved, all tools can access files within it.

func NewDirCache

func NewDirCache() *DirCache

NewDirCache creates a new DirCache.

func (*DirCache) Get

func (c *DirCache) Get(dir string) (ConfirmOutcome, bool)

Get checks if a directory is approved.

func (*DirCache) IsPathInApprovedDir

func (c *DirCache) IsPathInApprovedDir(path string) bool

IsPathInApprovedDir checks if a path is within any approved directory.

func (*DirCache) Set

func (c *DirCache) Set(dir string, outcome ConfirmOutcome)

Set stores a directory approval.

type EditFileArgs

type EditFileArgs struct {
	FilePath string `json:"file_path"`
	// Mode 1: Delegated edit (natural language)
	Instructions string `json:"instructions,omitempty"`
	LineRange    string `json:"line_range,omitempty"` // e.g., "10-20"
	// Mode 2: Direct edit (deterministic)
	OldText string `json:"old_text,omitempty"`
	NewText string `json:"new_text,omitempty"`
}

EditFileArgs supports two modes: - Mode 1 (Delegated): instructions + optional line_range - Mode 2 (Direct): old_text + new_text

type EditFileTool

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

EditFileTool implements the edit_file tool with dual modes.

func NewEditFileTool

func NewEditFileTool(approval *ApprovalManager) *EditFileTool

NewEditFileTool creates a new EditFileTool.

func (*EditFileTool) Execute

func (t *EditFileTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*EditFileTool) Preview

func (t *EditFileTool) Preview(args json.RawMessage) string

func (*EditFileTool) Spec

func (t *EditFileTool) Spec() llm.ToolSpec

type FileEntry

type FileEntry struct {
	FilePath  string    `json:"file_path"`
	IsDir     bool      `json:"is_dir"`
	SizeBytes int64     `json:"size_bytes"`
	ModTime   time.Time `json:"mod_time"`
}

FileEntry represents a file in glob results.

type GitRepoInfo added in v0.0.35

type GitRepoInfo struct {
	IsRepo   bool   // Whether the path is inside a git repository
	Root     string // Absolute path to the repository root
	RepoName string // Basename of the repository (for display)
}

GitRepoInfo contains information about a git repository.

func DetectGitRepo added in v0.0.35

func DetectGitRepo(path string) GitRepoInfo

DetectGitRepo detects if the given path is inside a git repository. Returns GitRepoInfo with IsRepo=false if not in a repo or if git is unavailable. The path can be a file or directory.

type GlobArgs

type GlobArgs struct {
	Pattern string `json:"pattern"`
	Path    string `json:"path,omitempty"`
}

GlobArgs are the arguments for glob.

type GlobTool

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

GlobTool implements the glob tool.

func NewGlobTool

func NewGlobTool(approval *ApprovalManager) *GlobTool

NewGlobTool creates a new GlobTool.

func (*GlobTool) Execute

func (t *GlobTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*GlobTool) Preview

func (t *GlobTool) Preview(args json.RawMessage) string

func (*GlobTool) Spec

func (t *GlobTool) Spec() llm.ToolSpec

type GrepArgs

type GrepArgs struct {
	Pattern    string `json:"pattern"`
	Path       string `json:"path,omitempty"`
	Include    string `json:"include,omitempty"` // glob filter e.g., "*.go"
	MaxResults int    `json:"max_results,omitempty"`
}

GrepArgs are the arguments for grep.

type GrepMatch

type GrepMatch struct {
	FilePath   string `json:"file_path"`
	LineNumber int    `json:"line_number"`
	Match      string `json:"match"`
	Context    string `json:"context,omitempty"` // 3 lines of context
}

GrepMatch represents a single grep match.

type GrepTool

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

GrepTool implements the grep tool.

func NewGrepTool

func NewGrepTool(approval *ApprovalManager, limits OutputLimits) *GrepTool

NewGrepTool creates a new GrepTool.

func (*GrepTool) Execute

func (t *GrepTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*GrepTool) Preview

func (t *GrepTool) Preview(args json.RawMessage) string

func (*GrepTool) Spec

func (t *GrepTool) Spec() llm.ToolSpec

type ImageGenerateArgs

type ImageGenerateArgs struct {
	Prompt          string   `json:"prompt"`
	InputImage      string   `json:"input_image,omitempty"`       // Single path for editing/variation (backward compat)
	InputImages     []string `json:"input_images,omitempty"`      // Multiple paths for multi-image editing
	AspectRatio     string   `json:"aspect_ratio,omitempty"`      // e.g., "16:9", "4:3"
	OutputPath      string   `json:"output_path,omitempty"`       // Save location
	ShowImage       *bool    `json:"show_image,omitempty"`        // Display via icat (default: true)
	CopyToClipboard *bool    `json:"copy_to_clipboard,omitempty"` // Copy to clipboard (default: true)
}

ImageGenerateArgs are the arguments for image_generate.

type ImageGenerateTool

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

ImageGenerateTool implements the image_generate tool.

func NewImageGenerateTool

func NewImageGenerateTool(approval *ApprovalManager, cfg *config.Config, providerOverride string) *ImageGenerateTool

NewImageGenerateTool creates a new ImageGenerateTool.

func (*ImageGenerateTool) Execute

func (*ImageGenerateTool) Preview

func (t *ImageGenerateTool) Preview(args json.RawMessage) string

func (*ImageGenerateTool) Spec

func (t *ImageGenerateTool) Spec() llm.ToolSpec

type LocalToolRegistry

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

LocalToolRegistry manages local tools and their registration with the engine.

func NewLocalToolRegistry

func NewLocalToolRegistry(toolConfig *ToolConfig, appConfig *config.Config, approvalMgr *ApprovalManager) (*LocalToolRegistry, error)

NewLocalToolRegistry creates a new registry from configuration. The approvalMgr parameter is used for interactive permission prompts.

func (*LocalToolRegistry) AddReadDir

func (r *LocalToolRegistry) AddReadDir(dir string) error

AddReadDir adds a directory to the read allowlist at runtime.

func (*LocalToolRegistry) AddShellPattern

func (r *LocalToolRegistry) AddShellPattern(pattern string) error

AddShellPattern adds a shell pattern to the allowlist at runtime.

func (*LocalToolRegistry) AddWriteDir

func (r *LocalToolRegistry) AddWriteDir(dir string) error

AddWriteDir adds a directory to the write allowlist at runtime.

func (*LocalToolRegistry) Get

func (r *LocalToolRegistry) Get(specName string) (llm.Tool, bool)

Get returns a tool by spec name.

func (*LocalToolRegistry) GetOutputTool added in v0.0.37

func (r *LocalToolRegistry) GetOutputTool(name string) *SetOutputTool

GetOutputTool returns the output tool by name if it exists and is a SetOutputTool.

func (*LocalToolRegistry) GetSkillTool added in v0.0.37

func (r *LocalToolRegistry) GetSkillTool() *ActivateSkillTool

GetSkillTool returns the activate_skill tool if registered.

func (*LocalToolRegistry) GetSpawnAgentTool added in v0.0.35

func (r *LocalToolRegistry) GetSpawnAgentTool() *SpawnAgentTool

GetSpawnAgentTool returns the spawn_agent tool if enabled.

func (*LocalToolRegistry) GetSpecs

func (r *LocalToolRegistry) GetSpecs() []llm.ToolSpec

GetSpecs returns tool specs for all enabled tools.

func (*LocalToolRegistry) IsEnabled

func (r *LocalToolRegistry) IsEnabled(specName string) bool

IsEnabled checks if a tool is enabled.

func (*LocalToolRegistry) Permissions

func (r *LocalToolRegistry) Permissions() *ToolPermissions

Permissions returns the underlying permissions manager.

func (*LocalToolRegistry) RegisterOutputTool added in v0.0.37

func (r *LocalToolRegistry) RegisterOutputTool(name, param, desc string) *SetOutputTool

RegisterOutputTool creates and registers a SetOutputTool with the given configuration. Returns the tool so the caller can retrieve the captured value later.

func (*LocalToolRegistry) RegisterSkillTool added in v0.0.37

func (r *LocalToolRegistry) RegisterSkillTool(skillRegistry *skills.Registry) *ActivateSkillTool

RegisterSkillTool registers the activate_skill tool with the given registry. This must be called after the skills registry is created.

func (*LocalToolRegistry) RegisterWithEngine

func (r *LocalToolRegistry) RegisterWithEngine(engine *llm.Engine)

RegisterWithEngine registers all enabled tools with the LLM engine.

func (*LocalToolRegistry) SetLimits

func (r *LocalToolRegistry) SetLimits(limits OutputLimits)

SetLimits updates the output limits.

type OutputLimits

type OutputLimits struct {
	MaxLines       int   // Max lines for read_file (default 2000)
	MaxBytes       int64 // Max bytes per tool output (default 50KB)
	MaxResults     int   // Max results for grep/glob (default 100/200)
	CumulativeSoft int64 // Soft cumulative limit per turn (default 100KB)
	CumulativeHard int64 // Hard cumulative limit per turn (default 200KB)
}

OutputLimits defines limits for tool output.

func DefaultOutputLimits

func DefaultOutputLimits() OutputLimits

DefaultOutputLimits returns the default output limits.

type ProjectApprovals added in v0.0.35

type ProjectApprovals struct {
	RepoRoot      string    `yaml:"repo_root"`
	RepoName      string    `yaml:"repo_name"`
	UpdatedAt     time.Time `yaml:"updated_at"`
	ReadApproved  bool      `yaml:"read_approved"`  // Whole repo read access
	WriteApproved bool      `yaml:"write_approved"` // Whole repo write access
	ApprovedPaths []string  `yaml:"approved_paths"` // Individual approved paths (relative to repo)
	ShellPatterns []string  `yaml:"shell_patterns"` // Approved shell command patterns
	// contains filtered or unexported fields
}

ProjectApprovals stores per-project approval decisions. Approvals are persisted to ~/.config/term-llm/projects/<repo-hash>.yaml

func LoadProjectApprovals added in v0.0.35

func LoadProjectApprovals(repoRoot string) (*ProjectApprovals, error)

LoadProjectApprovals loads or creates approval data for a git repository. Returns nil if the repo root is empty or invalid.

func (*ProjectApprovals) ApprovePath added in v0.0.35

func (p *ProjectApprovals) ApprovePath(path string) error

ApprovePath adds a specific path to the approved list. Path should be absolute; it will be stored relative to the repo root.

func (*ProjectApprovals) ApproveRead added in v0.0.35

func (p *ProjectApprovals) ApproveRead() error

ApproveRead approves read access for the entire repo.

func (*ProjectApprovals) ApproveShellPattern added in v0.0.35

func (p *ProjectApprovals) ApproveShellPattern(pattern string) error

ApproveShellPattern adds a shell command pattern to the approved list.

func (*ProjectApprovals) ApproveWrite added in v0.0.35

func (p *ProjectApprovals) ApproveWrite() error

ApproveWrite approves write access for the entire repo.

func (*ProjectApprovals) IsPathApproved added in v0.0.35

func (p *ProjectApprovals) IsPathApproved(path string, isWrite bool) bool

IsPathApproved checks if a specific path is approved. Path should be absolute; it will be checked against repo root and approved paths.

func (*ProjectApprovals) IsReadApproved added in v0.0.35

func (p *ProjectApprovals) IsReadApproved() bool

IsReadApproved checks if read access is approved for the entire repo.

func (*ProjectApprovals) IsShellPatternApproved added in v0.0.35

func (p *ProjectApprovals) IsShellPatternApproved(command string) bool

IsShellPatternApproved checks if a command matches any approved shell pattern.

func (*ProjectApprovals) IsWriteApproved added in v0.0.35

func (p *ProjectApprovals) IsWriteApproved() bool

IsWriteApproved checks if write access is approved for the entire repo.

func (*ProjectApprovals) Save added in v0.0.35

func (p *ProjectApprovals) Save() error

Save persists the approval data to disk.

type ReadFileArgs

type ReadFileArgs struct {
	FilePath  string `json:"file_path"`
	StartLine int    `json:"start_line,omitempty"`
	EndLine   int    `json:"end_line,omitempty"`
}

ReadFileArgs are the arguments for read_file.

type ReadFileTool

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

ReadFileTool implements the read_file tool.

func NewReadFileTool

func NewReadFileTool(approval *ApprovalManager, limits OutputLimits) *ReadFileTool

NewReadFileTool creates a new ReadFileTool.

func (*ReadFileTool) Execute

func (t *ReadFileTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*ReadFileTool) Preview

func (t *ReadFileTool) Preview(args json.RawMessage) string

func (*ReadFileTool) Spec

func (t *ReadFileTool) Spec() llm.ToolSpec

type RunAgentScriptArgs added in v0.0.74

type RunAgentScriptArgs struct {
	Script         string `json:"script"`
	Args           string `json:"args,omitempty"`
	TimeoutSeconds int    `json:"timeout_seconds,omitempty"`
}

RunAgentScriptArgs are the arguments for the run_agent_script tool.

type RunAgentScriptTool added in v0.0.74

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

RunAgentScriptTool executes scripts bundled in the agent's source directory. Scripts are resolved by filename only (no paths), and execution is implicitly trusted — no approval prompts are required.

func NewRunAgentScriptTool added in v0.0.74

func NewRunAgentScriptTool(config *ToolConfig, limits OutputLimits) *RunAgentScriptTool

NewRunAgentScriptTool creates a new RunAgentScriptTool.

func (*RunAgentScriptTool) Execute added in v0.0.74

func (*RunAgentScriptTool) Preview added in v0.0.74

func (t *RunAgentScriptTool) Preview(args json.RawMessage) string

func (*RunAgentScriptTool) Spec added in v0.0.74

func (t *RunAgentScriptTool) Spec() llm.ToolSpec

type SetOutputTool added in v0.0.37

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

SetOutputTool captures structured output from an agent. This tool is dynamically created based on agent configuration and provides a way to force structured output via a tool call, eliminating verbose prose that LLMs often include even with explicit instructions.

func NewSetOutputTool added in v0.0.37

func NewSetOutputTool(name, paramName, description string) *SetOutputTool

NewSetOutputTool creates a tool with custom name/description.

func (*SetOutputTool) Execute added in v0.0.37

func (t *SetOutputTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*SetOutputTool) IsFinishingTool added in v0.0.49

func (t *SetOutputTool) IsFinishingTool() bool

IsFinishingTool returns true because output tools signal agent completion.

func (*SetOutputTool) Name added in v0.0.37

func (t *SetOutputTool) Name() string

Name returns the configured tool name.

func (*SetOutputTool) Preview added in v0.0.37

func (t *SetOutputTool) Preview(args json.RawMessage) string

func (*SetOutputTool) Spec added in v0.0.37

func (t *SetOutputTool) Spec() llm.ToolSpec

func (*SetOutputTool) Value added in v0.0.37

func (t *SetOutputTool) Value() string

Value returns the captured output value.

type ShellApprovalCache

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

ShellApprovalCache caches shell command pattern approvals for the session.

func NewShellApprovalCache

func NewShellApprovalCache() *ShellApprovalCache

NewShellApprovalCache creates a new ShellApprovalCache.

func (*ShellApprovalCache) AddPattern

func (c *ShellApprovalCache) AddPattern(pattern string)

AddPattern adds a pattern to the session cache.

func (*ShellApprovalCache) GetPatterns

func (c *ShellApprovalCache) GetPatterns() []string

GetPatterns returns all session-approved patterns.

type ShellArgs

type ShellArgs struct {
	Command        string `json:"command"`
	WorkingDir     string `json:"working_dir,omitempty"`
	TimeoutSeconds int    `json:"timeout_seconds,omitempty"`
}

ShellArgs are the arguments for the shell tool.

type ShellResult

type ShellResult struct {
	Stdout   string `json:"stdout"`
	Stderr   string `json:"stderr"`
	ExitCode int    `json:"exit_code"`
	TimedOut bool   `json:"timed_out,omitempty"`
}

ShellResult contains the result of a shell command.

type ShellTool

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

ShellTool implements the shell tool.

func NewShellTool

func NewShellTool(approval *ApprovalManager, config *ToolConfig, limits OutputLimits) *ShellTool

NewShellTool creates a new ShellTool.

func (*ShellTool) Execute

func (t *ShellTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*ShellTool) Preview

func (t *ShellTool) Preview(args json.RawMessage) string

func (*ShellTool) Spec

func (t *ShellTool) Spec() llm.ToolSpec

type ShowImageArgs added in v0.0.33

type ShowImageArgs struct {
	FilePath        string `json:"file_path"`
	CopyToClipboard *bool  `json:"copy_to_clipboard,omitempty"` // Default: true
	Prompt          string `json:"prompt,omitempty"`            // Steering prompt for image analysis
}

ShowImageArgs are the arguments for show_image.

type ShowImageTool added in v0.0.33

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

ShowImageTool implements the show_image tool for displaying images to users.

func NewShowImageTool added in v0.0.33

func NewShowImageTool(approval *ApprovalManager) *ShowImageTool

NewShowImageTool creates a new ShowImageTool.

func (*ShowImageTool) Execute added in v0.0.33

func (t *ShowImageTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*ShowImageTool) Preview added in v0.0.33

func (t *ShowImageTool) Preview(args json.RawMessage) string

func (*ShowImageTool) Spec added in v0.0.33

func (t *ShowImageTool) Spec() llm.ToolSpec

type SkillActivatedCallback added in v0.0.37

type SkillActivatedCallback func(allowedTools []string)

SkillActivatedCallback is called when a skill is activated. It receives the skill's allowed tools list (may be empty if skill has no restrictions).

type SpawnAgentArgs added in v0.0.35

type SpawnAgentArgs struct {
	AgentName string `json:"agent_name"`        // Required: name of the agent to spawn
	Prompt    string `json:"prompt"`            // Required: task/prompt for the sub-agent
	Timeout   int    `json:"timeout,omitempty"` // Optional: timeout in seconds (default 300)
}

SpawnAgentArgs are the arguments for the spawn_agent tool.

type SpawnAgentResult added in v0.0.35

type SpawnAgentResult struct {
	AgentName string `json:"agent_name"`
	Output    string `json:"output,omitempty"`
	Error     string `json:"error,omitempty"`
	Type      string `json:"type,omitempty"` // Error type for structured handling
	Duration  int64  `json:"duration_ms,omitempty"`
	SessionID string `json:"session_id,omitempty"` // Child session ID for inspector integration
}

SpawnAgentResult is the result returned by spawn_agent.

type SpawnAgentRunResult added in v0.0.46

type SpawnAgentRunResult struct {
	Output    string // Text output from the agent
	SessionID string // Child session ID for inspector integration (empty if session tracking disabled)
}

SpawnAgentRunResult contains the output from a sub-agent run.

type SpawnAgentRunner added in v0.0.35

type SpawnAgentRunner interface {
	// RunAgent runs a sub-agent and returns its text output.
	// ctx is used for cancellation, agentName is the agent to load,
	// prompt is the task, and depth is the current nesting level.
	RunAgent(ctx context.Context, agentName string, prompt string, depth int) (SpawnAgentRunResult, error)

	// RunAgentWithCallback runs a sub-agent with an event callback for progress reporting.
	// callID is used to correlate events with the parent's spawn_agent tool call.
	RunAgentWithCallback(ctx context.Context, agentName string, prompt string, depth int,
		callID string, cb SubagentEventCallback) (SpawnAgentRunResult, error)
}

SpawnAgentRunner is the interface for running sub-agents. This is set by the cmd package to avoid circular imports.

type SpawnAgentTool added in v0.0.35

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

SpawnAgentTool implements the spawn_agent tool.

func NewSpawnAgentTool added in v0.0.35

func NewSpawnAgentTool(config SpawnConfig, depth int) *SpawnAgentTool

NewSpawnAgentTool creates a new spawn_agent tool.

func (*SpawnAgentTool) Execute added in v0.0.35

func (t *SpawnAgentTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

Execute runs the spawn_agent tool.

func (*SpawnAgentTool) GetEventCallback added in v0.0.42

func (t *SpawnAgentTool) GetEventCallback() SubagentEventCallback

GetEventCallback returns the current event callback (thread-safe).

func (*SpawnAgentTool) Preview added in v0.0.35

func (t *SpawnAgentTool) Preview(args json.RawMessage) string

Preview returns a short description of the tool call.

func (*SpawnAgentTool) SetDepth added in v0.0.35

func (t *SpawnAgentTool) SetDepth(depth int)

SetDepth sets the current nesting depth for this tool. Used when creating tools for sub-agents to track depth.

func (*SpawnAgentTool) SetEventCallback added in v0.0.42

func (t *SpawnAgentTool) SetEventCallback(cb SubagentEventCallback)

SetEventCallback sets the callback for receiving subagent progress events. Events are bubbled up to the parent for display during execution.

func (*SpawnAgentTool) SetRunner added in v0.0.35

func (t *SpawnAgentTool) SetRunner(runner SpawnAgentRunner)

SetRunner sets the runner for executing sub-agents. This must be called before Execute can succeed.

func (*SpawnAgentTool) Spec added in v0.0.35

func (t *SpawnAgentTool) Spec() llm.ToolSpec

Spec returns the tool specification.

type SpawnConfig added in v0.0.35

type SpawnConfig struct {
	MaxParallel    int      // Max concurrent sub-agents (default 3)
	MaxDepth       int      // Max nesting level (default 2)
	DefaultTimeout int      // Default timeout in seconds (default 300)
	AllowedAgents  []string // Optional whitelist of allowed agents
}

SpawnConfig configures spawn_agent behavior.

func DefaultSpawnConfig added in v0.0.35

func DefaultSpawnConfig() SpawnConfig

DefaultSpawnConfig returns the default spawn configuration.

type SubagentEvent added in v0.0.42

type SubagentEvent struct {
	Type         SubagentEventType // "init", "text", "tool_start", "tool_end", "phase", "usage", "done"
	Text         string            // for "text" events
	ToolName     string            // for tool events
	ToolInfo     string            // for tool events
	ToolOutput   string            // for "tool_end" events - text content
	Diffs        []llm.DiffData    // for "tool_end" events - structured diffs
	Images       []string          // for "tool_end" events - image paths
	Success      bool              // for "tool_end" events
	Phase        string            // for "phase" events
	InputTokens  int               // for "usage" events
	OutputTokens int               // for "usage" events
	Provider     string            // for "init" events - provider name
	Model        string            // for "init" events - model name
}

SubagentEvent represents an event from a running subagent.

type SubagentEventCallback added in v0.0.42

type SubagentEventCallback func(callID string, event SubagentEvent)

SubagentEventCallback is called to bubble up events from a running subagent. callID is the tool call ID of the spawn_agent call.

type SubagentEventType added in v0.0.42

type SubagentEventType string

SubagentEventType identifies the type of subagent event.

const (
	SubagentEventInit      SubagentEventType = "init" // Sent first with provider/model info
	SubagentEventText      SubagentEventType = "text"
	SubagentEventToolStart SubagentEventType = "tool_start"
	SubagentEventToolEnd   SubagentEventType = "tool_end"
	SubagentEventPhase     SubagentEventType = "phase"
	SubagentEventUsage     SubagentEventType = "usage"
	SubagentEventDone      SubagentEventType = "done"
)

type ToolConfig

type ToolConfig struct {
	Enabled         []string    `mapstructure:"enabled"`            // Enabled tool spec names
	ReadDirs        []string    `mapstructure:"read_dirs"`          // Directories for read operations
	WriteDirs       []string    `mapstructure:"write_dirs"`         // Directories for write operations
	ShellAllow      []string    `mapstructure:"shell_allow"`        // Shell command patterns
	ScriptCommands  []string    `mapstructure:"script_commands"`    // Exact script commands (auto-approved)
	ShellAutoRun    bool        `mapstructure:"shell_auto_run"`     // Auto-approve matching shell
	ShellAutoRunEnv string      `mapstructure:"shell_auto_run_env"` // Env var required for auto-run
	ShellNonTTYEnv  string      `mapstructure:"shell_non_tty_env"`  // Env var for non-TTY execution
	ImageProvider   string      `mapstructure:"image_provider"`     // Override for image provider
	Spawn           SpawnConfig `mapstructure:"spawn"`              // Spawn agent configuration
	AgentDir        string      `mapstructure:"-"`                  // Agent source directory (set at runtime)
}

ToolConfig holds configuration for the local tool system.

func DefaultToolConfig

func DefaultToolConfig() ToolConfig

DefaultToolConfig returns sensible defaults for tool configuration.

func NewToolConfigFromFields

func NewToolConfigFromFields(enabled, readDirs, writeDirs, shellAllow []string, shellAutoRun bool, shellAutoRunEnv, shellNonTTYEnv, imageProvider string) ToolConfig

NewToolConfigFromFields creates a ToolConfig from individual field values. This allows callers from the config package to create ToolConfigs without circular imports.

func (*ToolConfig) BuildPermissions

func (c *ToolConfig) BuildPermissions() (*ToolPermissions, error)

BuildPermissions creates a ToolPermissions from this config.

func (*ToolConfig) CanAutoRunShell

func (c *ToolConfig) CanAutoRunShell() bool

CanAutoRunShell checks if shell commands can be auto-run.

func (*ToolConfig) CanRunShellNonTTY

func (c *ToolConfig) CanRunShellNonTTY() bool

CanRunShellNonTTY checks if shell can run in non-TTY mode.

func (*ToolConfig) EnabledSpecNames

func (c *ToolConfig) EnabledSpecNames() []string

EnabledSpecNames returns the spec names for all enabled tools.

func (*ToolConfig) IsToolEnabled

func (c *ToolConfig) IsToolEnabled(specName string) bool

IsToolEnabled checks if a tool is enabled.

func (ToolConfig) Merge

func (c ToolConfig) Merge(other ToolConfig) ToolConfig

Merge combines this config with another, with other taking precedence for non-empty values.

func (*ToolConfig) Validate

func (c *ToolConfig) Validate() []error

Validate checks the configuration for errors.

type ToolDisplay

type ToolDisplay struct {
	Title    string `json:"title,omitempty"`
	Preview  string `json:"preview,omitempty"`
	FilePath string `json:"file_path,omitempty"`
}

ToolDisplay contains optional display metadata for UI.

type ToolError

type ToolError struct {
	Type    ToolErrorType `json:"type"`
	Message string        `json:"message"`
}

ToolError provides structured error information for retry logic.

func NewToolError

func NewToolError(errType ToolErrorType, message string) *ToolError

NewToolError creates a new ToolError.

func NewToolErrorf

func NewToolErrorf(errType ToolErrorType, format string, args ...interface{}) *ToolError

NewToolErrorf creates a new ToolError with formatted message.

func (*ToolError) Error

func (e *ToolError) Error() string

type ToolErrorType

type ToolErrorType string

ToolErrorType provides structured errors for agent retry logic.

const (
	ErrFileNotFound       ToolErrorType = "FILE_NOT_FOUND"
	ErrInvalidParams      ToolErrorType = "INVALID_PARAMS"
	ErrPathNotInWorkspace ToolErrorType = "PATH_NOT_IN_WORKSPACE"
	ErrExecutionFailed    ToolErrorType = "EXECUTION_FAILED"
	ErrPermissionDenied   ToolErrorType = "PERMISSION_DENIED"
	ErrBinaryFile         ToolErrorType = "BINARY_FILE"
	ErrFileTooLarge       ToolErrorType = "FILE_TOO_LARGE"
	ErrImageGenFailed     ToolErrorType = "IMAGE_GEN_FAILED"
	ErrUnsupportedFormat  ToolErrorType = "UNSUPPORTED_FORMAT"
	ErrTimeout            ToolErrorType = "TIMEOUT"
	ErrSymlinkEscape      ToolErrorType = "SYMLINK_ESCAPE"
)

type ToolKind

type ToolKind string

ToolKind categorizes tools for permission grouping.

const (
	KindRead        ToolKind = "read"
	KindEdit        ToolKind = "edit"
	KindSearch      ToolKind = "search"
	KindExecute     ToolKind = "execute"
	KindImage       ToolKind = "image"
	KindInteractive ToolKind = "interactive"
	KindAgent       ToolKind = "agent" // For spawn_agent tool
	KindSkill       ToolKind = "skill" // For activate_skill tool
)

func GetToolKind

func GetToolKind(specName string) ToolKind

GetToolKind returns the kind for a tool spec name.

type ToolManager

type ToolManager struct {
	Registry    *LocalToolRegistry
	ApprovalMgr *ApprovalManager
}

ToolManager provides a high-level interface for tool management in commands.

func NewToolManager

func NewToolManager(toolConfig *ToolConfig, appConfig *config.Config) (*ToolManager, error)

NewToolManager creates a new tool manager from config.

func (*ToolManager) GetSpawnAgentTool added in v0.0.35

func (m *ToolManager) GetSpawnAgentTool() *SpawnAgentTool

GetSpawnAgentTool returns the spawn_agent tool if enabled, for runner configuration.

func (*ToolManager) GetSpecs

func (m *ToolManager) GetSpecs() []llm.ToolSpec

GetSpecs returns all tool specs for the request.

func (*ToolManager) SetupEngine

func (m *ToolManager) SetupEngine(engine *llm.Engine)

SetupEngine registers tools with the engine.

type ToolMetadata

type ToolMetadata struct {
	ExecutionTimeMs   int64 `json:"execution_time_ms"`
	PermissionCheckMs int64 `json:"permission_check_ms,omitempty"`
	OutputBytes       int64 `json:"output_bytes"`
	Truncated         bool  `json:"truncated,omitempty"`
}

ToolMetadata contains execution metrics.

type ToolPayload

type ToolPayload struct {
	Output      string         `json:"output"`
	Display     *ToolDisplay   `json:"display,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	Attachments []Attachment   `json:"attachments,omitempty"`
	Error       *ToolError     `json:"error,omitempty"`
}

ToolPayload is an optional JSON payload for tools that need display/metadata. This is encoded in ToolResult.Content when UI metadata is required.

func (*ToolPayload) ToJSON

func (p *ToolPayload) ToJSON() string

ToJSON encodes the payload as JSON for use in ToolResult.Content.

type ToolPermissions

type ToolPermissions struct {
	ReadDirs       []string // Directories for read/grep/glob/view
	WriteDirs      []string // Directories for write/edit
	ShellAllow     []string // Shell command patterns (glob syntax)
	ScriptCommands []string // Exact script commands (auto-approved)
	// contains filtered or unexported fields
}

ToolPermissions manages allowlists for tool access.

func NewToolPermissions

func NewToolPermissions() *ToolPermissions

NewToolPermissions creates a new ToolPermissions instance.

func (*ToolPermissions) AddReadDir

func (p *ToolPermissions) AddReadDir(dir string) error

AddReadDir adds a directory to the read allowlist.

func (*ToolPermissions) AddScriptCommand added in v0.0.33

func (p *ToolPermissions) AddScriptCommand(command string)

AddScriptCommand adds an exact script command to the allowlist.

func (*ToolPermissions) AddShellPattern

func (p *ToolPermissions) AddShellPattern(pattern string) error

AddShellPattern adds a shell command pattern to the allowlist.

func (*ToolPermissions) AddWriteDir

func (p *ToolPermissions) AddWriteDir(dir string) error

AddWriteDir adds a directory to the write allowlist.

func (*ToolPermissions) CheckSymlinkEscape

func (p *ToolPermissions) CheckSymlinkEscape(path string, allowedDirs []string) error

CheckSymlinkEscape checks if a path escapes via symlink. Returns an error if the resolved path is outside the allowed directories.

func (*ToolPermissions) CompileShellPatterns

func (p *ToolPermissions) CompileShellPatterns() error

CompileShellPatterns pre-compiles all shell patterns.

func (*ToolPermissions) IsPathAllowedForRead

func (p *ToolPermissions) IsPathAllowedForRead(path string) (bool, error)

IsPathAllowedForRead checks if a path is allowed for read operations.

func (*ToolPermissions) IsPathAllowedForWrite

func (p *ToolPermissions) IsPathAllowedForWrite(path string) (bool, error)

IsPathAllowedForWrite checks if a path is allowed for write operations.

func (*ToolPermissions) IsShellCommandAllowed

func (p *ToolPermissions) IsShellCommandAllowed(command string) bool

IsShellCommandAllowed checks if a shell command matches any allowlist pattern or script.

type UnifiedDiffArgs added in v0.0.55

type UnifiedDiffArgs struct {
	Diff string `json:"diff"`
}

UnifiedDiffArgs are the arguments for unified_diff.

type UnifiedDiffTool added in v0.0.55

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

UnifiedDiffTool implements the unified_diff tool.

func NewUnifiedDiffTool added in v0.0.55

func NewUnifiedDiffTool(approval *ApprovalManager) *UnifiedDiffTool

NewUnifiedDiffTool creates a new UnifiedDiffTool.

func (*UnifiedDiffTool) Execute added in v0.0.55

func (t *UnifiedDiffTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*UnifiedDiffTool) Preview added in v0.0.55

func (t *UnifiedDiffTool) Preview(args json.RawMessage) string

func (*UnifiedDiffTool) Spec added in v0.0.55

func (t *UnifiedDiffTool) Spec() llm.ToolSpec

type ViewImageArgs

type ViewImageArgs struct {
	FilePath string `json:"file_path"`
	Detail   string `json:"detail,omitempty"` // "low", "high", or "auto"
}

ViewImageArgs are the arguments for view_image.

type ViewImageTool

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

ViewImageTool implements the view_image tool.

func NewViewImageTool

func NewViewImageTool(approval *ApprovalManager) *ViewImageTool

NewViewImageTool creates a new ViewImageTool.

func (*ViewImageTool) Execute

func (t *ViewImageTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*ViewImageTool) Preview

func (t *ViewImageTool) Preview(args json.RawMessage) string

func (*ViewImageTool) Spec

func (t *ViewImageTool) Spec() llm.ToolSpec

type WriteFileArgs

type WriteFileArgs struct {
	FilePath string `json:"file_path"`
	Content  string `json:"content"`
}

WriteFileArgs are the arguments for write_file.

type WriteFileTool

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

WriteFileTool implements the write_file tool.

func NewWriteFileTool

func NewWriteFileTool(approval *ApprovalManager) *WriteFileTool

NewWriteFileTool creates a new WriteFileTool.

func (*WriteFileTool) Execute

func (t *WriteFileTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*WriteFileTool) Preview

func (t *WriteFileTool) Preview(args json.RawMessage) string

func (*WriteFileTool) Spec

func (t *WriteFileTool) Spec() llm.ToolSpec

Jump to

Keyboard shortcuts

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