tool

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultTimeout = 60 * time.Second

DefaultTimeout 默认工具执行超时时间

View Source
const MaxTimeout = 300 * time.Second

MaxTimeout 最大超时时间

Variables

View Source
var (
	ErrToolNotFound        = errors.New("tool not found")
	ErrInvalidParameters   = errors.New("invalid parameters")
	ErrToolExecutionFailed = errors.New("tool execution failed")
	ErrToolTimeout         = errors.New("tool execution timeout")
)

Common tool errors

View Source
var CodeTemplates = map[string]string{
	"file_processor": `
import os
import json

def process_files(directory, pattern="*.txt"):
    """Process all files matching pattern in directory."""
    import glob
    results = []
    for filepath in glob.glob(os.path.join(directory, pattern)):
        with open(filepath, 'r') as f:
            results.append({
                'path': filepath,
                'content': f.read(),
                'size': os.path.getsize(filepath)
            })
    return results

# Example usage
results = process_files('/tmp', '*.txt')
print(f"Processed {len(results)} files")
json_dump(results)
`,

	"web_scraper": `
import json
import re

def scrape_links(html, base_url=''):
    """Extract links from HTML."""
    pattern = r'href=["\']([^"\']+)["\']'
    links = re.findall(pattern, html)
    return [{'url': link, 'absolute': link if link.startswith('http') else base_url + link} for link in links]

# Example usage
html = tool('web_fetch', url='https://example.com')
if isinstance(html, dict):
    html = html.get('content', '')

links = scrape_links(str(html), 'https://example.com')
print(f"Found {len(links)} links")
json_dump(links[:10])
`,

	"data_analysis": `
import json
from collections import Counter

def analyze_data(items, key):
    """Analyze items by key."""
    counter = Counter()
    for item in items:
        if isinstance(item, dict) and key in item:
            counter[item[key]] += 1
    return {
        'total': len(items),
        'distribution': dict(counter),
        'most_common': counter.most_common(5)
    }

# Example: Analyze a list
data = [{'category': 'A', 'value': 1}, {'category': 'B', 'value': 2}]
results = analyze_data(data, 'category')
json_dump(results)
`,

	"file_processor_node": `
const fs = require('fs');
const path = require('path');

async function processFiles(directory, pattern = "*.txt") {
    const results = [];
    const files = fs.readdirSync(directory);
    
    for (const file of files) {
        if (file.endsWith('.txt')) {
            const filePath = path.join(directory, file);
            const content = fs.readFileSync(filePath, 'utf8');
            results.push({
                path: filePath,
                content: content,
                size: fs.statSync(filePath).size
            });
        }
    }
    return results;
}

// Example usage
const results = processFiles('/tmp');
console.log("Processed " + results.length + " files");
json_dump(results);
`,

	"web_scraper_node": `
const https = require('https');
const http = require('http');

function extractLinks(html, baseUrl) {
    baseUrl = baseUrl || '';
    const linkRegex = /href=["']([^"']+)["']/g;
    const links = [];
    let match;
    while ((match = linkRegex.exec(html)) !== null) {
        links.push({
            url: match[1],
            absolute: match[1].startsWith('http') ? match[1] : baseUrl + match[1]
        });
    }
    return links;
}

// Example usage
// const html = await web_fetch('https://example.com');
// const links = extractLinks(html, 'https://example.com');
// console.log("Found " + links.length + " links");
// json_dump(links.slice(0, 10));
`,

	"data_analysis_node": `
function analyzeData(items, key) {
    const distribution = {};
    items.forEach(item => {
        if (item && typeof item === 'object' && key in item) {
            const val = item[key];
            distribution[val] = (distribution[val] || 0) + 1;
        }
    });
    
    const entries = Object.entries(distribution);
    entries.sort((a, b) => b[1] - a[1]);
    const sorted = entries.slice(0, 5);
    
    return {
        total: items.length,
        distribution: distribution,
        most_common: sorted
    };
}

// Example: Analyze a list
const data = [{category: 'A', value: 1}, {category: 'B', value: 2}];
const results = analyzeData(data, 'category');
json_dump(results);
`,
}

CodeTemplates provides pre-built code templates

View Source
var DefaultRetryOptions = RetryOptions{
	MaxAttempts: 3,
	InitialWait: 100 * time.Millisecond,
	MaxWait:     5 * time.Second,
	Multiplier:  2.0,
	ShouldRetry: func(err error, attempt int) bool {
		if err == nil {
			return false
		}

		return attempt < 3
	},
}
View Source
var KanbanManager *kanban.Manager

KanbanManager is the global kanban manager instance

View Source
var ToolsetRegistry = make(map[string]*ToolsetDefinition)

Toolset registry for managing tool groups

Functions

func CloseKanbanManager

func CloseKanbanManager() error

CloseKanbanManager closes the global kanban manager

func ExportBrowserToolsJSON

func ExportBrowserToolsJSON() string

ExportBrowserToolsJSON exports browser tools as JSON

func ExportTerminalBackendsJSON

func ExportTerminalBackendsJSON() string

ExportTerminalBackendsJSON exports available backends as JSON

func GetAllToolsets

func GetAllToolsets() map[string]*ToolsetDefinition

GetAllToolsets returns all toolsets

func GetTemplate

func GetTemplate(name string) (string, bool)

GetTemplate returns a code template by name

func GetToolsetNames

func GetToolsetNames() []string

GetToolsetNames returns all registered toolset names

func InitKanbanManager

func InitKanbanManager(homeDir string) error

InitKanbanManager initializes the global kanban manager

func InitializeDefaultToolsets

func InitializeDefaultToolsets()

InitializeDefaultToolsets registers all default toolsets

func LintFile

func LintFile(filePath string) ([]string, error)

LintFile performs syntax checking on a file after writing. Returns issues (non-blocking) or nil if no issues found.

func ListTemplates

func ListTemplates() []string

ListTemplates returns all available template names

func MarshalResult

func MarshalResult(v interface{}) string

MarshalResult marshals a result to JSON string

func ParseTaskStatus

func ParseTaskStatus(s string) kanban.TaskStatus

ParseTaskStatus parses a string into TaskStatus

func RegisterKanbanTools

func RegisterKanbanTools(registry *Registry)

RegisterKanbanTools registers kanban tools to the registry Tools are only registered when KANBAN_TASK environment variable is set

func RegisterMCPServerToolset

func RegisterMCPServerToolset(serverName string, toolNames []string)

RegisterMCPServerToolset registers a toolset for an MCP server

func RegisterToolset

func RegisterToolset(ts *ToolsetDefinition)

RegisterToolset registers a toolset

func ResolveToolset

func ResolveToolset(name string, visited map[string]bool) []string

ResolveToolset resolves a toolset and all its includes to get all tool names

func UnregisterMCPServerToolset

func UnregisterMCPServerToolset(serverName string)

UnregisterMCPServerToolset removes an MCP server toolset

func ValidateCode

func ValidateCode(code string) (bool, string)

ValidateCode performs static analysis on code for security issues Supports both Python and JavaScript/Node.js

func ValidateCodeForLanguage

func ValidateCodeForLanguage(code, language string) (bool, string)

ValidateCodeForLanguage performs security check for specific language

func ValidateParams

func ValidateParams(schema map[string]interface{}, params map[string]interface{}) error

ValidateParams 验证参数是否符合 Schema

Types

type AsyncJob

type AsyncJob struct {
	ID        string
	ToolName  string
	Params    map[string]any
	Status    JobStatus
	Result    *ToolResult
	Error     error
	CreatedAt time.Time
	StartedAt time.Time
	EndedAt   time.Time
}

AsyncJob 异步任务

type AsyncTool

type AsyncTool interface {
	Tool
	// Start 启动异步执行,返回 jobID
	Start(ctx context.Context, params map[string]any) (string, error)
	// Status 获取任务状态
	Status(jobID string) (JobStatus, error)
	// Result 获取任务结果
	Result(jobID string) (*ToolResult, error)
	// Cancel 取消任务
	Cancel(jobID string) error
}

AsyncTool 异步工具接口

type AsyncToolExecutor

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

AsyncToolExecutor 异步工具执行器

func NewAsyncToolExecutor

func NewAsyncToolExecutor(registry *Registry, maxWorkers int) *AsyncToolExecutor

NewAsyncToolExecutor 创建异步执行器

func (*AsyncToolExecutor) Cancel

func (e *AsyncToolExecutor) Cancel(jobID string) error

Cancel 取消任务

func (*AsyncToolExecutor) GetJob

func (e *AsyncToolExecutor) GetJob(jobID string) (*AsyncJob, error)

GetJob 获取任务

func (*AsyncToolExecutor) ListJobs

func (e *AsyncToolExecutor) ListJobs() []*AsyncJob

ListJobs 列出所有任务

func (*AsyncToolExecutor) Submit

func (e *AsyncToolExecutor) Submit(ctx context.Context, toolName string, params map[string]any) (string, error)

Submit 提交异步任务

type BackendManager

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

BackendManager manages terminal backends

func NewBackendManager

func NewBackendManager() *BackendManager

func (*BackendManager) Execute

func (m *BackendManager) Execute(ctx context.Context, backendName string, cmd string, workDir string, timeout time.Duration) (*ExecutionResult, error)

func (*BackendManager) Get

func (m *BackendManager) Get(name string) TerminalBackend

func (*BackendManager) GetDefault

func (m *BackendManager) GetDefault() TerminalBackend

func (*BackendManager) List

func (m *BackendManager) List() []string

func (*BackendManager) Register

func (m *BackendManager) Register(backend TerminalBackend)

func (*BackendManager) SetDefault

func (m *BackendManager) SetDefault(name string)

type BaseTool

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

BaseTool 提供工具的默认实现基础类

func NewBaseTool

func NewBaseTool(name, description string, schema map[string]interface{}) *BaseTool

NewBaseTool 创建一个基础工具

func (*BaseTool) Description

func (t *BaseTool) Description() string

func (*BaseTool) Name

func (t *BaseTool) Name() string

func (*BaseTool) Schema

func (t *BaseTool) Schema() map[string]interface{}

type BrowserBackTool

type BrowserBackTool struct{}

BrowserBackTool navigates back

func NewBrowserBackTool

func NewBrowserBackTool() *BrowserBackTool

func (*BrowserBackTool) Description

func (t *BrowserBackTool) Description() string

func (*BrowserBackTool) Execute

func (t *BrowserBackTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*BrowserBackTool) Name

func (t *BrowserBackTool) Name() string

func (*BrowserBackTool) Schema

func (t *BrowserBackTool) Schema() map[string]interface{}

type BrowserClickTool

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

BrowserClickTool simulates clicking an element

func NewBrowserClickTool

func NewBrowserClickTool(bt *BrowserTools) *BrowserClickTool

func (*BrowserClickTool) Description

func (t *BrowserClickTool) Description() string

func (*BrowserClickTool) Execute

func (t *BrowserClickTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*BrowserClickTool) Name

func (t *BrowserClickTool) Name() string

func (*BrowserClickTool) Schema

func (t *BrowserClickTool) Schema() map[string]interface{}

type BrowserConsoleTool

type BrowserConsoleTool struct{}

BrowserConsoleTool extracts console errors (placeholder)

func NewBrowserConsoleTool

func NewBrowserConsoleTool() *BrowserConsoleTool

func (*BrowserConsoleTool) Description

func (t *BrowserConsoleTool) Description() string

func (*BrowserConsoleTool) Execute

func (t *BrowserConsoleTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*BrowserConsoleTool) Name

func (t *BrowserConsoleTool) Name() string

func (*BrowserConsoleTool) Schema

func (t *BrowserConsoleTool) Schema() map[string]interface{}

type BrowserGetImagesTool

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

BrowserGetImagesTool extracts image URLs

func NewBrowserGetImagesTool

func NewBrowserGetImagesTool(bt *BrowserTools) *BrowserGetImagesTool

func (*BrowserGetImagesTool) Description

func (t *BrowserGetImagesTool) Description() string

func (*BrowserGetImagesTool) Execute

func (t *BrowserGetImagesTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*BrowserGetImagesTool) Name

func (t *BrowserGetImagesTool) Name() string

func (*BrowserGetImagesTool) Schema

func (t *BrowserGetImagesTool) Schema() map[string]interface{}

type BrowserNavigateTool

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

BrowserNavigateTool navigates to a URL

func NewBrowserNavigateTool

func NewBrowserNavigateTool(bt *BrowserTools) *BrowserNavigateTool

func (*BrowserNavigateTool) Description

func (t *BrowserNavigateTool) Description() string

func (*BrowserNavigateTool) Execute

func (t *BrowserNavigateTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*BrowserNavigateTool) Name

func (t *BrowserNavigateTool) Name() string

func (*BrowserNavigateTool) Schema

func (t *BrowserNavigateTool) Schema() map[string]interface{}

type BrowserScrollTool

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

BrowserScrollTool scrolls the page

func NewBrowserScrollTool

func NewBrowserScrollTool(bt *BrowserTools) *BrowserScrollTool

func (*BrowserScrollTool) Description

func (t *BrowserScrollTool) Description() string

func (*BrowserScrollTool) Execute

func (t *BrowserScrollTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*BrowserScrollTool) Name

func (t *BrowserScrollTool) Name() string

func (*BrowserScrollTool) Schema

func (t *BrowserScrollTool) Schema() map[string]interface{}

type BrowserSnapshotTool

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

BrowserSnapshotTool takes a snapshot of the current page

func NewBrowserSnapshotTool

func NewBrowserSnapshotTool(bt *BrowserTools) *BrowserSnapshotTool

func (*BrowserSnapshotTool) Description

func (t *BrowserSnapshotTool) Description() string

func (*BrowserSnapshotTool) Execute

func (t *BrowserSnapshotTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*BrowserSnapshotTool) Name

func (t *BrowserSnapshotTool) Name() string

func (*BrowserSnapshotTool) Schema

func (t *BrowserSnapshotTool) Schema() map[string]interface{}

type BrowserTools

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

BrowserTools provides enhanced browser automation tools

func NewBrowserTools

func NewBrowserTools() *BrowserTools

NewBrowserTools creates a new browser tools instance

type BrowserTypeTool

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

BrowserTypeTool simulates typing text

func NewBrowserTypeTool

func NewBrowserTypeTool(bt *BrowserTools) *BrowserTypeTool

func (*BrowserTypeTool) Description

func (t *BrowserTypeTool) Description() string

func (*BrowserTypeTool) Execute

func (t *BrowserTypeTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*BrowserTypeTool) Name

func (t *BrowserTypeTool) Name() string

func (*BrowserTypeTool) Schema

func (t *BrowserTypeTool) Schema() map[string]interface{}

type CSVTool

type CSVTool struct {
	BaseTool
}

func NewCSVTool

func NewCSVTool() *CSVTool

func (*CSVTool) Execute

func (t *CSVTool) Execute(ctx context.Context, args map[string]any) (any, error)

type CacheKeyBuilder

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

CacheKeyBuilder 缓存 key 构建器

func NewCacheKeyBuilder

func NewCacheKeyBuilder(prefix string) *CacheKeyBuilder

func (*CacheKeyBuilder) Build

func (b *CacheKeyBuilder) Build(toolName string, params map[string]any) string

type CacheStats

type CacheStats struct {
	Hits       int64
	Misses     int64
	Evictions  int64
	Items      int
	MemoryUsed int64
}

CacheStats 缓存统计

type CachedToolExecutor

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

CachedToolExecutor 带有缓存的执行器包装

func NewCachedToolExecutor

func NewCachedToolExecutor(registry *Registry, cache ToolCache) *CachedToolExecutor

NewCachedToolExecutor 创建缓存执行器

func (*CachedToolExecutor) ExecuteCached

func (e *CachedToolExecutor) ExecuteCached(ctx context.Context, toolName string, params map[string]any, ttl time.Duration) (*ToolResult, error)

ExecuteCached 带缓存执行

func (*CachedToolExecutor) InvalidateCache

func (e *CachedToolExecutor) InvalidateCache(toolName string)

InvalidateCache 使缓存失效

type CancelTaskTool

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

CancelTaskTool cancels a running sub-agent task

func NewCancelTaskTool

func NewCancelTaskTool() *CancelTaskTool

NewCancelTaskTool creates a new cancel task tool

func (*CancelTaskTool) Description

func (t *CancelTaskTool) Description() string

func (*CancelTaskTool) Execute

func (t *CancelTaskTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute cancels a task

func (*CancelTaskTool) Name

func (t *CancelTaskTool) Name() string

func (*CancelTaskTool) Schema

func (t *CancelTaskTool) Schema() map[string]interface{}

type ClarifyTool

type ClarifyTool struct{}

ClarifyTool asks the user for clarification

func NewClarifyTool

func NewClarifyTool() *ClarifyTool

NewClarifyTool creates a new clarify tool

func (*ClarifyTool) Description

func (t *ClarifyTool) Description() string

Description returns the tool description

func (*ClarifyTool) Execute

func (t *ClarifyTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute asks the user for clarification

func (*ClarifyTool) Name

func (t *ClarifyTool) Name() string

Name returns the tool name

func (*ClarifyTool) Parameters

func (t *ClarifyTool) Parameters() map[string]interface{}

func (*ClarifyTool) Schema

func (t *ClarifyTool) Schema() map[string]interface{}

Parameters returns the tool parameters schema

type CodeExecutionRequest

type CodeExecutionRequest struct {
	Code     string                 `json:"code"`
	Language string                 `json:"language,omitempty"`
	Timeout  int                    `json:"timeout,omitempty"`
	WorkDir  string                 `json:"workdir,omitempty"`
	Tools    []string               `json:"tools,omitempty"`
	Context  map[string]interface{} `json:"context,omitempty"`
}

CodeExecutionRequest represents a code execution request with tool context

type CodeExecutionResponse

type CodeExecutionResponse struct {
	Success   bool           `json:"success"`
	Output    string         `json:"output,omitempty"`
	Error     string         `json:"error,omitempty"`
	ExitCode  int            `json:"exit_code"`
	ToolCalls []CodeToolCall `json:"tool_calls,omitempty"`
	Duration  time.Duration  `json:"duration"`
}

CodeExecutionResponse represents the response from code execution

type CodeExecutorConfig

type CodeExecutorConfig struct {
	Timeout     time.Duration // Max execution time
	MemoryLimit int           // Memory limit in MB
	AllowedDirs []string      // Allowed working directories
	EnableTools bool          // Enable tool calling from code
}

CodeExecutorConfig holds configuration for code execution

func DefaultCodeExecutorConfig

func DefaultCodeExecutorConfig() *CodeExecutorConfig

DefaultCodeExecutorConfig returns the default configuration

type CodeToolCall

type CodeToolCall struct {
	Tool     string        `json:"tool"`
	Args     interface{}   `json:"args"`
	Result   interface{}   `json:"result"`
	Duration time.Duration `json:"duration"`
}

CodeToolCall represents a tool call made during code execution

type CronJobTool

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

CronJobTool manages scheduled tasks (cron jobs)

func NewCronJobTool

func NewCronJobTool() *CronJobTool

NewCronJobTool creates a new cron job tool

func (*CronJobTool) Description

func (t *CronJobTool) Description() string

Description returns the tool description

func (*CronJobTool) Execute

func (t *CronJobTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute manages cron jobs

func (*CronJobTool) Name

func (t *CronJobTool) Name() string

Name returns the tool name

func (*CronJobTool) Parameters

func (t *CronJobTool) Parameters() map[string]interface{}

func (*CronJobTool) Schema

func (t *CronJobTool) Schema() map[string]interface{}

Parameters returns the tool parameters schema

type DaytonaBackend

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

DaytonaBackend executes commands via Daytona (serverless dev environments)

func NewDaytonaBackend

func NewDaytonaBackend() *DaytonaBackend

func (*DaytonaBackend) Configure

func (b *DaytonaBackend) Configure(workspace, image, language, serverURL, apiKey string)

func (*DaytonaBackend) Description

func (b *DaytonaBackend) Description() string

func (*DaytonaBackend) Execute

func (b *DaytonaBackend) Execute(ctx context.Context, cmd string, workDir string, timeout time.Duration) (*ExecutionResult, error)

func (*DaytonaBackend) Health

func (b *DaytonaBackend) Health() error

func (*DaytonaBackend) IsAvailable

func (b *DaytonaBackend) IsAvailable() bool

func (*DaytonaBackend) Name

func (b *DaytonaBackend) Name() string

func (*DaytonaBackend) SetAutoWake

func (b *DaytonaBackend) SetAutoWake(autoWake bool)

func (*DaytonaBackend) SetPersist

func (b *DaytonaBackend) SetPersist(persist bool)

type DefaultMetricsRecorder

type DefaultMetricsRecorder struct{}

DefaultMetricsRecorder 默认指标记录器(空实现)

func (*DefaultMetricsRecorder) RecordToolExecution

func (r *DefaultMetricsRecorder) RecordToolExecution(toolName string, duration time.Duration, success bool, errorMsg string)

func (*DefaultMetricsRecorder) RecordToolMetric

func (r *DefaultMetricsRecorder) RecordToolMetric(toolName string, metricName string, value float64)

type DefaultToolExecutor

type DefaultToolExecutor struct{}

DefaultToolExecutor 默认工具执行器

func NewDefaultToolExecutor

func NewDefaultToolExecutor() *DefaultToolExecutor

NewDefaultToolExecutor 创建默认执行器

func (*DefaultToolExecutor) ExecuteWithProtection

func (e *DefaultToolExecutor) ExecuteWithProtection(ctx context.Context, tool Tool, params map[string]interface{}, timeout time.Duration) ToolExecutionResult

ExecuteWithProtection 执行工具,带有 panic 保护和超时控制

type DelegateTaskTool

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

DelegateTaskTool allows spawning isolated sub-agents for complex subtasks

func NewDelegateTaskTool

func NewDelegateTaskTool() *DelegateTaskTool

NewDelegateTaskTool creates a new delegate task tool

func (*DelegateTaskTool) Description

func (t *DelegateTaskTool) Description() string

func (*DelegateTaskTool) Execute

func (t *DelegateTaskTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute spawns a sub-agent task

func (*DelegateTaskTool) Name

func (t *DelegateTaskTool) Name() string

func (*DelegateTaskTool) Schema

func (t *DelegateTaskTool) Schema() map[string]interface{}

type DirectoryTreeTool

type DirectoryTreeTool struct {
	BaseTool
}

DirectoryTreeTool 目录树展示工具

func NewDirectoryTreeTool

func NewDirectoryTreeTool() *DirectoryTreeTool

NewDirectoryTreeTool 创建目录树工具

func (*DirectoryTreeTool) Execute

func (t *DirectoryTreeTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute 执行目录树展示

func (*DirectoryTreeTool) ValidateParams

func (t *DirectoryTreeTool) ValidateParams(params map[string]interface{}) error

ValidateParams 实现 ParamValidator 接口

type DockerBackend

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

DockerBackend executes commands in Docker containers

func NewDockerBackend

func NewDockerBackend() *DockerBackend

func (*DockerBackend) Description

func (b *DockerBackend) Description() string

func (*DockerBackend) Execute

func (b *DockerBackend) Execute(ctx context.Context, cmd string, workDir string, timeout time.Duration) (*ExecutionResult, error)

func (*DockerBackend) Health

func (b *DockerBackend) Health() error

func (*DockerBackend) IsAvailable

func (b *DockerBackend) IsAvailable() bool

func (*DockerBackend) Name

func (b *DockerBackend) Name() string

func (*DockerBackend) SetCpuLimit

func (b *DockerBackend) SetCpuLimit(limit string)

func (*DockerBackend) SetImage

func (b *DockerBackend) SetImage(image string)

func (*DockerBackend) SetMemoryLimit

func (b *DockerBackend) SetMemoryLimit(limit string)

type DocumentationGenerator

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

DocumentationGenerator 文档生成器

func NewDocumentationGenerator

func NewDocumentationGenerator() *DocumentationGenerator

NewDocumentationGenerator 创建文档生成器

func (*DocumentationGenerator) GenerateIndex

func (dg *DocumentationGenerator) GenerateIndex(tools []Tool) map[string]interface{}

GenerateIndex 生成工具索引

func (*DocumentationGenerator) GenerateMarkdown

func (dg *DocumentationGenerator) GenerateMarkdown(tools []Tool) string

GenerateMarkdown 生成 Markdown 格式文档

func (*DocumentationGenerator) GenerateOpenAPISpec

func (dg *DocumentationGenerator) GenerateOpenAPISpec(tools []Tool) []byte

GenerateOpenAPISpec 生成 OpenAPI 格式的工具规范

func (*DocumentationGenerator) GenerateToolHelp

func (dg *DocumentationGenerator) GenerateToolHelp(toolName string, tools []Tool) string

GenerateToolHelp 生成单个工具的帮助信息

type DynamicTool

type DynamicTool struct {
	Tool
	TTL     time.Duration
	Expires time.Time
}

DynamicTool 动态工具,支持 TTL 过期

func NewDynamicTool

func NewDynamicTool(tool Tool, ttl time.Duration) *DynamicTool

NewDynamicTool 创建一个动态工具

func (*DynamicTool) IsExpired

func (d *DynamicTool) IsExpired() bool

IsExpired 检查工具是否已过期

type EnvTool

type EnvTool struct {
	BaseTool
}

func NewEnvTool

func NewEnvTool() *EnvTool

func (*EnvTool) Execute

func (t *EnvTool) Execute(ctx context.Context, args map[string]any) (any, error)

type ExecuteCodeTool

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

ExecuteCodeTool provides in-process Python code execution with tool access

func NewExecuteCodeTool

func NewExecuteCodeTool() *ExecuteCodeTool

NewExecuteCodeTool creates a new execute_code tool

func (*ExecuteCodeTool) Description

func (t *ExecuteCodeTool) Description() string

func (*ExecuteCodeTool) Execute

func (t *ExecuteCodeTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute runs Python code with optional tool access

func (*ExecuteCodeTool) ExecuteWithTools

func (t *ExecuteCodeTool) ExecuteWithTools(ctx context.Context, req *CodeExecutionRequest, toolRegistry map[string]Tool) (*CodeExecutionResponse, error)

ExecuteWithTools executes code with tool integration

func (*ExecuteCodeTool) Name

func (t *ExecuteCodeTool) Name() string

func (*ExecuteCodeTool) RegisterTool

func (t *ExecuteCodeTool) RegisterTool(name string, tool Tool)

RegisterTool registers a tool that can be called from executed code

func (*ExecuteCodeTool) Schema

func (t *ExecuteCodeTool) Schema() map[string]interface{}

type ExecuteCommandTool

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

func NewSecureExecuteCommandTool

func NewSecureExecuteCommandTool(workDir string) *ExecuteCommandTool

func (*ExecuteCommandTool) AddToWhitelist

func (t *ExecuteCommandTool) AddToWhitelist(cmd string)

AddToWhitelist adds a command to the allowed list

func (*ExecuteCommandTool) Description

func (t *ExecuteCommandTool) Description() string

func (*ExecuteCommandTool) Execute

func (t *ExecuteCommandTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*ExecuteCommandTool) Name

func (t *ExecuteCommandTool) Name() string

func (*ExecuteCommandTool) Parameters

func (t *ExecuteCommandTool) Parameters() map[string]interface{}

func (*ExecuteCommandTool) Schema

func (t *ExecuteCommandTool) Schema() map[string]interface{}

func (*ExecuteCommandTool) SetAllowAny

func (t *ExecuteCommandTool) SetAllowAny(allow bool)

SetAllowAny allows executing arbitrary commands (use with caution)

type ExecutionResult

type ExecutionResult struct {
	Command   string        `json:"command"`
	ExitCode  int           `json:"exit_code"`
	Output    string        `json:"output"`
	Duration  time.Duration `json:"duration"`
	Backend   string        `json:"backend"`
	Timestamp time.Time     `json:"timestamp"`
}

ExecutionResult represents the result of a command execution

type FileEditTool

type FileEditTool struct{}

FileEditTool handles file edit operations

func NewFileEditTool

func NewFileEditTool() *FileEditTool

func (*FileEditTool) Description

func (t *FileEditTool) Description() string

func (*FileEditTool) Execute

func (t *FileEditTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

func (*FileEditTool) Name

func (t *FileEditTool) Name() string

func (*FileEditTool) Parameters

func (t *FileEditTool) Parameters() map[string]interface{}

func (*FileEditTool) Schema

func (t *FileEditTool) Schema() map[string]interface{}

type FileSearchTool

type FileSearchTool struct {
	BaseTool
}

FileSearchTool 文件内容搜索工具

func NewFileSearchTool

func NewFileSearchTool() *FileSearchTool

NewFileSearchTool 创建文件搜索工具

func (*FileSearchTool) Execute

func (t *FileSearchTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute 执行文件搜索

func (*FileSearchTool) ValidateParams

func (t *FileSearchTool) ValidateParams(params map[string]interface{}) error

ValidateParams 实现 ParamValidator 接口

type GroupManager

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

func DefaultToolGroups

func DefaultToolGroups(registry *Registry) *GroupManager

DefaultGroups 返回默认的工具分组

func NewGroupManager

func NewGroupManager() *GroupManager

NewGroupManager 创建分组管理器

func (*GroupManager) AddToolToGroup

func (gm *GroupManager) AddToolToGroup(tool Tool, groupName string) error

AddToolToGroup 将工具添加到分组

func (*GroupManager) CreateGroup

func (gm *GroupManager) CreateGroup(name, description string) *ToolGroup

CreateGroup 创建新的分组

func (*GroupManager) DeleteGroup

func (gm *GroupManager) DeleteGroup(name string)

DeleteGroup 删除分组(不删除工具)

func (*GroupManager) DisableGroup

func (gm *GroupManager) DisableGroup(name string)

DisableGroup 禁用分组

func (*GroupManager) EnableGroup

func (gm *GroupManager) EnableGroup(name string)

EnableGroup 启用分组

func (*GroupManager) GetEnabledTools

func (gm *GroupManager) GetEnabledTools() []Tool

GetEnabledTools 获取所有启用的工具

func (*GroupManager) GetGroup

func (gm *GroupManager) GetGroup(name string) *ToolGroup

GetGroup 获取分组

func (*GroupManager) GetToolGroup

func (gm *GroupManager) GetToolGroup(toolName string) string

GetToolGroup 获取工具所属的分组

func (*GroupManager) ListGroups

func (gm *GroupManager) ListGroups() []*ToolGroup

ListGroups 列出所有分组

func (*GroupManager) RegisterGroup

func (gm *GroupManager) RegisterGroup(group *ToolGroup)

RegisterGroup 注册分组

func (*GroupManager) RemoveToolFromGroup

func (gm *GroupManager) RemoveToolFromGroup(toolName, groupName string) error

RemoveToolFromGroup 将工具从分组移除

type HACallServiceTool

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

HACallServiceTool calls a Home Assistant service

func NewHACallServiceTool

func NewHACallServiceTool() *HACallServiceTool

func (*HACallServiceTool) Description

func (t *HACallServiceTool) Description() string

func (*HACallServiceTool) Execute

func (t *HACallServiceTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*HACallServiceTool) Name

func (t *HACallServiceTool) Name() string

func (*HACallServiceTool) Schema

func (t *HACallServiceTool) Schema() map[string]interface{}

type HAConfig

type HAConfig struct {
	URL    string // e.g., "http://homeassistant.local:8123"
	Token  string // Long-lived access token
	Client *http.Client
}

HAConfig holds Home Assistant connection configuration

func NewHAConfig

func NewHAConfig() *HAConfig

NewHAConfig creates a new Home Assistant config from environment

func (*HAConfig) IsConfigured

func (c *HAConfig) IsConfigured() bool

IsConfigured checks if Home Assistant is properly configured

type HAConfigTool

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

HAConfigTool provides Home Assistant system information

func NewHAConfigTool

func NewHAConfigTool() *HAConfigTool

func (*HAConfigTool) Description

func (t *HAConfigTool) Description() string

func (*HAConfigTool) Execute

func (t *HAConfigTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*HAConfigTool) Name

func (t *HAConfigTool) Name() string

func (*HAConfigTool) Schema

func (t *HAConfigTool) Schema() map[string]interface{}

type HAEventsTool

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

HAEventsTool provides Home Assistant event monitoring

func NewHAEventsTool

func NewHAEventsTool() *HAEventsTool

func (*HAEventsTool) Description

func (t *HAEventsTool) Description() string

func (*HAEventsTool) Execute

func (t *HAEventsTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*HAEventsTool) Name

func (t *HAEventsTool) Name() string

func (*HAEventsTool) Schema

func (t *HAEventsTool) Schema() map[string]interface{}

type HAGetStateTool

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

HAGetStateTool gets the state of a specific entity

func NewHAGetStateTool

func NewHAGetStateTool() *HAGetStateTool

func (*HAGetStateTool) Description

func (t *HAGetStateTool) Description() string

func (*HAGetStateTool) Execute

func (t *HAGetStateTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*HAGetStateTool) Name

func (t *HAGetStateTool) Name() string

func (*HAGetStateTool) Schema

func (t *HAGetStateTool) Schema() map[string]interface{}

type HAListServicesTool

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

HAListServicesTool lists available Home Assistant services

func NewHAListServicesTool

func NewHAListServicesTool() *HAListServicesTool

func (*HAListServicesTool) Description

func (t *HAListServicesTool) Description() string

func (*HAListServicesTool) Execute

func (t *HAListServicesTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*HAListServicesTool) Name

func (t *HAListServicesTool) Name() string

func (*HAListServicesTool) Schema

func (t *HAListServicesTool) Schema() map[string]interface{}

type HATool

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

HATool provides Home Assistant smart home control

func NewHATool

func NewHATool() *HATool

func (*HATool) Description

func (t *HATool) Description() string

func (*HATool) Execute

func (t *HATool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*HATool) Name

func (t *HATool) Name() string

func (*HATool) Schema

func (t *HATool) Schema() map[string]interface{}

type HashTool

type HashTool struct {
	BaseTool
}

func NewHashTool

func NewHashTool() *HashTool

func (*HashTool) Execute

func (t *HashTool) Execute(ctx context.Context, args map[string]any) (any, error)

type HelpGenerator

type HelpGenerator struct{}

HelpGenerator 帮助信息生成器

func NewHelpGenerator

func NewHelpGenerator() *HelpGenerator

NewHelpGenerator 创建帮助生成器

func (*HelpGenerator) GenerateAllHelp

func (hg *HelpGenerator) GenerateAllHelp(registry *Registry) string

GenerateAllHelp 生成所有工具的帮助

func (*HelpGenerator) GenerateHelp

func (hg *HelpGenerator) GenerateHelp(tool Tool) string

GenerateHelp 生成帮助文本

type ImageGenerationTool

type ImageGenerationTool struct {
	BaseTool
}

ImageGenerationTool 图片生成工具

func NewImageGenerationTool

func NewImageGenerationTool() *ImageGenerationTool

NewImageGenerationTool 创建图片生成工具

func (*ImageGenerationTool) Execute

func (t *ImageGenerationTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute 生成图片

func (*ImageGenerationTool) ValidateParams

func (t *ImageGenerationTool) ValidateParams(params map[string]interface{}) error

ValidateParams 验证参数

type InMemoryToolCache

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

InMemoryToolCache 内存缓存实现

func NewInMemoryCache

func NewInMemoryCache(maxSize int) *InMemoryToolCache

NewInMemoryCache 创建内存缓存

func (*InMemoryToolCache) Clear

func (c *InMemoryToolCache) Clear()

func (*InMemoryToolCache) Delete

func (c *InMemoryToolCache) Delete(key string)

func (*InMemoryToolCache) Get

func (c *InMemoryToolCache) Get(key string) (*ToolResult, bool)

func (*InMemoryToolCache) Set

func (c *InMemoryToolCache) Set(key string, result *ToolResult, ttl time.Duration)

func (*InMemoryToolCache) Size

func (c *InMemoryToolCache) Size() int

type JSONTool

type JSONTool struct {
	BaseTool
}

func NewJSONTool

func NewJSONTool() *JSONTool

func (*JSONTool) Execute

func (t *JSONTool) Execute(ctx context.Context, args map[string]any) (any, error)

type Job

type Job struct {
	ID        string     `json:"id"`
	Name      string     `json:"name,omitempty"`
	Schedule  string     `json:"schedule"`
	Prompt    string     `json:"prompt"`
	Platform  string     `json:"platform,omitempty"`
	Enabled   bool       `json:"enabled"`
	CreatedAt time.Time  `json:"created_at"`
	LastRun   *time.Time `json:"last_run,omitempty"`
}

Job represents a cron job

type JobStatus

type JobStatus string

JobStatus 异步任务状态

const (
	StatusPending   JobStatus = "pending"
	StatusRunning   JobStatus = "running"
	StatusCompleted JobStatus = "completed"
	StatusFailed    JobStatus = "failed"
	StatusCancelled JobStatus = "cancelled"
)

type KanbanBlockTool

type KanbanBlockTool struct {
	*BaseTool
}

KanbanBlockTool blocks the current task

func NewKanbanBlockTool

func NewKanbanBlockTool() *KanbanBlockTool

NewKanbanBlockTool creates a new kanban block tool

func (*KanbanBlockTool) Execute

func (t *KanbanBlockTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute blocks a task

type KanbanCommentTool

type KanbanCommentTool struct {
	*BaseTool
}

KanbanCommentTool adds a comment to a task

func NewKanbanCommentTool

func NewKanbanCommentTool() *KanbanCommentTool

NewKanbanCommentTool creates a new kanban comment tool

func (*KanbanCommentTool) Execute

func (t *KanbanCommentTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute adds a comment

type KanbanCompleteTool

type KanbanCompleteTool struct {
	*BaseTool
}

KanbanCompleteTool completes the current task

func NewKanbanCompleteTool

func NewKanbanCompleteTool() *KanbanCompleteTool

NewKanbanCompleteTool creates a new kanban complete tool

func (*KanbanCompleteTool) Execute

func (t *KanbanCompleteTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute completes a task

type KanbanCreateTool

type KanbanCreateTool struct {
	*BaseTool
}

KanbanCreateTool creates a new task

func NewKanbanCreateTool

func NewKanbanCreateTool() *KanbanCreateTool

NewKanbanCreateTool creates a new kanban create tool

func (*KanbanCreateTool) Execute

func (t *KanbanCreateTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute creates a task

type KanbanHeartbeatTool

type KanbanHeartbeatTool struct {
	*BaseTool
}

KanbanHeartbeatTool reports task heartbeat

func NewKanbanHeartbeatTool

func NewKanbanHeartbeatTool() *KanbanHeartbeatTool

NewKanbanHeartbeatTool creates a new kanban heartbeat tool

func (*KanbanHeartbeatTool) Execute

func (t *KanbanHeartbeatTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute reports a heartbeat

type KanbanLinkTool

type KanbanLinkTool struct {
	*BaseTool
}

KanbanLinkTool links two tasks as parent-child

func NewKanbanLinkTool

func NewKanbanLinkTool() *KanbanLinkTool

NewKanbanLinkTool creates a new kanban link tool

func (*KanbanLinkTool) Execute

func (t *KanbanLinkTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute links two tasks

type KanbanShowTool

type KanbanShowTool struct {
	*BaseTool
}

KanbanShowTool shows the current task details

func NewKanbanShowTool

func NewKanbanShowTool() *KanbanShowTool

NewKanbanShowTool creates a new kanban show tool

func (*KanbanShowTool) Execute

func (t *KanbanShowTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute shows the task details

type LintResult

type LintResult struct {
	FilePath string   `json:"file_path"`
	Issues   []string `json:"issues,omitempty"`
	Success  bool     `json:"success"`
}

LintResult represents the result of a lint check

func LintFiles

func LintFiles(paths []string) []LintResult

LintFiles checks multiple files and returns aggregated results

type ListFilesTool

type ListFilesTool struct{}

func (*ListFilesTool) Description

func (t *ListFilesTool) Description() string

func (*ListFilesTool) Execute

func (t *ListFilesTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*ListFilesTool) Name

func (t *ListFilesTool) Name() string

func (*ListFilesTool) Schema

func (t *ListFilesTool) Schema() map[string]interface{}

type ListTasksTool

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

ListTasksTool lists all sub-agent tasks

func NewListTasksTool

func NewListTasksTool() *ListTasksTool

NewListTasksTool creates a new list tasks tool

func (*ListTasksTool) Description

func (t *ListTasksTool) Description() string

func (*ListTasksTool) Execute

func (t *ListTasksTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute lists tasks

func (*ListTasksTool) Name

func (t *ListTasksTool) Name() string

func (*ListTasksTool) Schema

func (t *ListTasksTool) Schema() map[string]interface{}

type LocalBackend

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

LocalBackend executes commands locally

func NewLocalBackend

func NewLocalBackend() *LocalBackend

func (*LocalBackend) Description

func (b *LocalBackend) Description() string

func (*LocalBackend) Execute

func (b *LocalBackend) Execute(ctx context.Context, cmd string, workDir string, timeout time.Duration) (*ExecutionResult, error)

func (*LocalBackend) Health

func (b *LocalBackend) Health() error

func (*LocalBackend) IsAvailable

func (b *LocalBackend) IsAvailable() bool

func (*LocalBackend) Name

func (b *LocalBackend) Name() string

func (*LocalBackend) SetAllowAny

func (b *LocalBackend) SetAllowAny(allow bool)

type Logger

type Logger interface {
	LogToolExecution(name string, params, result map[string]interface{}, duration time.Duration, err error)
}

Logger 工具日志接口

type LongRunningTool

type LongRunningTool struct {
	BaseTool
	// contains filtered or unexported fields
}

LongRunningTool 长时运行工具示例

func NewLongRunningTool

func NewLongRunningTool(executor *AsyncToolExecutor) *LongRunningTool

NewLongRunningTool 创建长时运行工具

func (*LongRunningTool) Cancel

func (t *LongRunningTool) Cancel(jobID string) error

func (*LongRunningTool) Result

func (t *LongRunningTool) Result(jobID string) (*ToolResult, error)

func (*LongRunningTool) Start

func (t *LongRunningTool) Start(ctx context.Context, params map[string]any) (string, error)

func (*LongRunningTool) Status

func (t *LongRunningTool) Status(jobID string) (JobStatus, error)

type Match

type Match struct {
	File    string   `json:"file"`
	Line    int      `json:"line"`
	Column  int      `json:"column,omitempty"`
	Content string   `json:"content"`
	Context []string `json:"context,omitempty"`
}

Match 结构体表示单个匹配

type MathTool

type MathTool struct {
	BaseTool
}

func NewMathTool

func NewMathTool() *MathTool

func (*MathTool) Execute

func (t *MathTool) Execute(ctx context.Context, args map[string]any) (any, error)

type MemoryRecallTool

type MemoryRecallTool struct{}

func (*MemoryRecallTool) Description

func (t *MemoryRecallTool) Description() string

func (*MemoryRecallTool) Execute

func (t *MemoryRecallTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*MemoryRecallTool) Name

func (t *MemoryRecallTool) Name() string

func (*MemoryRecallTool) Schema

func (t *MemoryRecallTool) Schema() map[string]interface{}

type MemoryStoreTool

type MemoryStoreTool struct{}

func (*MemoryStoreTool) Description

func (t *MemoryStoreTool) Description() string

func (*MemoryStoreTool) Execute

func (t *MemoryStoreTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*MemoryStoreTool) Name

func (t *MemoryStoreTool) Name() string

func (*MemoryStoreTool) Schema

func (t *MemoryStoreTool) Schema() map[string]interface{}

type MetricsRecorder

type MetricsRecorder interface {
	RecordToolExecution(toolName string, duration time.Duration, success bool, errorMsg string)
	RecordToolMetric(toolName string, metricName string, value float64)
}

MetricsRecorder 指标记录器接口

type Middleware

type Middleware func(next ToolFunc) ToolFunc

Middleware 中间件函数类型

func CacheMiddleware

func CacheMiddleware(cache ToolCache, ttl time.Duration) Middleware

func ChainMiddlewares

func ChainMiddlewares(middlewares ...Middleware) Middleware

ChainMiddlewares 将多个中间件链接成一个

func LoggingMiddleware

func LoggingMiddleware(logger Logger) Middleware

func MetricsMiddleware

func MetricsMiddleware(recorder MetricsRecorder) Middleware

func PanicRecoveryMiddleware

func PanicRecoveryMiddleware() Middleware

func RateLimitMiddleware

func RateLimitMiddleware(rate float64, burst int) Middleware

func RetryMiddleware

func RetryMiddleware(opts ...RetryOptions) Middleware

func TimeoutMiddleware

func TimeoutMiddleware(defaultTimeout time.Duration) Middleware

func ValidationMiddleware

func ValidationMiddleware() Middleware

type ModalBackend

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

ModalBackend executes commands via Modal (serverless GPU/CPUs)

func NewModalBackend

func NewModalBackend() *ModalBackend

func (*ModalBackend) Configure

func (b *ModalBackend) Configure(appName, volumePath, gpu string, memory int, cpu float64)

func (*ModalBackend) Description

func (b *ModalBackend) Description() string

func (*ModalBackend) Execute

func (b *ModalBackend) Execute(ctx context.Context, cmd string, workDir string, timeout time.Duration) (*ExecutionResult, error)

func (*ModalBackend) Health

func (b *ModalBackend) Health() error

func (*ModalBackend) IsAvailable

func (b *ModalBackend) IsAvailable() bool

func (*ModalBackend) Name

func (b *ModalBackend) Name() string

func (*ModalBackend) SetGPU

func (b *ModalBackend) SetGPU(gpu string)

func (*ModalBackend) SetMemory

func (b *ModalBackend) SetMemory(memory int)

type ParamValidator

type ParamValidator interface {
	ValidateParams(params map[string]interface{}) error
}

ParamValidator 参数验证器接口

type PluginTool

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

PluginTool wraps a plugin command as a Tool that the agent can call. When the agent invokes this tool, it executes the plugin's entrypoint with the command name and arguments.

func NewPluginTool

func NewPluginTool(pluginID, entrypoint string, command string, desc string, argNames []string) *PluginTool

NewPluginTool creates a tool from a plugin command spec

func (*PluginTool) Description

func (t *PluginTool) Description() string

func (*PluginTool) Execute

func (t *PluginTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

func (*PluginTool) Name

func (t *PluginTool) Name() string

func (*PluginTool) Schema

func (t *PluginTool) Schema() map[string]interface{}

type PluginToolLoader

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

PluginToolLoader discovers plugins and creates PluginTool instances from their manifest commands.

func (*PluginToolLoader) DiscoverTools

func (l *PluginToolLoader) DiscoverTools() []Tool

DiscoverTools scans the plugin directory and creates PluginTool instances for every command declared in every plugin manifest.

type PollTaskTool

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

PollTaskTool polls for sub-agent task results

func NewPollTaskTool

func NewPollTaskTool() *PollTaskTool

NewPollTaskTool creates a new poll task tool

func (*PollTaskTool) Description

func (t *PollTaskTool) Description() string

func (*PollTaskTool) Execute

func (t *PollTaskTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute polls for task status

func (*PollTaskTool) Name

func (t *PollTaskTool) Name() string

func (*PollTaskTool) Schema

func (t *PollTaskTool) Schema() map[string]interface{}

type ProcessInfo

type ProcessInfo struct {
	ID      string    `json:"id"`
	Command string    `json:"command"`
	Backend string    `json:"backend"`
	WorkDir string    `json:"workdir"`
	PID     int       `json:"pid"`
	Start   time.Time `json:"start"`
	Status  string    `json:"status"`
}

type ProcessTool

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

ProcessTool manages background processes

func NewProcessTool

func NewProcessTool() *ProcessTool

func (*ProcessTool) Description

func (t *ProcessTool) Description() string

func (*ProcessTool) Execute

func (t *ProcessTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*ProcessTool) Name

func (t *ProcessTool) Name() string

func (*ProcessTool) Schema

func (t *ProcessTool) Schema() map[string]interface{}

type RandomTool

type RandomTool struct {
	BaseTool
}

func NewRandomTool

func NewRandomTool() *RandomTool

func (*RandomTool) Execute

func (t *RandomTool) Execute(ctx context.Context, args map[string]any) (any, error)

type RateLimiter

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

func NewRateLimiter

func NewRateLimiter() *RateLimiter

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(toolName string, rate float64, burst int) bool

type ReadFileTool

type ReadFileTool struct{}

func (*ReadFileTool) Description

func (t *ReadFileTool) Description() string

func (*ReadFileTool) Execute

func (t *ReadFileTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*ReadFileTool) Name

func (t *ReadFileTool) Name() string

func (*ReadFileTool) Schema

func (t *ReadFileTool) Schema() map[string]interface{}

type Registry

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

Registry 管理工具注册和执行

func NewRegistry

func NewRegistry() *Registry

NewRegistry 创建一个新的工具注册表

func (*Registry) CleanupDynamic

func (r *Registry) CleanupDynamic()

CleanupDynamic 清理过期的动态工具

func (*Registry) Count

func (r *Registry) Count() int

Count 返回已注册工具数量

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, name string, args map[string]interface{}) (interface{}, error)

Execute 执行工具

func (*Registry) ExecuteSafe

func (r *Registry) ExecuteSafe(ctx context.Context, name string, args map[string]interface{}) ToolExecutionResult

ExecuteSafe 安全执行工具,捕获所有错误

func (*Registry) ExecuteWithTimeout

func (r *Registry) ExecuteWithTimeout(ctx context.Context, name string, args map[string]interface{}, timeout time.Duration) (interface{}, error)

ExecuteWithTimeout 执行工具并指定超时时间

func (*Registry) FilterToolsByKeyword

func (r *Registry) FilterToolsByKeyword(keyword string) []Tool

FilterToolsByKeyword 按关键词过滤工具

func (*Registry) FilterToolsByPrefix

func (r *Registry) FilterToolsByPrefix(prefix string) []Tool

FilterToolsByPrefix 按前缀过滤工具

func (*Registry) Get

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

Get 获取工具实例

func (*Registry) GetTimeout

func (r *Registry) GetTimeout(name string) time.Duration

GetTimeout 获取工具的默认超时时间

func (*Registry) GetToolInfo

func (r *Registry) GetToolInfo(name string) (*ToolInfo, error)

GetToolInfo 获取工具信息

func (*Registry) HasTool

func (r *Registry) HasTool(name string) bool

HasTool 检查工具是否已注册

func (*Registry) List

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

List 返回所有已注册的工具名称

func (*Registry) ListWithSchemas

func (r *Registry) ListWithSchemas() []map[string]interface{}

ListWithSchemas 返回所有工具及其 Schema

func (*Registry) Register

func (r *Registry) Register(t Tool)

Register 注册一个工具

func (*Registry) RegisterAll

func (r *Registry) RegisterAll(workDir string)

RegisterAll 注册所有内置工具

func (*Registry) RegisterDynamic

func (r *Registry) RegisterDynamic(tool Tool, ttl time.Duration)

RegisterDynamic 注册一个动态工具(带 TTL)

func (*Registry) RegisterOptionalTools

func (r *Registry) RegisterOptionalTools()

RegisterOptionalTools registers tools that require external API configuration. These are not registered by default to avoid confusing the LLM with non-functional placeholder tools.

func (*Registry) RegisterSkillTool

func (r *Registry) RegisterSkillTool(provider SkillInfoProvider)

RegisterSkillTool 注册技能工具(带 SkillInfoProvider)

func (*Registry) RegisterWithSkillManager

func (r *Registry) RegisterWithSkillManager(skillManager SkillInfoProvider, workDir string)

RegisterWithSkillManager 注册所有工具,包括技能工具

func (*Registry) SetLogger

func (r *Registry) SetLogger(logger Logger)

SetLogger 设置日志处理器

func (*Registry) SetTimeout

func (r *Registry) SetTimeout(name string, timeout time.Duration)

SetTimeout 设置工具的默认超时时间

func (*Registry) Unregister

func (r *Registry) Unregister(name string)

Unregister 注销一个工具

type RetryOptions

type RetryOptions struct {
	MaxAttempts int                               // 最大重试次数
	InitialWait time.Duration                     // 初始等待时间
	MaxWait     time.Duration                     // 最大等待时间
	Multiplier  float64                           // 退避倍数
	ShouldRetry func(err error, attempt int) bool // 判断是否重试
}

type SSHBackend

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

SSHBackend executes commands over SSH

func NewSSHBackend

func NewSSHBackend() *SSHBackend

func (*SSHBackend) Configure

func (b *SSHBackend) Configure(host, user, keyPath, password string, port int)

func (*SSHBackend) Description

func (b *SSHBackend) Description() string

func (*SSHBackend) Execute

func (b *SSHBackend) Execute(ctx context.Context, cmd string, workDir string, timeout time.Duration) (*ExecutionResult, error)

func (*SSHBackend) Health

func (b *SSHBackend) Health() error

func (*SSHBackend) IsAvailable

func (b *SSHBackend) IsAvailable() bool

func (*SSHBackend) Name

func (b *SSHBackend) Name() string

type SearchInFilesTool

type SearchInFilesTool struct{}

func (*SearchInFilesTool) Description

func (t *SearchInFilesTool) Description() string

func (*SearchInFilesTool) Execute

func (t *SearchInFilesTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*SearchInFilesTool) Name

func (t *SearchInFilesTool) Name() string

func (*SearchInFilesTool) Schema

func (t *SearchInFilesTool) Schema() map[string]interface{}

type SearchResult

type SearchResult struct {
	Pattern      string  `json:"pattern"`
	Path         string  `json:"path"`
	TotalFiles   int     `json:"total_files"`
	TotalMatches int     `json:"total_matches"`
	Matches      []Match `json:"matches"`
}

SearchResult 搜索结果

type SessionSearchTool

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

SessionSearchTool searches through past conversation sessions

func GetSessionSearchTool

func GetSessionSearchTool() *SessionSearchTool

GetSessionSearchTool creates a new session search tool

func (*SessionSearchTool) Description

func (t *SessionSearchTool) Description() string

Description returns the tool description

func (*SessionSearchTool) Execute

func (t *SessionSearchTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute performs the session search

func (*SessionSearchTool) Name

func (t *SessionSearchTool) Name() string

Name returns the tool name

func (*SessionSearchTool) Parameters

func (t *SessionSearchTool) Parameters() map[string]interface{}

func (*SessionSearchTool) Schema

func (t *SessionSearchTool) Schema() map[string]interface{}

Parameters returns the tool parameters schema

type SingularityBackend

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

SingularityBackend executes commands in Singularity containers

func NewSingularityBackend

func NewSingularityBackend() *SingularityBackend

func (*SingularityBackend) Configure

func (b *SingularityBackend) Configure(imagePath string, bindPaths []string, overlayPath string)

func (*SingularityBackend) Description

func (b *SingularityBackend) Description() string

func (*SingularityBackend) Execute

func (b *SingularityBackend) Execute(ctx context.Context, cmd string, workDir string, timeout time.Duration) (*ExecutionResult, error)

func (*SingularityBackend) Health

func (b *SingularityBackend) Health() error

func (*SingularityBackend) IsAvailable

func (b *SingularityBackend) IsAvailable() bool

func (*SingularityBackend) Name

func (b *SingularityBackend) Name() string

func (*SingularityBackend) SetContain

func (b *SingularityBackend) SetContain(contain bool)

type SkillData

type SkillData map[string]interface{}

SkillData represents skill data as a map to avoid circular imports

type SkillInfoProvider

type SkillInfoProvider interface {
	ListSkills() []string
	GetSkillInfo(name string) (description string, tools []string, content string, err error)
}

SkillInfoProvider 技能信息提供者接口(用于解耦循环依赖)

type SkillInvokeTool

type SkillInvokeTool struct {
	BaseTool
	// contains filtered or unexported fields
}

SkillInvokeTool 技能调用工具

func NewSkillInvokeTool

func NewSkillInvokeTool(provider SkillInfoProvider) *SkillInvokeTool

NewSkillInvokeTool 创建技能调用工具

func (*SkillInvokeTool) Execute

func (t *SkillInvokeTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute 执行技能调用

func (*SkillInvokeTool) ValidateParams

func (t *SkillInvokeTool) ValidateParams(params map[string]interface{}) error

ValidateParams 实现 ParamValidator 接口

type SkillListTool

type SkillListTool struct {
	*BaseTool
	// contains filtered or unexported fields
}

SkillListTool lists all available skills

func NewSkillListTool

func NewSkillListTool() *SkillListTool

NewSkillListTool creates a new skill list tool

func (*SkillListTool) Execute

func (t *SkillListTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute lists all skills

func (*SkillListTool) MarshalJSON

func (t *SkillListTool) MarshalJSON() ([]byte, error)

MarshalJSON for SkillListTool

func (*SkillListTool) SetManager

func (t *SkillListTool) SetManager(mgr SkillsManager)

SetManager sets the skills manager

type SkillManageTool

type SkillManageTool struct {
	*BaseTool
	// contains filtered or unexported fields
}

SkillManageTool allows creating, updating, and deleting skills

func NewSkillManageTool

func NewSkillManageTool() *SkillManageTool

NewSkillManageTool creates a new skill manage tool

func (*SkillManageTool) Execute

func (t *SkillManageTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute manages skills

func (*SkillManageTool) MarshalJSON

func (t *SkillManageTool) MarshalJSON() ([]byte, error)

MarshalJSON for SkillManageTool

func (*SkillManageTool) SetManager

func (t *SkillManageTool) SetManager(mgr SkillsManager)

SetManager sets the skills manager

type SkillViewTool

type SkillViewTool struct {
	*BaseTool
	// contains filtered or unexported fields
}

SkillViewTool shows detailed information about a skill

func NewSkillViewTool

func NewSkillViewTool() *SkillViewTool

NewSkillViewTool creates a new skill view tool

func (*SkillViewTool) Execute

func (t *SkillViewTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute returns skill information

func (*SkillViewTool) MarshalJSON

func (t *SkillViewTool) MarshalJSON() ([]byte, error)

MarshalJSON for SkillViewTool

func (*SkillViewTool) SetManager

func (t *SkillViewTool) SetManager(mgr SkillsManager)

SetManager sets the skills manager

type SkillsManager

type SkillsManager interface {
	List() map[string]SkillData
	Get(name string) (SkillData, error)
	GetCategories() []string
	GetSkillDir(name string) (string, error)
	Create(name, description, content, category string, tags []string) (SkillData, error)
	Update(name, content string) error
	Delete(name string) error
}

SkillsManager interface for skills manager

type StringTool

type StringTool struct {
	BaseTool
}

func NewStringTool

func NewStringTool() *StringTool

func (*StringTool) Execute

func (t *StringTool) Execute(ctx context.Context, args map[string]any) (any, error)

type SubAgent

type SubAgent struct {
	ID       string                 `json:"id"`
	Task     string                 `json:"task"`
	Status   string                 `json:"status"` // "pending", "running", "completed", "failed"
	Result   string                 `json:"result,omitempty"`
	Error    string                 `json:"error,omitempty"`
	Created  time.Time              `json:"created"`
	Finished *time.Time             `json:"finished,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

SubAgent represents a delegated sub-agent task

type SubAgentManager

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

SubAgentManager manages sub-agent tasks

func GetSubAgentManager

func GetSubAgentManager() *SubAgentManager

GetSubAgentManager returns the global sub-agent manager

type SystemInfoTool

type SystemInfoTool struct {
	BaseTool
}

func NewSystemInfoTool

func NewSystemInfoTool() *SystemInfoTool

func (*SystemInfoTool) Execute

func (t *SystemInfoTool) Execute(ctx context.Context, args map[string]any) (any, error)

type TTLCache

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

func NewTTLCache

func NewTTLCache(defaultTTL time.Duration) *TTLCache

func (*TTLCache) Clear

func (c *TTLCache) Clear()

func (*TTLCache) Delete

func (c *TTLCache) Delete(key string)

func (*TTLCache) Get

func (c *TTLCache) Get(key string) (*ToolResult, bool)

func (*TTLCache) Set

func (c *TTLCache) Set(key string, result *ToolResult, ttl time.Duration)

func (*TTLCache) Size

func (c *TTLCache) Size() int

type TTSTool

type TTSTool struct {
	BaseTool
}

TTSTool 文字转语音工具

func NewTTSTool

func NewTTSTool() *TTSTool

NewTTSTool 创建 TTS 工具

func (*TTSTool) Execute

func (t *TTSTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute 执行 TTS

func (*TTSTool) ValidateParams

func (t *TTSTool) ValidateParams(params map[string]interface{}) error

ValidateParams 验证参数

type TerminalBackend

type TerminalBackend interface {
	// Name returns the backend name
	Name() string

	// Description returns the backend description
	Description() string

	// Execute runs a command in the backend
	Execute(ctx context.Context, cmd string, workDir string, timeout time.Duration) (*ExecutionResult, error)

	// IsAvailable checks if the backend is available
	IsAvailable() bool

	// Health checks the backend health
	Health() error
}

TerminalBackend defines the interface for different terminal execution backends

type TerminalTool

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

TerminalTool provides enhanced terminal execution with backend support

func NewTerminalTool

func NewTerminalTool() *TerminalTool

func (*TerminalTool) Description

func (t *TerminalTool) Description() string

func (*TerminalTool) Execute

func (t *TerminalTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*TerminalTool) Name

func (t *TerminalTool) Name() string

func (*TerminalTool) Schema

func (t *TerminalTool) Schema() map[string]interface{}

type TimeTool

type TimeTool struct {
	BaseTool
}

func NewTimeTool

func NewTimeTool() *TimeTool

func (*TimeTool) Execute

func (t *TimeTool) Execute(ctx context.Context, args map[string]any) (any, error)

type TodoItem

type TodoItem struct {
	ID          string     `json:"id"`
	Title       string     `json:"title"`
	Description string     `json:"description,omitempty"`
	Status      string     `json:"status"`             // pending, in_progress, completed, cancelled
	Priority    string     `json:"priority,omitempty"` // low, medium, high
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
	CompletedAt *time.Time `json:"completed_at,omitempty"`
}

TodoItem represents a single todo item

type TodoTool

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

TodoTool manages todo items

func GetTodoTool

func GetTodoTool() *TodoTool

GetTodoTool returns the singleton todo tool

func (*TodoTool) Description

func (t *TodoTool) Description() string

Description returns the tool description

func (*TodoTool) Execute

func (t *TodoTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute performs the todo action

func (*TodoTool) Name

func (t *TodoTool) Name() string

Name returns the tool name

func (*TodoTool) Parameters

func (t *TodoTool) Parameters() map[string]interface{}

func (*TodoTool) Schema

func (t *TodoTool) Schema() map[string]interface{}

Parameters returns the tool parameters schema

type Tool

type Tool interface {
	// Name 返回工具名称
	Name() string
	// Description 返回工具描述
	Description() string
	// Schema 返回 OpenAI function calling 格式的 JSON Schema
	Schema() map[string]interface{}
	// Execute 执行工具,返回结果或错误
	Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)
}

Tool 定义所有工具的统一接口(参考 PicoClaw 设计)

func GetAllTools

func GetAllTools() []Tool

GetAllTools 返回所有内置工具实例

func GetEnabledTools

func GetEnabledTools(registry *Registry, enabledToolsets []string) []Tool

GetEnabledTools returns tools based on enabled toolsets

type ToolCache

type ToolCache interface {
	// Get 获取缓存结果
	Get(key string) (*ToolResult, bool)
	// Set 设置缓存结果
	Set(key string, result *ToolResult, ttl time.Duration)
	// Delete 删除缓存
	Delete(key string)
	// Clear 清空缓存
	Clear()
	// Size 返回缓存条目数
	Size() int
}

ToolCache 工具结果缓存接口

type ToolContext

type ToolContext struct {
	context.Context
	SessionID string          // 会话ID
	UserID    string          // 用户ID
	RequestID string          // 请求ID
	ToolName  string          // 当前工具名称
	Metadata  map[string]any  // 元数据
	Logger    Logger          // 日志器
	Metrics   MetricsRecorder // 指标记录器
	StartTime time.Time       // 开始时间
}

ToolContext 工具执行上下文,扩展标准 context.Context

func FromContext

func FromContext(ctx context.Context) *ToolContext

FromContext 从 context.Context 获取 ToolContext

func NewToolContext

func NewToolContext(parent context.Context) *ToolContext

NewToolContext 创建工具上下文

func (*ToolContext) Elapsed

func (tc *ToolContext) Elapsed() time.Duration

Elapsed 返回已用时间

func (*ToolContext) GetMetadata

func (tc *ToolContext) GetMetadata(key string) (any, bool)

GetMetadata 获取元数据

func (*ToolContext) SetMetadata

func (tc *ToolContext) SetMetadata(key string, value any)

SetMetadata 设置元数据

func (*ToolContext) ToContext

func (tc *ToolContext) ToContext() context.Context

ToContext 将 ToolContext 转为标准 context.Context

func (*ToolContext) WithLogger

func (tc *ToolContext) WithLogger(logger Logger) *ToolContext

WithLogger 设置日志器

func (*ToolContext) WithMetrics

func (tc *ToolContext) WithMetrics(metrics MetricsRecorder) *ToolContext

WithMetrics 设置指标记录器

func (*ToolContext) WithRequest

func (tc *ToolContext) WithRequest(requestID string) *ToolContext

WithRequest 设置请求ID

func (*ToolContext) WithSession

func (tc *ToolContext) WithSession(sessionID string) *ToolContext

WithSession 设置会话ID

func (*ToolContext) WithTool

func (tc *ToolContext) WithTool(toolName string) *ToolContext

WithTool 设置工具名称

func (*ToolContext) WithUser

func (tc *ToolContext) WithUser(userID string) *ToolContext

WithUser 设置用户ID

type ToolExecutionResult

type ToolExecutionResult struct {
	ToolName  string
	Params    map[string]interface{}
	Result    interface{}
	Error     error
	Duration  time.Duration
	Recovered bool // 是否从 panic 中恢复
}

ToolExecutionResult 工具执行结果

type ToolExecutor

type ToolExecutor interface {
	ExecuteWithProtection(ctx context.Context, tool Tool, params map[string]interface{}, timeout time.Duration) ToolExecutionResult
}

ToolExecutor 工具执行器接口

type ToolFunc

type ToolFunc func(ctx context.Context, params map[string]any) (*ToolResult, error)

ToolFunc 工具执行函数类型

type ToolGroup

type ToolGroup struct {
	Name        string         // 分组名称
	Description string         // 分组描述
	Tools       []Tool         // 分组中的工具
	Enabled     bool           // 是否启用
	Metadata    map[string]any // 分组元数据
}

ToolGroup 工具分组

func NewToolGroup

func NewToolGroup(name, description string) *ToolGroup

NewToolGroup 创建新的工具分组

func (*ToolGroup) Add

func (g *ToolGroup) Add(tool Tool)

Add 添加工具到分组

func (*ToolGroup) Count

func (g *ToolGroup) Count() int

Count 返回分组中的工具数量

func (*ToolGroup) Get

func (g *ToolGroup) Get(toolName string) Tool

Get 获取分组中的工具

func (*ToolGroup) Remove

func (g *ToolGroup) Remove(toolName string) bool

Remove 从分组移除工具

type ToolInfo

type ToolInfo struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Schema      map[string]interface{} `json:"schema"`
}

ToolInfo 工具信息

func (*ToolInfo) FromTool

func (ti *ToolInfo) FromTool(tool Tool) *ToolInfo

FromTool 从 Tool 创建 ToolInfo

func (*ToolInfo) ToJSON

func (ti *ToolInfo) ToJSON() string

ToJSON 将工具信息转为 JSON 字符串

type ToolResult

type ToolResult struct {
	Success   bool           // 是否成功
	Data      any            // 结果数据
	Error     string         // 错误信息
	ErrorCode string         // 错误码
	Metadata  map[string]any // 执行元数据
	Duration  time.Duration  // 执行耗时
	Warnings  []string       // 警告信息
}

ToolResult 标准化工具执行结果

func NewErrorResult

func NewErrorResult(err string) *ToolResult

NewErrorResult 创建错误结果

func NewErrorResultWithCode

func NewErrorResultWithCode(err string, code string) *ToolResult

NewErrorResultWithCode 创建带错误码的结果

func NewSuccessResult

func NewSuccessResult(data any) *ToolResult

NewSuccessResult 创建成功结果

func (*ToolResult) AddWarning

func (r *ToolResult) AddWarning(warning string) *ToolResult

AddWarning 添加警告

func (*ToolResult) IsSuccess

func (r *ToolResult) IsSuccess() bool

IsSuccess 检查是否成功

func (*ToolResult) ToMap

func (r *ToolResult) ToMap() map[string]any

ToMap 转换为 map

func (*ToolResult) WithDuration

func (r *ToolResult) WithDuration(d time.Duration) *ToolResult

WithDuration 设置执行耗时

func (*ToolResult) WithMetadata

func (r *ToolResult) WithMetadata(key string, value any) *ToolResult

WithMetadata 添加元数据

type ToolSchema

type ToolSchema struct{}

ToolSchema 工具 Schema 转换工具

func (*ToolSchema) ToOpenAISchema

func (ts *ToolSchema) ToOpenAISchema(tool Tool) map[string]interface{}

ToOpenAISchema 将工具转换为 OpenAI function calling 格式

func (*ToolSchema) ToOpenAISchemas

func (ts *ToolSchema) ToOpenAISchemas(tools []Tool) []map[string]interface{}

ToOpenAISchemas 批量转换工具为 OpenAI 格式

type ToolsetDefinition

type ToolsetDefinition struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Tools       []string `json:"tools"`
	Includes    []string `json:"includes"` // Include other toolsets
}

ToolsetDefinition defines a named group of tools

func GetToolset

func GetToolset(name string) *ToolsetDefinition

GetToolset returns a toolset by name

type TreeNode

type TreeNode struct {
	Name     string      `json:"name"`
	Type     string      `json:"type"` // "file" or "directory"
	Path     string      `json:"path"`
	Children []*TreeNode `json:"children,omitempty"`
	Size     int64       `json:"size,omitempty"`
	Mode     string      `json:"mode,omitempty"`
}

type UUIDTool

type UUIDTool struct {
	BaseTool
}

func NewUUIDTool

func NewUUIDTool() *UUIDTool

func (*UUIDTool) Execute

func (t *UUIDTool) Execute(ctx context.Context, args map[string]any) (any, error)

type VideoAnalyzeTool

type VideoAnalyzeTool struct {
	BaseTool
}

VideoAnalyzeTool 视频理解工具

func NewVideoAnalyzeTool

func NewVideoAnalyzeTool() *VideoAnalyzeTool

NewVideoAnalyzeTool 创建视频理解工具

func (*VideoAnalyzeTool) Execute

func (t *VideoAnalyzeTool) Execute(ctx context.Context, params map[string]interface{}) (interface{}, error)

Execute 分析视频内容

type WebExtractTool

type WebExtractTool struct{}

func (*WebExtractTool) Description

func (t *WebExtractTool) Description() string

func (*WebExtractTool) Execute

func (t *WebExtractTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*WebExtractTool) Name

func (t *WebExtractTool) Name() string

func (*WebExtractTool) Schema

func (t *WebExtractTool) Schema() map[string]interface{}

type WebFetchTool

type WebFetchTool struct{}

WebFetchTool fetches and parses web pages using goquery

func NewWebFetchTool

func NewWebFetchTool() *WebFetchTool

NewWebFetchTool creates a new web fetch tool

func (*WebFetchTool) Description

func (t *WebFetchTool) Description() string

func (*WebFetchTool) Execute

func (t *WebFetchTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*WebFetchTool) Name

func (t *WebFetchTool) Name() string

func (*WebFetchTool) Schema

func (t *WebFetchTool) Schema() map[string]interface{}

type WebSearchResult

type WebSearchResult struct {
	Title   string `json:"title"`
	URL     string `json:"url"`
	Snippet string `json:"snippet"`
}

WebSearchResult represents a web search result

type WebSearchTool

type WebSearchTool struct{}

func (*WebSearchTool) Description

func (t *WebSearchTool) Description() string

func (*WebSearchTool) Execute

func (t *WebSearchTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*WebSearchTool) Name

func (t *WebSearchTool) Name() string

func (*WebSearchTool) Parameters

func (t *WebSearchTool) Parameters() map[string]interface{}

func (*WebSearchTool) Schema

func (t *WebSearchTool) Schema() map[string]interface{}

type WebSelectTool

type WebSelectTool struct{}

WebSelectTool extracts specific elements from web pages

func NewWebSelectTool

func NewWebSelectTool() *WebSelectTool

NewWebSelectTool creates a new web select tool

func (*WebSelectTool) Description

func (t *WebSelectTool) Description() string

func (*WebSelectTool) Execute

func (t *WebSelectTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*WebSelectTool) Name

func (t *WebSelectTool) Name() string

func (*WebSelectTool) Schema

func (t *WebSelectTool) Schema() map[string]interface{}

type WriteFileTool

type WriteFileTool struct{}

func (*WriteFileTool) Description

func (t *WriteFileTool) Description() string

func (*WriteFileTool) Execute

func (t *WriteFileTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*WriteFileTool) Name

func (t *WriteFileTool) Name() string

func (*WriteFileTool) Schema

func (t *WriteFileTool) Schema() map[string]interface{}

type YAMLTool

type YAMLTool struct {
	BaseTool
}

func NewYAMLTool

func NewYAMLTool() *YAMLTool

func (*YAMLTool) Execute

func (t *YAMLTool) Execute(ctx context.Context, args map[string]any) (any, error)

Jump to

Keyboard shortcuts

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