Help us shape the future of Go! Take the 2026 Go Developer Survey

tool

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 59 Imported by: 0

README

LuckyAgent Tools

An independent Go module for tool registration, execution contracts, generic builtins, Skills and MCP clients. It does not import the LuckyAgent runtime.

github.com/yurika0211/luckyagent-tools

The root package is named tool. Its implementations were extracted from LuckyAgent and retain the original MIT license and attribution.

go get github.com/yurika0211/luckyagent-tools@v0.2.2

Embed a tool registry

package main

import (
    "fmt"

    tool "github.com/yurika0211/luckyagent-tools"
)

func main() {
    registry := tool.NewRegistry()
    registry.Register(&tool.Tool{
        Name:       "echo",
        Permission: tool.PermAuto,
        Parameters: map[string]tool.Param{"text": {Type: "string", Required: true}},
        Handler: func(args map[string]any) (string, error) {
            return fmt.Sprint(args["text"]), nil
        },
    })
    output, err := registry.Call("echo", map[string]any{"text": "hello"})
    if err != nil {
        panic(err)
    }
    fmt.Println(output)
}

RegisterBuiltinTools registers the standalone catalog. Applications may also register individual factories, use RegisterBuiltinToolsWithConfig for search and OpenCLI options, and provide callbacks to memory/RAG tool definitions. Unconfigured callbacks keep their existing unavailable-service responses.

Ownership

Package Responsibilities
Root tool Tool/Param contracts, registry and function schemas, routing, execution context, gateway, subscriptions and usage tracking
Root builtin factories Shell, files and Office documents, search/fetch, HTTP, time, calculation, structured data and SQLite queries, OpenCLI
Root Skill APIs Discovery, parsing, lifecycle, execution, documentation reads, archive staging, scanning and installation confirmation
Root MCP APIs MCP server configuration, tool discovery, registration and calls
search Search engines and result aggregation
sandbox Execution mode, task snapshots, path checks and isolated shell commands
opencli Host-independent OpenCLI configuration DTO
textutil Shared text, HTML and URL formatting helpers
Root runtime services Memory/RAG handlers, delegation/autonomy tool adapters, cron/heartbeat tools, media/computer tools, temporary credential tools and coding-agent bridges
memory, rag, credentials, chat Neutral backend ports, shared data and credential identifier validation
task, collab, autonomy Deprecated compatibility aliases to the independent luckyagent-orchestrator engines
cron Generic scheduled job engine
computer, multimodal, codex, grok Optional desktop/media providers and external coding-agent clients
approval, hitl Neutral approval values and runtime-scoped human approval/input waits
skillroute Matching immutable skill descriptions to natural-language requests
execpolicy Turn-local intent constraints and tool-call decisions using the task policy decision contract
compact Chunking, text-only parallel summaries, validation, local fallback and restoration evidence
workflow DAG execution with host-supplied action handlers and no HTTP framework dependency

The embedding host owns tool selection, approval prompts, Agent execution, memory/RAG persistence, credential storage, provider selection and lifecycle. Reusable execution, validation and rendering live here. Permission metadata and deny/sandbox checks are preserved; dispatch itself does not ask a human for approval. The host resolves PermApprove before calling a handler.

Task storage, collaboration, autonomy and ordinary-delegation management now live in github.com/yurika0211/luckyagent-orchestrator. This SDK retains tool definitions and public compatibility names. See orchestration adapters for ownership, the v0.1.0 engine dependency and local development.

Defaults preserve LuckyAgent-compatible file roots and environment behavior. Filesystem read policies and task sandbox snapshots remain explicit inputs; this extraction does not broaden file or network access. The SQLite builtin uses go-sqlite3 and therefore requires CGO for database operations.

Development

go test ./...
go test -race ./...

Tests moved with the generic implementations. Application adapter tests remain in LuckyAgent's internal/toolapp; a boundary test rejects imports from the LuckyAgent host, and the embedding example is executed as a Go example test.

LuckyAgent retains aliases at internal/tool, internal/tool/search, internal/sandbox and the moved formatting helpers in internal/utils. Platform and model application services use the same shared tool types.

Inject application capabilities

The execution packages above do not import the root tool catalog, the host, or API/gateway modules. hitl.New creates one broker per runtime identity and notifies the caller with a neutral pending value; the caller renders it and resolves replies. Credential input still requires a masked form. Existing root ApprovalOption and PendingApproval remain aliases of the shared values.

skillroute.Match accepts skill descriptors and returns an original-slice index, score, explicit-name flag and reason, or nil for weak/ambiguous matches. execpolicy.New accepts per-turn disabled tools/actions; Evaluate reuses task.PolicyDecision, while approvals, quotas and actual dispatch stay in the runtime. Neither package loads configuration or executes tools.

compact.New accepts an estimator, limits, text-rendering callbacks and a text-only ChatFunc. Generate preserves user-turn boundaries, limits parallel calls and merges in history order. Progress callbacks are serialized. Hosts validate the final summary before saving their own backups/checkpoints. Validate, LocalSummary, SelectInput and RestoreAttachments can also be used independently. workflow.NewWorkflowEngine accepts an executor with registered action callbacks; HTTP adapters live in luckyagent-api/workflow.

See compaction evidence and cancellation for local-fallback claims, final validation responsibilities and parent cancellation behavior.

These execution APIs are additions after v0.2.2. Downstream modules must require a commit pseudo-version or a newer release containing them. Use matching checkouts in a Go workspace during joint development, and merge tools before upgrading API and host dependencies. No runtime JSON configuration, tool wire name or stored session format is changed by the extraction.

NewMemoryToolService consumes memory.ToolBackend; NewRAGToolService consumes the two-method rag.Backend search/index port. The module never opens LuckyAgent's memory or RAG store. CredentialProvider.WithCredential grants access for a single callback; credential loading, zeroing and cleanup belong to the provider. Pass it to NewEphemeralCredentialToolService or its terminal variant. Temporary tool expiry, session scope, shell quoting and redaction stay in this module.

Delegate managers accept executor functions; media tools accept providers; desktop tools accept ComputerManager. Hosts instantiate only the capabilities they enable and close owned services during shutdown. NewServices assembles the runtime catalog. RegisterRuntimeBuiltinTools[WithConfig] adds the optional media tools; the existing RegisterBuiltinTools[WithConfig] remains the generic standalone catalog for source compatibility.

Desktop capture and tool schemas

The X11 backend has a bounded native screenshot fallback when ImageMagick is missing or fails; see X11 capture. Tool conversion sorts the JSON Schema required array so map iteration does not reorder required parameter names between otherwise identical requests.

Documentation

Index

Examples

Constants

View Source
const (
	SeverityInfo  = "info"
	SeverityWarn  = "warn"
	SeverityBlock = "block"
)

Severity levels for a ScanFinding. A block finding cannot be overridden by the user; a warn finding can be accepted explicitly at confirm time.

View Source
const (
	InstallStaging   = "staging"
	InstallScanning  = "scanning"
	InstallProbing   = "probing"
	InstallReady     = "ready"
	InstallRejected  = "rejected"
	InstallConfirmed = "confirmed"
	InstallAborted   = "aborted"
	InstallFailed    = "failed"
)

Install states, as surfaced to the API and UI.

View Source
const (
	SourceArchive = "archive"
	SourcePath    = "path"
)

Install source kinds.

View Source
const PriorityCritical = delegateruntime.PriorityCritical
View Source
const PriorityNormal = delegateruntime.PriorityNormal
View Source
const SkillVersion = "v0.5.0"

SkillVersion is the current skill plugin system version.

View Source
const StatusCancelled = delegateruntime.StatusCancelled
View Source
const StatusCompleted = delegateruntime.StatusCompleted
View Source
const StatusPending = delegateruntime.StatusPending
View Source
const StatusRunning = delegateruntime.StatusRunning

Variables

View Source
var DefaultDelegateConfig = delegateruntime.DefaultDelegateConfig
View Source
var DelegateExecutionSessionID = delegateruntime.DelegateExecutionSessionID
View Source
var NewPriorityTaskQueue = delegateruntime.NewPriorityTaskQueue

Functions

func AnnotateToolCall

func AnnotateToolCall(name, arguments, result string) string

AnnotateToolCall describes a tool invocation using only its supplied arguments and result. Unknown tools receive a safe generic summary.

func AnnotateToolCallWithTemplates

func AnnotateToolCallWithTemplates(name, arguments, result string, templates map[string]string) string

AnnotateToolCallWithTemplates applies a configured template for the named tool. Supported placeholders are {tool}, {path}, {query}, {command}, {workdir}, {result}, {status}, and {content_size}.

func BoolArg

func BoolArg(v any, rest ...any) bool

BoolArg reads a boolean value or an argument-map key with a fallback.

func BoundedIntArg

func BoundedIntArg(args map[string]any, key string, def, minValue, maxValue int) int

BoundedIntArg reads an integer argument and clamps it to the supplied bounds.

func CheckCollisions

func CheckCollisions(summary *CapabilitySummary, existing *SkillRegistry, tools *Registry) []string

CheckCollisions reports why a staged skill cannot coexist with what is already installed. Names are compared post-sanitizeName because that is the key the registry actually uses, and it is many-to-one ("a b" and "a-b" both collapse).

func CloneToolArgs

func CloneToolArgs(args map[string]any) map[string]any

CloneToolArgs copies an argument map before an adapter rewrites a call.

func CompressOutput

func CompressOutput(output string, config OutputCompressConfig) string

CompressOutput 压缩单个工具输出

func CopyLocalDir

func CopyLocalDir(src, dest string, limits InstallLimits) (*extractStats, error)

CopyLocalDir copies a directory tree into dest under the same limits as archive extraction. Symlinks are rejected rather than followed: following them would let a local-path install pull in arbitrary files from outside the source.

func DedupOutputs

func DedupOutputs(outputs map[string]string) map[string]string

DedupOutputs 对多个工具输出去重(移除完全重复的输出)

func DefaultTierConfigs

func DefaultTierConfigs() map[SubTier]TierConfig

DefaultTierConfigs 默认订阅等级配置

func ExpandSandboxPath

func ExpandSandboxPath(path string) string

ExpandSandboxPath expands the path forms understood by filesystem tools.

func ExtractArchive

func ExtractArchive(archivePath, dest string, limits InstallLimits) (*extractStats, error)

ExtractArchive unpacks a zip or gzipped tar into dest, enforcing limits on every entry. dest must already exist. It returns the first violation as an *extractError; partial output is left for the caller to clean up.

func ExtractDelegateWorkspace added in v0.2.0

func ExtractDelegateWorkspace(contextStr string) string

func ExtractDocumentText

func ExtractDocumentText(path string) (text, format string, err error)

func FormatAuditEntry

func FormatAuditEntry(entry AuditEntry) string

FormatAuditEntry formats an audit entry as JSON string.

func MergeToolParams

func MergeToolParams(base map[string]Param, groups ...map[string]Param) map[string]Param

MergeToolParams combines schemas while preserving the primary action field.

func MoveDir

func MoveDir(src, dst string) error

MoveDir renames src to dst, falling back to a copy when the two live on different filesystems (os.Rename returns EXDEV). dst must not already exist: os.Rename over a non-empty directory fails with ENOTEMPTY on Linux, so callers snapshot-then-move rather than overwriting in place.

func NormalizeRoot

func NormalizeRoot(root, skillDirName string) (string, error)

NormalizeRoot arranges extracted content so that root holds exactly one child directory containing SKILL.md. That shape is required because SkillLoader iterates a directory and descends one level into each child, so the loader must be pointed at the *parent* of the skill.

It handles both common archive layouts: SKILL.md at the archive root, and SKILL.md under a single wrapping directory.

func NumberArg

func NumberArg(v any) (float64, bool)

NumberArg reads the numeric argument representations accepted by builtins.

func ParallelCompressOutputs

func ParallelCompressOutputs(outputs map[string]string, config OutputCompressConfig) map[string]string

ParallelCompressOutputs 并行压缩多个工具输出 使用 goroutine 并发处理每个输出

func ParamSchema

func ParamSchema(p Param) map[string]any

ParamSchema produces the nested JSON schema used by function calling.

func PrettyStructuredValue

func PrettyStructuredValue(v any) (string, error)

PrettyStructuredValue formats structured tool output as indented JSON.

func RegisterBuiltinComputerTools added in v0.2.0

func RegisterBuiltinComputerTools(r *Registry, manager ComputerManager, cfg ComputerUseConfig)

RegisterBuiltinComputerTools adds the optional desktop observation/control tools to an existing registry. Keeping this separate avoids constructing a platform backend when computer use is disabled.

func RegisterBuiltinTools

func RegisterBuiltinTools(r *Registry)

RegisterBuiltinTools registers the standalone tool catalog. Application operations such as media processing can be registered by the embedding host.

func RegisterBuiltinToolsWithConfig

func RegisterBuiltinToolsWithConfig(r *Registry, searchCfg *WebSearchConfig, opencliCfg *OpenCLIConfig)

RegisterBuiltinToolsWithConfig supplies search and OpenCLI options. Memory and RAG definitions retain their callback-based, unconfigured defaults.

func RegisterMCPTools

func RegisterMCPTools(r *Registry, client *MCPClient)

RegisterMCPTools 将 MCP Server 的工具注册到 Registry

func RegisterRuntimeBuiltinTools added in v0.2.0

func RegisterRuntimeBuiltinTools(r *Registry, mediaProcessor ...*multimodal.Processor)

RegisterRuntimeBuiltinTools 注册所有内置工具

func RegisterRuntimeBuiltinToolsWithConfig added in v0.2.0

func RegisterRuntimeBuiltinToolsWithConfig(r *Registry, searchCfg *WebSearchConfig, opencliCfg *OpenCLIConfig, mediaProcessor ...*multimodal.Processor)

RegisterRuntimeBuiltinToolsWithConfig 注册所有内置工具(带搜索配置)

func RegisterSkillTools

func RegisterSkillTools(r *Registry, skills []*SkillInfo, handler func(toolName string, skillDir string) func(args map[string]any) (string, error))

RegisterSkillTools 将 Skill 工具注册到 Registry handler 为 Skill 工具的通用处理器(通常调用脚本或子进程)

func ResolveWorkspacePath

func ResolveWorkspacePath(path string) (string, error)

ResolveWorkspacePath restricts an adapter's path to the tool workspace.

func SandboxWorkspaceDir

func SandboxWorkspaceDir() string

SandboxWorkspaceDir returns the compatible default tool workspace.

func StringArg

func StringArg(v any) string

StringArg returns a trimmed string argument.

func ToOpenAIName

func ToOpenAIName(name string) string

ToOpenAIName returns the model-facing name used in function schemas. It is exported so policy and routing code can compare registry names with names returned by providers without duplicating the conversion rules.

func ToolAction

func ToolAction(args map[string]any) string

ToolAction reads the normalized action of a multi-action tool.

func TruncateOutput

func TruncateOutput(output string, maxChars int) string

TruncateOutput 截断单个输出

func TruncateOutputs

func TruncateOutputs(outputs map[string]string, maxChars int) map[string]string

TruncateOutputs 批量截断工具输出

func ValidSkillName

func ValidSkillName(name string) bool

ValidSkillName reports whether a name is safe to use as a path segment and as a URL segment. sanitizeName permits CJK, so this cannot be a plain ASCII allowlist — several installed skills have Chinese names.

func ValidateFetchURL

func ValidateFetchURL(rawURL string) error

ValidateFetchURL applies the shared fetch URL restrictions.

func ValidateHTTPMethod

func ValidateHTTPMethod(method string, allowMutation bool) error

ValidateHTTPMethod enforces the builtin's opt-in for mutating HTTP methods.

func ValidatePath

func ValidatePath(path string) error

ValidatePath applies the shared builtin path validation rules.

func ValidateRequestHeader

func ValidateRequestHeader(name, value string) error

ValidateRequestHeader rejects unsafe or protected request headers.

Types

type AgentExecutorFunc added in v0.2.0

type AgentExecutorFunc = delegateruntime.AgentExecutorFunc

type AgentExecutorOptions added in v0.2.0

type AgentExecutorOptions = delegateruntime.AgentExecutorOptions

type AgentExecutorWithOptionsFunc added in v0.2.0

type AgentExecutorWithOptionsFunc = delegateruntime.AgentExecutorWithOptionsFunc

type ApprovalOption

type ApprovalOption = approval.Option

ApprovalOption and PendingApproval retain the original public API.

type ApprovalRequiredError added in v0.2.0

type ApprovalRequiredError struct {
	Tool    string
	Action  computer.Action
	Reason  string
	Actions []computer.Action
}

ApprovalRequiredError preserves the proposed action when a control request is intentionally stopped before it reaches the platform backend.

func (*ApprovalRequiredError) Error added in v0.2.0

func (e *ApprovalRequiredError) Error() string

type AuditEntry

type AuditEntry struct {
	Timestamp  time.Time      `json:"timestamp"`
	ToolName   string         `json:"tool_name"`
	SkillName  string         `json:"skill_name"`
	Args       map[string]any `json:"args,omitempty"`
	Result     string         `json:"result,omitempty"`
	Error      string         `json:"error,omitempty"`
	Duration   time.Duration  `json:"duration"`
	Success    bool           `json:"success"`
	OutputSize int            `json:"output_size"`
	Panic      bool           `json:"panic,omitempty"`
}

AuditEntry records a single skill tool invocation for audit purposes.

type AuditStats

type AuditStats struct {
	TotalInvocations      int           `json:"total_invocations"`
	SuccessfulInvocations int           `json:"successful_invocations"`
	FailedInvocations     int           `json:"failed_invocations"`
	PanicCount            int           `json:"panic_count"`
	TotalDuration         time.Duration `json:"total_duration"`
	AvgDuration           time.Duration `json:"avg_duration"`
}

AuditStats holds summary audit statistics.

type AutonomyStartFunc added in v0.2.0

type AutonomyStartFunc func() error

AutonomyStartFunc starts the runtime autonomy kit when a tool action needs workers or heartbeat execution.

type AutonomyToolService added in v0.2.0

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

AutonomyToolService wraps autonomy tool definitions for tool-layer registration.

func NewAutonomyToolService added in v0.2.0

func NewAutonomyToolService(kit *autonomy.AutonomyKit, start ...AutonomyStartFunc) *AutonomyToolService

NewAutonomyToolService creates an autonomy tool service.

func (*AutonomyToolService) HandleAutonomy added in v0.2.0

func (s *AutonomyToolService) HandleAutonomy(args map[string]any) (string, error)

HandleAutonomy exposes a single model-visible autonomy control surface while keeping the lower-level autonomy_* tools available for internal callers.

func (*AutonomyToolService) HandleHeartbeatTrigger added in v0.2.0

func (s *AutonomyToolService) HandleHeartbeatTrigger(args map[string]any) (string, error)

func (*AutonomyToolService) HandleQueueAdd added in v0.2.0

func (s *AutonomyToolService) HandleQueueAdd(args map[string]any) (string, error)

func (*AutonomyToolService) HandleQueueList added in v0.2.0

func (s *AutonomyToolService) HandleQueueList(args map[string]any) (string, error)

func (*AutonomyToolService) HandleQueueUpdate added in v0.2.0

func (s *AutonomyToolService) HandleQueueUpdate(args map[string]any) (string, error)

func (*AutonomyToolService) HandleReport added in v0.2.0

func (s *AutonomyToolService) HandleReport(args map[string]any) (string, error)

func (*AutonomyToolService) HandleScaleDown added in v0.2.0

func (s *AutonomyToolService) HandleScaleDown(args map[string]any) (string, error)

func (*AutonomyToolService) HandleScaleUp added in v0.2.0

func (s *AutonomyToolService) HandleScaleUp(args map[string]any) (string, error)

func (*AutonomyToolService) HandleSetWorkers added in v0.2.0

func (s *AutonomyToolService) HandleSetWorkers(args map[string]any) (string, error)

func (*AutonomyToolService) HandleStatus added in v0.2.0

func (s *AutonomyToolService) HandleStatus(args map[string]any) (string, error)

func (*AutonomyToolService) HandleWorkerList added in v0.2.0

func (s *AutonomyToolService) HandleWorkerList(args map[string]any) (string, error)

func (*AutonomyToolService) HandleWorkerSpawn added in v0.2.0

func (s *AutonomyToolService) HandleWorkerSpawn(args map[string]any) (string, error)

func (*AutonomyToolService) RegisterTools added in v0.2.0

func (s *AutonomyToolService) RegisterTools(r *Registry)

RegisterTools registers autonomy-related tools onto the registry.

type BuiltinToolService added in v0.2.0

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

BuiltinToolService wraps the generic builtin tool registrations.

func NewBuiltinToolService added in v0.2.0

func NewBuiltinToolService(searchCfg *WebSearchConfig, opencliCfg *OpenCLIConfig, defaultImageProvider string, mediaProcessor *multimodal.Processor, imageGenerator multimodal.ImageGenerator, imageGenDefaults ImageGenerationDefaults, speechSynthesizer multimodal.SpeechSynthesizer, ttsDefaults TTSDefaults, policies ...FilesystemPolicy) *BuiltinToolService

NewBuiltinToolService creates a builtin tool service.

func (*BuiltinToolService) RegisterTools added in v0.2.0

func (s *BuiltinToolService) RegisterTools(r *Registry)

RegisterTools registers builtin terminal/file/web/time tools.

func (*BuiltinToolService) ReloadMedia added in v0.2.0

func (s *BuiltinToolService) ReloadMedia(r *Registry, defaultImageProvider string, mediaProcessor *multimodal.Processor, imageGenerator multimodal.ImageGenerator, imageGenDefaults ImageGenerationDefaults, speechSynthesizer multimodal.SpeechSynthesizer, ttsDefaults TTSDefaults)

ReloadMedia replaces only media-dependent tool implementations. Existing invocations retain their captured provider while new tool calls use the updated model configuration.

func (*BuiltinToolService) SetComputerUseService added in v0.2.0

func (s *BuiltinToolService) SetComputerUseService(service *ComputerUseToolService)

SetComputerUseService attaches the optional desktop automation tools.

type CapabilitySummary

type CapabilitySummary struct {
	Name        string           `json:"name"`
	Aliases     []string         `json:"aliases,omitempty"`
	Description string           `json:"description,omitempty"`
	Summary     string           `json:"summary,omitempty"`
	Scripts     []string         `json:"scripts,omitempty"`
	Tools       []CapabilityTool `json:"tools"`
	Probed      bool             `json:"probed"`
	ProbeErrors []string         `json:"probe_errors,omitempty"`
	Collisions  []string         `json:"collisions,omitempty"`
}

CapabilitySummary is what a user reviews before confirming an install.

type CapabilityTool

type CapabilityTool struct {
	Name          string   `json:"name"`
	Description   string   `json:"description,omitempty"`
	ExposeToModel bool     `json:"expose_to_model"`
	Command       []string `json:"command,omitempty"`
	// Origin records how the tool was derived: "declared" (a ## Tools section),
	// "script" (one tool per file in scripts/), or "cli_probe" (scraped from
	// `<script> --help`, which means the skill's code was executed).
	Origin string `json:"origin"`
	// FullName is the name the tool would occupy in the tool Registry.
	FullName string `json:"full_name"`
}

CapabilityTool describes one tool the staged skill would contribute.

type Category

type Category string

Category 工具分类

const (
	CatBuiltin  Category = "builtin"  // 内置工具
	CatSkill    Category = "skill"    // Skill 插件工具
	CatMCP      Category = "mcp"      // MCP Server 工具
	CatDelegate Category = "delegate" // 子代理委派
)

type CodexToolService added in v0.2.0

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

CodexToolService exposes the app-server lifecycle as a small, stateful tool family. It returns summaries and cursors instead of forwarding the unbounded app-server stream directly into the model context.

func NewCodexToolService added in v0.2.0

func NewCodexToolService(manager *codex.Manager) *CodexToolService

func (*CodexToolService) Close added in v0.2.0

func (s *CodexToolService) Close() error

func (*CodexToolService) RegisterTools added in v0.2.0

func (s *CodexToolService) RegisterTools(r *Registry)

type ComputerManager added in v0.2.0

ComputerManager is the narrow manager contract required by the tools. The concrete computer.Manager satisfies it, while tests can provide a fake implementation without touching the desktop.

type ComputerUseConfig added in v0.2.0

type ComputerUseConfig = computer.ToolConfig

ComputerUseConfig is exported from the tool package for callers that do not otherwise need to import the config package.

type ComputerUseToolService added in v0.2.0

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

ComputerUseToolService binds the model-facing tools to a stateful desktop manager and applies the config-level source/mode/input policy.

func NewComputerUseToolService added in v0.2.0

func NewComputerUseToolService(manager ComputerManager, cfg ComputerUseConfig) *ComputerUseToolService

func (*ComputerUseToolService) ActTool added in v0.2.0

func (s *ComputerUseToolService) ActTool() *Tool

func (*ComputerUseToolService) ObserveTool added in v0.2.0

func (s *ComputerUseToolService) ObserveTool() *Tool

func (*ComputerUseToolService) RegisterTools added in v0.2.0

func (s *ComputerUseToolService) RegisterTools(r *Registry)

type CredentialProvider added in v0.2.0

type CredentialProvider interface {
	WithCredential(context.Context, string, func([]byte) error) error
}

CredentialProvider grants access for one call; the host owns storage and cleanup.

type CronSaveFunc added in v0.2.0

type CronSaveFunc func() error

CronSaveFunc persists cron jobs after mutation.

type CronTaskFactory added in v0.2.0

type CronTaskFactory func(id, mode, command string, metadata map[string]string) func() error

CronTaskFactory builds a runnable task for a cron job.

type CronToolService added in v0.2.0

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

CronToolService implements cron_* handlers in the tool layer.

func NewCronToolService added in v0.2.0

func NewCronToolService(engine *cronpkg.Engine, save CronSaveFunc, buildTask CronTaskFactory) *CronToolService

NewCronToolService creates a cron tool service.

func (*CronToolService) HandleAdd added in v0.2.0

func (s *CronToolService) HandleAdd(args map[string]any) (string, error)

func (*CronToolService) HandleCron added in v0.2.0

func (s *CronToolService) HandleCron(args map[string]any) (string, error)

func (*CronToolService) HandleList added in v0.2.0

func (s *CronToolService) HandleList(args map[string]any) (string, error)

func (*CronToolService) HandlePause added in v0.2.0

func (s *CronToolService) HandlePause(args map[string]any) (string, error)

func (*CronToolService) HandleRemove added in v0.2.0

func (s *CronToolService) HandleRemove(args map[string]any) (string, error)

func (*CronToolService) HandleResume added in v0.2.0

func (s *CronToolService) HandleResume(args map[string]any) (string, error)

func (*CronToolService) HandleStatus added in v0.2.0

func (s *CronToolService) HandleStatus(args map[string]any) (string, error)

func (*CronToolService) HandleValidate added in v0.2.0

func (s *CronToolService) HandleValidate(args map[string]any) (string, error)

func (*CronToolService) RegisterTools added in v0.2.0

func (s *CronToolService) RegisterTools(r *Registry)

RegisterTools registers cron-related tools onto the registry.

type DelegateConfig added in v0.2.0

type DelegateConfig = delegateruntime.DelegateConfig

Compatibility names for the independent delegation engine.

type DelegateManager added in v0.2.0

type DelegateManager struct {
	*delegateruntime.DelegateManager
}

DelegateManager binds the independent delegation engine to tool definitions. All task state and execution lifecycle are owned by the embedded engine.

func NewDelegateManager added in v0.2.0

func NewDelegateManager(cfg DelegateConfig) *DelegateManager

func (*DelegateManager) DelegateParallelTool added in v0.2.0

func (dm *DelegateManager) DelegateParallelTool() *Tool

DelegateParallelTool 创建并行委派工具

type DelegateTarget added in v0.2.0

type DelegateTarget = delegateruntime.DelegateTarget

type DelegateTask added in v0.2.0

type DelegateTask = delegateruntime.DelegateTask

type EphemeralCredentialTerminalToolService added in v0.2.0

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

EphemeralCredentialTerminalToolService owns session-scoped terminal wrappers. The wrapper stores only credential_ref and a declarative command template; the credential value exists only while the child process runs.

func NewEphemeralCredentialTerminalToolService added in v0.2.0

func NewEphemeralCredentialTerminalToolService(resolver CredentialProvider) *EphemeralCredentialTerminalToolService

func (*EphemeralCredentialTerminalToolService) Close added in v0.2.0

func (*EphemeralCredentialTerminalToolService) RegisterTools added in v0.2.0

func (s *EphemeralCredentialTerminalToolService) RegisterTools(r *Registry)

RegisterTools exposes only the factory. Generated wrappers are hidden from the global model list and are appended for their owning session by Agent.

func (*EphemeralCredentialTerminalToolService) RevokeSession added in v0.2.0

func (s *EphemeralCredentialTerminalToolService) RevokeSession(scope string)

func (*EphemeralCredentialTerminalToolService) VisibleTools added in v0.2.0

func (s *EphemeralCredentialTerminalToolService) VisibleTools(scope string) []map[string]any

type EphemeralCredentialToolService added in v0.2.0

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

EphemeralCredentialToolService creates short-lived, session-scoped HTTP tools. The generated tool stores only a credential reference; it never stores the decrypted credential value.

func NewEphemeralCredentialToolService added in v0.2.0

func NewEphemeralCredentialToolService(resolver CredentialProvider) *EphemeralCredentialToolService

NewEphemeralCredentialToolService creates the in-memory temporary-tool manager. The credential store is opened only for the duration of a call.

func (*EphemeralCredentialToolService) Close added in v0.2.0

Close removes every generated wrapper from the registry.

func (*EphemeralCredentialToolService) RegisterTools added in v0.2.0

func (s *EphemeralCredentialToolService) RegisterTools(r *Registry)

RegisterTools exposes only the factory. Generated wrappers are hidden from the global registry's model list and are added per session by the agent.

func (*EphemeralCredentialToolService) RevokeSession added in v0.2.0

func (s *EphemeralCredentialToolService) RevokeSession(scope string)

RevokeSession removes all temporary tools belonging to a session.

func (*EphemeralCredentialToolService) VisibleTools added in v0.2.0

func (s *EphemeralCredentialToolService) VisibleTools(scope string) []map[string]any

VisibleTools returns schemas for temporary tools belonging to one session. The wrappers remain hidden from Registry.ListModelVisible so another session cannot discover them.

type ErrQuotaExceeded

type ErrQuotaExceeded struct {
	Tool   string
	UserID string
	Reason string
}

func (ErrQuotaExceeded) Error

func (e ErrQuotaExceeded) Error() string

type ErrToolDenied

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

ErrToolDenied 工具权限拒绝

func (ErrToolDenied) Error

func (e ErrToolDenied) Error() string

type ErrToolDisabled

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

ErrToolDisabled 工具已禁用

func (ErrToolDisabled) Error

func (e ErrToolDisabled) Error() string

type ErrToolNotFound

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

ErrToolNotFound 工具未找到错误

func (ErrToolNotFound) Error

func (e ErrToolNotFound) Error() string

type ExecutionContext

type ExecutionContext struct {
	Context   context.Context
	SessionID string
	Source    string
	UserID    string
	// UserRequest is the raw routing text for the current user turn. Sensitive
	// tools may use it to verify that an operation was explicitly requested.
	UserRequest string
	AutoApprove bool
	// Sandbox is captured when the task starts. A running task keeps the same
	// execution boundary even if the global mode changes later.
	Sandbox *sandbox.Snapshot
}

ExecutionContext carries request-local execution metadata to context-aware tools. Context is always non-nil when dispatched through the registry.

type FilesystemPolicy

type FilesystemPolicy struct {
	AllowedReadRoots    []string
	AllowOutsideSandbox bool
}

FilesystemPolicy extends the built-in filesystem sandbox with explicit, read-only roots. Write, patch, move, mkdir, and delete operations continue to use the built-in sandbox only.

func DefaultFilesystemPolicy

func DefaultFilesystemPolicy() FilesystemPolicy

func FilesystemPolicyFromOptional

func FilesystemPolicyFromOptional(policies []FilesystemPolicy) FilesystemPolicy

FilesystemPolicyFromOptional resolves the legacy variadic policy input.

type Gateway

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

Gateway is the unified tool execution entry point.

func NewGateway

func NewGateway(registry *Registry) *Gateway

func (*Gateway) Execute

func (g *Gateway) Execute(name string, args map[string]any, userID string) (*GatewayResult, error)

func (*Gateway) ExecuteWithContext

func (g *Gateway) ExecuteWithContext(name string, args map[string]any, userID string, exec ExecutionContext) (*GatewayResult, error)

ExecuteWithContext is the request-aware gateway entry point. It preserves the legacy Execute behavior while allowing desktop tools to receive session, source, cancellation, and approval metadata.

func (*Gateway) ExecuteWithShellContext

func (g *Gateway) ExecuteWithShellContext(name string, args map[string]any, userID string, sc *ShellContext) (*GatewayResult, error)

func (*Gateway) ExecuteWithShellExecutionContext

func (g *Gateway) ExecuteWithShellExecutionContext(name string, args map[string]any, userID string, sc *ShellContext, exec ExecutionContext) (*GatewayResult, error)

ExecuteWithShellExecutionContext combines shell injection with request-aware context dispatch.

func (*Gateway) Router

func (g *Gateway) Router() *ToolRouter

func (*Gateway) Subscriptions

func (g *Gateway) Subscriptions() *SubscriptionManager

func (*Gateway) Tracker

func (g *Gateway) Tracker() *UsageTracker

type GatewayResult

type GatewayResult struct {
	ToolName     string
	Output       string
	Metadata     map[string]any
	Observations []Observation
	Duration     time.Duration
	Success      bool
	Timestamp    time.Time
}

func (*GatewayResult) Format

func (r *GatewayResult) Format() string

type GrokToolService added in v0.2.0

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

GrokToolService exposes the local grok agent lifecycle as a small, stateful tool family. It returns summaries and cursors instead of forwarding the unbounded ACP stream directly into the model context.

func NewGrokToolService added in v0.2.0

func NewGrokToolService(manager *grok.Manager) *GrokToolService

func (*GrokToolService) Close added in v0.2.0

func (s *GrokToolService) Close() error

func (*GrokToolService) RegisterTools added in v0.2.0

func (s *GrokToolService) RegisterTools(r *Registry)

type HeartbeatToolService added in v0.2.0

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

HeartbeatToolService wraps heartbeat-related tool handlers.

func NewHeartbeatToolService added in v0.2.0

func NewHeartbeatToolService(
	trigger func(args map[string]any) (string, error),
	status func(args map[string]any) (string, error),
) *HeartbeatToolService

NewHeartbeatToolService creates a heartbeat tool service from injected handlers.

func (*HeartbeatToolService) RegisterTools added in v0.2.0

func (s *HeartbeatToolService) RegisterTools(r *Registry)

RegisterTools registers heartbeat-related tools onto the registry.

type ImageGenerationDefaults added in v0.2.0

type ImageGenerationDefaults struct {
	Model             string
	Size              string
	Quality           string
	Background        string
	OutputFormat      string
	OutputCompression int
	Count             int
}

ImageGenerationDefaults captures configurable defaults for the image_generate tool.

type InstallHistory

type InstallHistory struct {
	VersionID string    `json:"version_id"`
	Digest    string    `json:"digest,omitempty"`
	Action    string    `json:"action"` // installed | upgraded | uninstalled | rolled_back
	At        time.Time `json:"at"`
}

InstallHistory is one entry in a skill's rollback history.

type InstallLimits

type InstallLimits struct {
	MaxArchiveBytes      int64
	MaxUncompressedBytes int64
	MaxSingleFileBytes   int64
	MaxFiles             int
	MaxCompressionRatio  int
	MaxPathDepth         int
	MaxPathLen           int
	BlockOnSecrets       bool
}

InstallLimits bounds extraction and scanning. Zero fields fall back to DefaultInstallLimits, so a partially-populated struct is still safe.

func DefaultInstallLimits

func DefaultInstallLimits() InstallLimits

DefaultInstallLimits mirrors config.SkillInstallConfig's defaults.

type InstallManager

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

InstallManager owns the staging area and the ledger, and serializes work per skill name.

Locking: nameLocks serializes Prepare/Confirm/Uninstall for one skill. It is deliberately not a single global lock — installs of unrelated skills should not block each other — but it does mean Confirm must re-run the collision check under the lock, because two Prepares can both have observed a clear field before either committed.

func NewInstallManager

func NewInstallManager(cfg InstallManagerConfig) *InstallManager

func (*InstallManager) Abort

func (m *InstallManager) Abort(id string) error

Abort discards a staged install.

func (*InstallManager) Confirm

func (m *InstallManager) Confirm(id string, acceptWarnings bool) (*InstallRecord, error)

Confirm commits a prepared install: snapshot any existing version, move the staged tree into place, update the ledger, then reload.

The rename happens before the reload, never after. A rename is atomic, so a concurrent reload either sees the new skill or does not; the explicit reload that follows picks it up either way. Reversing the order could miss it.

func (*InstallManager) GC

func (m *InstallManager) GC()

GC drops expired staging directories and prunes old version snapshots.

func (*InstallManager) ListStaged

func (m *InstallManager) ListStaged() []*InstallRecord

ListStaged returns staged installs that have not been committed or aborted.

func (*InstallManager) Prepare

func (m *InstallManager) Prepare(id string) (*InstallRecord, error)

Prepare runs extraction, the static scan, and the trial load for a staged install. It is the long pole: the probe stage spawns one subprocess per discovered subcommand, so callers run it in the background.

Order is the whole point: nothing executes until the scan is clean.

func (*InstallManager) Rollback

func (m *InstallManager) Rollback(name, versionID string) error

Rollback restores a snapshot, snapshotting whatever is currently live first so the operation is itself reversible.

func (*InstallManager) SetRuntime

func (m *InstallManager) SetRuntime(reload func() (int, error), registry func() *SkillRegistry, tools func() *Registry)

SetRuntime wires the live views the manager needs. reload must re-scan the skills tree; registry and tools supply the collision precheck.

func (*InstallManager) StageArchive

func (m *InstallManager) StageArchive(filename string, read func(dst string) error) (string, *InstallRecord, error)

StageArchive copies uploaded bytes into a fresh staging directory and returns its install id. This must run synchronously inside the HTTP handler: the multipart temp files are removed the moment the handler returns.

func (*InstallManager) StageLocalDir

func (m *InstallManager) StageLocalDir(srcDir string) (string, *InstallRecord, error)

StageLocalDir copies a server-local directory into staging.

This source is an arbitrary-read primitive — whatever it copies in becomes readable by the model through skill_read — so it is refused unless the path sits under an explicitly configured root.

func (*InstallManager) Staged

func (m *InstallManager) Staged(id string) (*InstallRecord, error)

func (*InstallManager) Store

func (m *InstallManager) Store() *InstallStore

func (*InstallManager) Uninstall

func (m *InstallManager) Uninstall(name string, purge bool) (string, error)

Uninstall removes a skill from the live tree, optionally snapshotting it first.

func (*InstallManager) Versions

func (m *InstallManager) Versions(name string) []string

Versions lists the rollback snapshots available for a skill, newest first.

type InstallManagerConfig

type InstallManagerConfig struct {
	SkillsDir   string
	StagingDir  string
	VersionsDir string
	LedgerPath  string

	Limits            InstallLimits
	ProbeCLI          bool
	ProbeTimeout      time.Duration
	TrialBudget       time.Duration
	AllowedLocalRoots []string
	KeepVersions      int
	StagingTTL        time.Duration
}

InstallManagerConfig wires the manager to the runtime.

type InstallRecord

type InstallRecord struct {
	InstallID string `json:"install_id"`
	Name      string `json:"name"`
	Version   string `json:"version,omitempty"`
	Digest    string `json:"digest,omitempty"`
	State     string `json:"state"`
	Mode      string `json:"mode"` // install | upgrade
	Error     string `json:"error,omitempty"`

	Source     InstallSource      `json:"source"`
	Scan       *ScanReport        `json:"scan,omitempty"`
	Capability *CapabilitySummary `json:"capability,omitempty"`

	Tools       []string         `json:"tools,omitempty"`
	CreatedAt   time.Time        `json:"created_at"`
	UpdatedAt   time.Time        `json:"updated_at"`
	InstalledAt time.Time        `json:"installed_at,omitempty"`
	History     []InstallHistory `json:"history,omitempty"`
}

InstallRecord is a staged or committed install. The staging copy lives at <staging>/<install-id>/record.json; the committed copy lives in the ledger.

func (*InstallRecord) CanConfirm

func (r *InstallRecord) CanConfirm() bool

CanConfirm reports whether the staged install may be committed.

type InstallSource

type InstallSource struct {
	Kind   string `json:"kind"`             // archive | path
	Origin string `json:"origin,omitempty"` // filename or local directory
	Size   int64  `json:"size,omitempty"`
}

InstallSource records where a staged skill came from.

type InstallStore

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

InstallStore persists the ledger of managed skills. Skills copied into skills/ by hand have no entry; that absence is what marks them unmanaged, so the UI knows not to offer rollback for them.

func NewInstallStore

func NewInstallStore(path string) *InstallStore

func (*InstallStore) Get

func (s *InstallStore) Get(name string) (*InstallRecord, bool)

Get returns the ledger entry for a skill.

func (*InstallStore) List

func (s *InstallStore) List() []*InstallRecord

List returns every managed record.

func (*InstallStore) Load

func (s *InstallStore) Load() (*Ledger, error)

Load reads the ledger. A missing file is not an error — it means nothing has been installed through the pipeline yet.

func (*InstallStore) Path

func (s *InstallStore) Path() string

func (*InstallStore) Remove

func (s *InstallStore) Remove(name string) error

Remove drops a skill's record.

func (*InstallStore) Save

func (s *InstallStore) Save(ledger *Ledger) error

Save writes the ledger atomically: a crash mid-write must not leave a truncated file that would read as "nothing is managed".

func (*InstallStore) Upsert

func (s *InstallStore) Upsert(rec *InstallRecord) error

Upsert replaces one skill's record under a single lock, so concurrent installs of different skills cannot lose each other's writes through a read-modify-write race.

type Ledger

type Ledger struct {
	Version int                       `json:"version"`
	Skills  map[string]*InstallRecord `json:"skills"`
	Updated time.Time                 `json:"updated"`
}

Ledger is the on-disk record of managed skills. Skills installed by hand (by copying a directory into skills/) have no entry, which is how the API tells managed from unmanaged.

type MCPClient

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

MCPClient 是 MCP (Model Context Protocol) 客户端 用于连接外部 MCP Server 并调用其工具

func NewMCPClient

func NewMCPClient() *MCPClient

NewMCPClient 创建 MCP 客户端

func (*MCPClient) AddServer

func (c *MCPClient) AddServer(cfg MCPServerConfig)

AddServer 添加 MCP Server

func (*MCPClient) CallTool

func (c *MCPClient) CallTool(serverName, toolName string, args map[string]any) (string, error)

CallTool 调用 MCP Server 的工具

func (*MCPClient) ListServers

func (c *MCPClient) ListServers() []MCPServerConfig

ListServers 列出所有 MCP Server

func (*MCPClient) ListTools

func (c *MCPClient) ListTools(serverName string) ([]MCPToolInfo, error)

ListTools 列出 MCP Server 的工具

func (*MCPClient) RemoveServer

func (c *MCPClient) RemoveServer(name string)

RemoveServer 移除 MCP Server

type MCPError

type MCPError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

MCPError MCP 错误

func (*MCPError) Error

func (e *MCPError) Error() string

type MCPRequest

type MCPRequest struct {
	JSONRPC string `json:"jsonrpc"`
	Method  string `json:"method"`
	Params  any    `json:"params,omitempty"`
	ID      int    `json:"id"`
}

MCPRequest MCP JSON-RPC 请求

type MCPResponse

type MCPResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *MCPError       `json:"error,omitempty"`
	ID      int             `json:"id"`
}

MCPResponse MCP JSON-RPC 响应

type MCPServerConfig

type MCPServerConfig struct {
	Name    string `json:"name"`
	URL     string `json:"url"`
	APIKey  string `json:"api_key,omitempty"`
	Enabled bool   `json:"enabled"`
}

MCPServerConfig MCP Server 配置

type MCPToolInfo

type MCPToolInfo struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Parameters  map[string]any `json:"parameters"`
}

MCPToolInfo MCP Server 返回的工具信息

type MemoryToolService added in v0.2.0

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

MemoryToolService implements remember/recall handlers in the tool layer.

func NewMemoryToolService added in v0.2.0

func NewMemoryToolService(store memory.ToolBackend) *MemoryToolService

NewMemoryToolService creates a tool-layer memory service.

func (*MemoryToolService) HandleContext added in v0.2.0

func (s *MemoryToolService) HandleContext(exec ExecutionContext, args map[string]any) (ToolCallResult, error)

HandleContext binds cancellation per request without mutating the shared service. Identity/authorization continues to be supplied by the host.

func (*MemoryToolService) HandleHygiene added in v0.2.0

func (s *MemoryToolService) HandleHygiene(args map[string]any) (string, error)

func (*MemoryToolService) HandleRecall added in v0.2.0

func (s *MemoryToolService) HandleRecall(args map[string]any) (string, error)

func (*MemoryToolService) HandleRecallDetailed added in v0.2.0

func (s *MemoryToolService) HandleRecallDetailed(args map[string]any) (ToolCallResult, error)

func (*MemoryToolService) HandleRemember added in v0.2.0

func (s *MemoryToolService) HandleRemember(args map[string]any) (string, error)

type NapCatCrossGroupReadConfig added in v0.2.0

type NapCatCrossGroupReadConfig struct {
	Enabled             bool
	RequireConfirmation bool
	AllowedGroups       []string
	BlockedGroups       []string
	LogAccess           bool
}

NapCatCrossGroupReadConfig is intentionally opt-in. A blank configuration is denied even if the tool is registered manually.

type NapCatGroupReader added in v0.2.0

type NapCatGroupReader interface {
	GetGroupMessageHistory(context.Context, string, int, int) ([]napcat.GroupMessage, error)
	GetGroupInfo(context.Context, string) (napcat.GroupInfo, error)
	ListGroups(context.Context) ([]napcat.GroupInfo, error)
}

NapCatGroupReader is the narrow live-gateway capability required by the cross-group history tool. Keeping it as an interface makes the policy layer testable and prevents arbitrary OneBot actions from reaching the model.

type Observation

type Observation struct {
	ImageURL     string
	Kind         string
	FrameID      string
	CapturedAt   time.Time
	FilePath     string
	MimeType     string
	Width        int
	Height       int
	ScaleFactor  float64
	DisplayID    string
	ActiveWindow string
	WindowBounds Rect
	SHA256       string
	ImageData    []byte
	Metadata     map[string]any
}

Observation is a structured non-text tool result. Computer-use tools use it to return a screenshot path and frame metadata for the agent to feed back to a vision-capable provider. The type intentionally remains provider-neutral.

type OpenCLIConfig

type OpenCLIConfig = opencli.Config

type OutputCompressConfig

type OutputCompressConfig struct {
	MaxChars       int  // 最大字符数(默认 2048)
	EnableTruncate bool // 是否启用截断
	EnableDedup    bool // 是否启用去重
	EnableSummary  bool // 是否启用摘要(需要 LLM 支持)
}

OutputCompressConfig 工具输出压缩配置

func DefaultOutputCompressConfig

func DefaultOutputCompressConfig() OutputCompressConfig

DefaultOutputCompressConfig 返回默认压缩配置

type ParallelDelegateResult added in v0.2.0

type ParallelDelegateResult = delegateruntime.ParallelDelegateResult

type ParallelDelegateTask added in v0.2.0

type ParallelDelegateTask = delegateruntime.ParallelDelegateTask

type Param

type Param struct {
	Type        string
	Description string
	Required    bool
	Default     any
	// Schema adds nested JSON Schema fields such as items and properties.
	Schema map[string]any
}

Param 代表工具参数

type PendingApproval

type PendingApproval = approval.Pending

type PermissionLevel

type PermissionLevel int

PermissionLevel 工具权限级别

const (
	PermAuto    PermissionLevel = iota // 自动批准(只读/安全操作)
	PermApprove                        // 需要用户批准(写操作/网络请求)
	PermDeny                           // 禁止使用
)

func (PermissionLevel) String

func (p PermissionLevel) String() string

type PrioritizedTask added in v0.2.0

type PrioritizedTask = delegateruntime.PrioritizedTask

type PriorityTaskQueue added in v0.2.0

type PriorityTaskQueue = delegateruntime.PriorityTaskQueue

type Quota

type Quota struct {
	ToolName string    `json:"tool_name"`
	Limit    int       `json:"limit"`    // 最大调用次数 (0 = 无限)
	Window   string    `json:"window"`   // 时间窗口: "hourly", "daily", "monthly"
	Used     int       `json:"used"`     // 已使用次数
	ResetAt  time.Time `json:"reset_at"` // 配额重置时间
}

Quota 工具使用配额

type RAGToolService added in v0.2.0

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

RAGToolService implements rag_search/rag_index handlers in the tool layer.

func NewRAGToolService added in v0.2.0

func NewRAGToolService(manager rag.Backend) *RAGToolService

NewRAGToolService creates a tool-layer RAG service.

func (*RAGToolService) HandleIndex added in v0.2.0

func (s *RAGToolService) HandleIndex(args map[string]any) (string, error)

func (*RAGToolService) HandleSearch added in v0.2.0

func (s *RAGToolService) HandleSearch(args map[string]any) (string, error)

type Rect

type Rect struct {
	X      int `json:"x,omitempty"`
	Y      int `json:"y,omitempty"`
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
}

Rect is kept provider-neutral so the tool package does not need to import the platform-specific computer package.

type Registry

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

Registry 管理所有已注册的工具

Example
package main

import (
	"fmt"

	tool "github.com/yurika0211/luckyagent-tools"
)

func main() {
	registry := tool.NewRegistry()
	registry.Register(&tool.Tool{
		Name:       "echo",
		Permission: tool.PermAuto,
		Parameters: map[string]tool.Param{"text": {Type: "string", Required: true}},
		Handler: func(args map[string]any) (string, error) {
			return fmt.Sprint(args["text"]), nil
		},
	})
	output, err := registry.Call("echo", map[string]any{"text": "hello"})
	if err != nil {
		panic(err)
	}
	fmt.Println(output)
}
Output:
hello

func NewRegistry

func NewRegistry() *Registry

NewRegistry 创建工具注册表

func (*Registry) Call

func (r *Registry) Call(name string, args map[string]any) (string, error)

Call 调用工具

func (*Registry) CallDetailed

func (r *Registry) CallDetailed(name string, args map[string]any) (ToolCallResult, error)

func (*Registry) CallDetailedWithContext

func (r *Registry) CallDetailedWithContext(name string, args map[string]any, exec ExecutionContext) (ToolCallResult, error)

CallDetailedWithContext dispatches a tool while preserving request-local context. Context-aware handlers take precedence over legacy handlers.

func (*Registry) CallDetailedWithShellContext

func (r *Registry) CallDetailedWithShellContext(name string, args map[string]any, sc *ShellContext) (ToolCallResult, error)

func (*Registry) CallDetailedWithShellExecutionContext

func (r *Registry) CallDetailedWithShellExecutionContext(name string, args map[string]any, sc *ShellContext, exec ExecutionContext) (ToolCallResult, error)

CallDetailedWithShellExecutionContext combines shell injection and request-local context for context-aware tools.

func (*Registry) CallWithContext

func (r *Registry) CallWithContext(name string, args map[string]any, exec ExecutionContext) (string, error)

CallWithContext dispatches a context-aware handler and returns its text output. It is a compatibility helper for callers that do not need metadata.

func (*Registry) CallWithShellContext

func (r *Registry) CallWithShellContext(name string, args map[string]any, sc *ShellContext) (string, error)

CallWithShellContext 执行工具并注入 shell 上下文 对于 ShellAware 的工具,自动在 args 中注入 _cwd 和 _env

func (*Registry) CheckPermission

func (r *Registry) CheckPermission(name string) (PermissionLevel, error)

CheckPermission 检查工具权限(不执行)

func (*Registry) Count

func (r *Registry) Count() int

Count 返回工具数量

func (*Registry) Disable

func (r *Registry) Disable(name string) error

Disable 禁用工具

func (*Registry) Enable

func (r *Registry) Enable(name string) error

Enable 启用工具

func (*Registry) FormatToolList

func (r *Registry) FormatToolList() string

FormatToolList 格式化工具列表为文本

func (*Registry) Get

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

Get 获取工具。name 可以是内部注册名,也可以是模型侧的 OpenAI 兼容名。

func (*Registry) List

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

List 列出所有工具

func (*Registry) ListByCategory

func (r *Registry) ListByCategory(cat Category) []*Tool

ListByCategory 按分类列出工具

func (*Registry) ListEnabled

func (r *Registry) ListEnabled() []*Tool

ListEnabled 列出所有启用的工具

func (*Registry) ListModelVisible

func (r *Registry) ListModelVisible() []*Tool

ListModelVisible returns enabled tools that should be exposed to the model.

func (*Registry) Register

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

Register 注册工具

func (*Registry) ReplaceCategory added in v0.2.2

func (r *Registry) ReplaceCategory(category Category, tools []*Tool) error

ReplaceCategory publishes a complete external catalog atomically. A name collision with another category leaves the previous catalog untouched.

func (*Registry) SetPermissionOverride

func (r *Registry) SetPermissionOverride(name string, perm PermissionLevel) error

SetPermissionOverride 设置工具权限覆盖

func (*Registry) Unregister

func (r *Registry) Unregister(name string)

Unregister 注销工具

type RouteRule

type RouteRule struct {
	Name        string // 规则名
	Priority    int    // 优先级(越高越先匹配)
	ToolPattern string // 工具名匹配模式(支持 * 通配符)
	Target      string // 目标工具名
	Enabled     bool   // 是否启用
}

RouteRule 路由规则

type SandboxConfig

type SandboxConfig struct {
	MaxExecutionTime time.Duration // maximum time a tool can run
	MaxOutputSize    int           // maximum output size in bytes
	EnableAuditLog   bool          // whether to record audit logs
}

SandboxConfig holds configuration for the skill execution sandbox.

func DefaultSandboxConfig

func DefaultSandboxConfig() SandboxConfig

DefaultSandboxConfig returns the default sandbox configuration.

type SandboxError

type SandboxError struct {
	ToolName string `json:"tool_name"`
	Message  string `json:"message"`
	Panic    bool   `json:"panic,omitempty"`
	Timeout  bool   `json:"timeout,omitempty"`
	Oversize bool   `json:"oversize,omitempty"`
}

SandboxError is a structured error returned from sandbox execution.

func (*SandboxError) Error

func (e *SandboxError) Error() string

type ScanFinding

type ScanFinding struct {
	Rule     string `json:"rule"`
	Severity string `json:"severity"`
	Path     string `json:"path,omitempty"`
	Line     int    `json:"line,omitempty"`
	Detail   string `json:"detail"`
}

ScanFinding is one rule hit. Path is relative to the staged skill root.

type ScanReport

type ScanReport struct {
	Findings  []ScanFinding `json:"findings"`
	Files     int           `json:"files"`
	Bytes     int64         `json:"bytes"`
	Blocked   bool          `json:"blocked"`
	Warnings  int           `json:"warnings"`
	Digest    string        `json:"digest"`
	ScannedAt time.Time     `json:"scanned_at"`
}

ScanReport is the result of the static pass over a staged skill.

func ScanSkillDir

func ScanSkillDir(skillDir string, limits InstallLimits) (*ScanReport, error)

ScanSkillDir runs every static rule over a staged skill directory. It executes nothing and makes no network calls, which is what lets it run before the trial load. Directories on the strip list are deleted as a side effect.

func (*ScanReport) BlockingFindings

func (r *ScanReport) BlockingFindings() []ScanFinding

BlockingFindings returns only the findings that make an install impossible.

type Services added in v0.2.0

Services groups tool-layer business services and owns their registration wiring.

func NewServices added in v0.2.0

func NewServices(searchCfg *WebSearchConfig, opencliCfg *OpenCLIConfig, defaultImageProvider string, mediaProcessor *multimodal.Processor, imageGenerator multimodal.ImageGenerator, imageGenDefaults ImageGenerationDefaults, speechSynthesizer multimodal.SpeechSynthesizer, ttsDefaults TTSDefaults, mem memory.ToolBackend, ragMgr rag.Backend, delegate *DelegateManager, policies ...FilesystemPolicy) *Services

NewServices creates a tool service container.

func (*Services) Close added in v0.2.0

func (s *Services) Close() error

Close releases optional long-lived tool runtimes such as Codex App Server and the Grok agent process.

func (*Services) PendingApprovals added in v0.2.0

func (s *Services) PendingApprovals() []PendingApproval

PendingApprovals aggregates optional external coding-agent bridges. Current Codex and Grok services resolve approvals through their own tools, so this list stays empty until those bridges expose a snapshot again.

func (*Services) RegisterCoreTools added in v0.2.0

func (s *Services) RegisterCoreTools(r *Registry)

RegisterCoreTools registers builtins and delegate tools through the service container.

func (*Services) ReloadMediaTools added in v0.2.0

func (s *Services) ReloadMediaTools(r *Registry, defaultImageProvider string, mediaProcessor *multimodal.Processor, imageGenerator multimodal.ImageGenerator, imageGenDefaults ImageGenerationDefaults, speechSynthesizer multimodal.SpeechSynthesizer, ttsDefaults TTSDefaults)

ReloadMediaTools updates the three media tools without rebuilding unrelated registry entries such as skills, MCP servers, or scheduled-task tools.

func (*Services) RespondApproval added in v0.2.0

func (s *Services) RespondApproval(ctx context.Context, provider, approvalID, decision string) (PendingApproval, error)

RespondApproval resolves a pending approval using the provider-neutral API.

func (*Services) RevokeEphemeralSession added in v0.2.0

func (s *Services) RevokeEphemeralSession(sessionID string)

RevokeEphemeralSession removes temporary credential tools for one session.

func (*Services) SetComputerUseService added in v0.2.0

func (s *Services) SetComputerUseService(service *ComputerUseToolService) *Services

SetComputerUseService attaches the optional desktop automation tools to the builtin registration set. It is separate from NewServices so existing callers remain source-compatible while computer backends stay optional.

type ShellContext

type ShellContext struct {
	Cwd string            // 当前工作目录
	Env map[string]string // 自定义环境变量
}

ShellContext 提供 shell 环境状态给工具调用

type SkillCandidate

type SkillCandidate struct {
	Name   string `json:"name"`
	Score  int    `json:"score"`
	Reason string `json:"reason"`
}

type SkillDocSection

type SkillDocSection struct {
	Heading string `json:"heading"`
	Level   int    `json:"level"`
	Start   int    `json:"start"`
	End     int    `json:"end"`
}

type SkillExecutor

type SkillExecutor struct {
}

SkillExecutor is the single execution adapter for skill-defined tools. Loader discovers skill metadata; registry owns lifecycle; executor turns a loaded skill tool definition into a callable Tool handler.

func NewSkillExecutor

func NewSkillExecutor() *SkillExecutor

NewSkillExecutor creates the default skill executor.

func (*SkillExecutor) Execute

func (e *SkillExecutor) Execute(skill *SkillInfo, toolDef SkillToolDef, args map[string]any) (string, error)

Execute runs one skill tool through the unified skill execution path.

func (*SkillExecutor) HandlerFor

func (e *SkillExecutor) HandlerFor(skill *SkillInfo, toolDef SkillToolDef) (func(args map[string]any) (string, error), error)

HandlerFor returns the callable handler for one skill tool definition.

type SkillInfo

type SkillInfo struct {
	Name        string
	Aliases     []string
	Description string
	Summary     string // v0.36.0: SKILL.md 精简摘要,用于注入 system prompt
	Dir         string
	Tools       []SkillToolDef
	Available   bool
}

SkillInfo Skill 元信息

type SkillLoader

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

SkillLoader 从 SKILL.md 文件加载工具定义

func NewSkillLoader

func NewSkillLoader(skillsDir string) *SkillLoader

NewSkillLoader 创建 Skill 加载器

func (*SkillLoader) Load

func (sl *SkillLoader) Load(path string) (*SkillInfo, error)

Load 加载单个 SKILL.md

func (*SkillLoader) LoadAll

func (sl *SkillLoader) LoadAll() ([]*SkillInfo, error)

LoadAll 加载所有 Skill

func (*SkillLoader) WithCLIInspect

func (sl *SkillLoader) WithCLIInspect(enabled bool, timeout time.Duration) *SkillLoader

WithCLIInspect toggles the `--help` probe and sets its per-invocation timeout. Pass enabled=false for a parse-only load that executes nothing.

func (*SkillLoader) WithProbeEnv

func (sl *SkillLoader) WithProbeEnv(env []string) *SkillLoader

WithProbeEnv replaces the environment handed to the `--help` probe. Use it to keep credentials in the parent environment out of reach of skill code that has not been reviewed yet.

type SkillMetadata

type SkillMetadata struct {
	Name         string            `json:"name"`
	Version      string            `json:"version"`
	Author       string            `json:"author"`
	Description  string            `json:"description"`
	Dir          string            `json:"dir"`
	Tools        []string          `json:"tools"`        // tool names provided by this skill
	Dependencies []string          `json:"dependencies"` // names of skills this one depends on
	State        SkillState        `json:"state"`
	LoadedAt     time.Time         `json:"loaded_at"`
	Error        string            `json:"error,omitempty"`
	Labels       map[string]string `json:"labels,omitempty"`
}

SkillMetadata holds rich metadata about a skill plugin.

type SkillReadContent

type SkillReadContent struct {
	Text       string `json:"text"`
	Offset     int    `json:"offset"`
	NextOffset int    `json:"next_offset,omitempty"`
	Truncated  bool   `json:"truncated"`
	TotalChars int    `json:"total_chars"`
}

type SkillRegistry

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

SkillRegistry manages skill plugin lifecycle: discover → load → register → enable/disable → unload.

func NewSkillRegistry

func NewSkillRegistry(registry *Registry, loader *SkillLoader) *SkillRegistry

NewSkillRegistry creates a new SkillRegistry.

func (*SkillRegistry) Count

func (sr *SkillRegistry) Count() int

Count returns the number of skills.

func (*SkillRegistry) CountByState

func (sr *SkillRegistry) CountByState(state SkillState) int

CountByState returns the number of skills in a given state.

func (*SkillRegistry) Disable

func (sr *SkillRegistry) Disable(name string) error

Disable disables a skill's tools and transitions to SkillDisabled.

func (*SkillRegistry) Discover

func (sr *SkillRegistry) Discover() ([]*SkillMetadata, error)

Discover scans the skill directory and records all discovered skills.

func (*SkillRegistry) Enable

func (sr *SkillRegistry) Enable(name string) error

Enable enables a skill's tools and transitions to SkillEnabled.

func (*SkillRegistry) EnableAll

func (sr *SkillRegistry) EnableAll() error

EnableAll enables every registered or disabled skill.

func (*SkillRegistry) Get

func (sr *SkillRegistry) Get(name string) (*SkillMetadata, bool)

Get retrieves metadata for a skill.

func (*SkillRegistry) HealthCheck

func (sr *SkillRegistry) HealthCheck() map[string][]string

HealthCheck verifies that all tools for enabled skills are callable. Returns a map of skill name -> list of unhealthy tool names.

func (*SkillRegistry) List

func (sr *SkillRegistry) List() []*SkillMetadata

List returns all skill metadata sorted by name.

func (*SkillRegistry) ListByState

func (sr *SkillRegistry) ListByState(state SkillState) []*SkillMetadata

ListByState returns skills filtered by state.

func (*SkillRegistry) Load

func (sr *SkillRegistry) Load(name string) error

Load parses a specific skill's SKILL.md and transitions it to SkillLoaded.

func (*SkillRegistry) LoadAll

func (sr *SkillRegistry) LoadAll() error

LoadAll loads all discovered skills.

func (*SkillRegistry) Register

func (sr *SkillRegistry) Register(name string) error

Register registers a skill's tools into the tool Registry and transitions to SkillRegistered.

func (*SkillRegistry) RegisterAll

func (sr *SkillRegistry) RegisterAll() error

RegisterAll registers all loaded skills.

func (*SkillRegistry) Reload

func (sr *SkillRegistry) Reload(name string) error

Reload reloads a single skill: unload → load → register → re-enable if it was enabled. Discover() is deliberately not called: it rebuilds metadata for every skill directory, so reloading one skill would drag all the others back to SkillDiscovered while their tools stayed registered.

func (*SkillRegistry) ResolveLoadOrder

func (sr *SkillRegistry) ResolveLoadOrder() ([]string, error)

ResolveLoadOrder returns skill names in dependency-safe load order. Skills with no dependencies come first; skills that depend on others come after. Returns an error if a circular dependency is detected.

func (*SkillRegistry) SetExecutor

func (sr *SkillRegistry) SetExecutor(executor *SkillExecutor)

SetExecutor replaces the skill executor used when registering skill tools.

func (*SkillRegistry) SetMetadata

func (sr *SkillRegistry) SetMetadata(name string, version, author string, dependencies []string, labels map[string]string) error

SetMetadata sets additional metadata fields on a skill.

func (*SkillRegistry) SkillInfos

func (sr *SkillRegistry) SkillInfos() []*SkillInfo

SkillInfos returns loaded skill definitions sorted by name.

func (*SkillRegistry) Unload

func (sr *SkillRegistry) Unload(name string) error

Unload removes a skill's tools from the registry and transitions to SkillUnloaded.

func (*SkillRegistry) UnloadAll

func (sr *SkillRegistry) UnloadAll()

UnloadAll unregisters every skill's tools. It is used when a whole registry generation is retired, so that the outgoing generation's skill_<name>_<tool> entries do not linger in the tool Registry. It takes no lock of its own; the per-call locking inside List and Unload is sufficient.

func (*SkillRegistry) UnwatchState

func (sr *SkillRegistry) UnwatchState(id string)

UnwatchState removes a state change watcher.

func (*SkillRegistry) Validate

func (sr *SkillRegistry) Validate(name string) error

Validate checks whether a loaded skill can be registered safely.

func (*SkillRegistry) ValidateAll

func (sr *SkillRegistry) ValidateAll() error

ValidateAll checks all loaded skills before registration.

func (*SkillRegistry) WatchState

func (sr *SkillRegistry) WatchState(id string, callback func(name string, from, to SkillState))

WatchState registers a callback for skill state changes.

type SkillSandbox

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

SkillSandbox provides an isolated execution environment for skill tools.

func NewSkillSandbox

func NewSkillSandbox(registry *Registry, config SandboxConfig) *SkillSandbox

NewSkillSandbox creates a new skill execution sandbox.

func (*SkillSandbox) AuditLog

func (sb *SkillSandbox) AuditLog() []AuditEntry

AuditLog returns a copy of the audit log.

func (*SkillSandbox) AuditLogForSkill

func (sb *SkillSandbox) AuditLogForSkill(skillName string) []AuditEntry

AuditLogForSkill returns audit entries for a specific skill.

func (*SkillSandbox) AuditLogForTool

func (sb *SkillSandbox) AuditLogForTool(toolName string) []AuditEntry

AuditLogForTool returns audit entries for a specific tool.

func (*SkillSandbox) AuditStats

func (sb *SkillSandbox) AuditStats() AuditStats

AuditStats returns summary statistics from the audit log.

func (*SkillSandbox) ClearAuditLog

func (sb *SkillSandbox) ClearAuditLog()

ClearAuditLog clears the audit log.

func (*SkillSandbox) Execute

func (sb *SkillSandbox) Execute(toolName string, args map[string]any) (string, error)

Execute runs a tool in the sandbox with timeout, resource limits, and error recovery.

func (*SkillSandbox) ExecuteWithContext

func (sb *SkillSandbox) ExecuteWithContext(ctx context.Context, toolName string, args map[string]any) (string, error)

ExecuteWithContext runs a tool in the sandbox with a context for cancellation.

type SkillState

type SkillState int

SkillState represents the lifecycle state of a skill plugin.

const (
	SkillDiscovered SkillState = iota // Skill directory found, not yet loaded
	SkillLoaded                       // SKILL.md parsed, metadata available
	SkillRegistered                   // Tools registered in Registry
	SkillEnabled                      // Skill is active and tools are callable
	SkillDisabled                     // Skill is loaded but tools are disabled
	SkillError                        // Skill encountered an error
	SkillUnloaded                     // Skill has been unloaded
)

func (SkillState) String

func (s SkillState) String() string

type SkillToolDef

type SkillToolDef struct {
	Name          string
	Description   string
	Parameters    map[string]Param
	Handler       func(args map[string]any) (string, error) // 需要外部注入
	Command       []string
	ExposeToModel bool
}

SkillToolDef Skill 中定义的工具

type SkillToolService

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

SkillToolService wraps skill tool registration and skill_read access.

func NewSkillToolService

func NewSkillToolService(skills []*SkillInfo) *SkillToolService

NewSkillToolService creates a skill tool service.

func (*SkillToolService) HandleRead

func (s *SkillToolService) HandleRead(args map[string]any) (string, error)

HandleRead reads a skill's SKILL.md or lists available skills.

func (*SkillToolService) RegisterReadTool

func (s *SkillToolService) RegisterReadTool(r *Registry)

RegisterReadTool registers the skill_read helper without registering skill tools. This lets SkillRegistry own the executable skill-tool lifecycle while the service still exposes skill documentation lookup.

func (*SkillToolService) RegisterSkillTools

func (s *SkillToolService) RegisterSkillTools(r *Registry)

RegisterSkillTools registers skill-derived tools and skill_read onto the registry.

type SubTier

type SubTier int

SubTier 订阅等级

const (
	SubFree       SubTier = iota // 免费级:基础工具
	SubBasic                     // 基础级:常用工具
	SubPro                       // 专业级:全部工具
	SubEnterprise                // 企业级:全部工具 + 优先级
)

func ParseSubTier

func ParseSubTier(s string) (SubTier, error)

ParseSubTier 从字符串解析订阅等级

func (SubTier) String

func (t SubTier) String() string

type SubscriptionManager

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

SubscriptionManager 订阅管理器

func NewSubscriptionManager

func NewSubscriptionManager() *SubscriptionManager

NewSubscriptionManager 创建订阅管理器

func (*SubscriptionManager) CanUse

func (sm *SubscriptionManager) CanUse(userID, toolName string) bool

CanUse 检查用户是否可以使用某工具

func (*SubscriptionManager) GetSubscription

func (sm *SubscriptionManager) GetSubscription(userID string) *UserSubscription

GetSubscription 获取用户订阅

func (*SubscriptionManager) GetTierConfig

func (sm *SubscriptionManager) GetTierConfig(tier SubTier) TierConfig

GetTierConfig 获取订阅等级配置

func (*SubscriptionManager) ListSubscriptions

func (sm *SubscriptionManager) ListSubscriptions() []UserSubscription

ListSubscriptions 列出所有订阅

func (*SubscriptionManager) RecordUsage

func (sm *SubscriptionManager) RecordUsage(userID, toolName string)

RecordUsage 记录使用

func (*SubscriptionManager) SetTierConfig

func (sm *SubscriptionManager) SetTierConfig(tier SubTier, config TierConfig)

SetTierConfig 设置订阅等级配置

func (*SubscriptionManager) Subscribe

func (sm *SubscriptionManager) Subscribe(userID string, tier SubTier, duration time.Duration) error

Subscribe 订阅

func (*SubscriptionManager) Unsubscribe

func (sm *SubscriptionManager) Unsubscribe(userID string)

Unsubscribe 取消订阅

type TTSDefaults added in v0.2.0

type TTSDefaults struct {
	Model  string
	Voice  string
	Format string
	Speed  float64
}

TTSDefaults captures configurable defaults for the text_to_speech tool.

type TaskCache added in v0.2.0

type TaskCache = delegateruntime.TaskCache

type TaskPriority added in v0.2.0

type TaskPriority = delegateruntime.TaskPriority

Compatibility names for the independent delegation engine.

type TaskStatus added in v0.2.0

type TaskStatus = delegateruntime.TaskStatus

type TierConfig

type TierConfig struct {
	Tier              SubTier
	AllowedCategories []Category // 允许的工具分类
	MaxCallsPerDay    int        // 每日最大调用次数 (0 = 无限)
	MaxCallsPerHour   int        // 每小时最大调用次数 (0 = 无限)
	Priority          int        // 优先级 (越高越优先)
}

TierConfig 订阅等级配置

type Tool

type Tool struct {
	Name        string
	Description string
	Parameters  map[string]Param
	// InputSchema preserves a provider's complete JSON Schema, including $defs.
	InputSchema     map[string]any
	Handler         func(args map[string]any) (string, error)
	DetailedHandler func(args map[string]any) (ToolCallResult, error)
	// ContextDetailedHandler is used by tools that need request/session metadata
	// or cancellation. Existing tools can continue using Handler or
	// DetailedHandler without changing their call sites.
	ContextDetailedHandler func(exec ExecutionContext, args map[string]any) (ToolCallResult, error)
	Permission             PermissionLevel // 权限级别
	// PermissionFor reports the permission of one call. Nil uses Permission.
	// A tool that mixes read and write actions uses this so a read does not
	// inherit the approval required by a write.
	PermissionFor func(args map[string]any) PermissionLevel
	Category      Category // 工具分类
	Source        string   // 来源(skill名/mcp server名/builtin)
	Enabled       bool     // 是否启用
	// ShellAware 标记该工具需要 shell 上下文注入(cwd + env)
	ShellAware bool
	// ParallelSafe 标记该工具可安全并发执行(无状态、无副作用冲突)
	// 如 web_search, web_fetch, file_read, current_time, recall 等
	// terminal, file_write 等有状态依赖的工具不应标记
	ParallelSafe bool
	// HiddenFromModel 标记该工具不应暴露给大模型的工具菜单。
	// 适用于内部脚本入口、低层 skill 动作等。
	HiddenFromModel bool
	// PolicySafe allows typed durable-memory policies to execute this tool
	// automatically. Keep false for write, shell, delegation, and control tools.
	PolicySafe bool
}

Tool 代表一个可调用的工具

func AskUserTool

func AskUserTool() *Tool

AskUserTool asks the human for missing information and waits for a reply. The agent loop intercepts this name before the handler runs.

func CSVQueryTool

func CSVQueryTool() *Tool

CSVQueryTool returns rows from a CSV file, optionally filtered by one column.

func CalculateTool

func CalculateTool() *Tool

func CurrentTimeTool

func CurrentTimeTool() *Tool

func DBSchemaTool

func DBSchemaTool() *Tool

DBSchemaTool inspects the schema of a local SQLite database.

func DataQueryTool

func DataQueryTool() *Tool

DataQueryTool extracts a nested field from a JSON or YAML file using dot-path syntax.

func DataTool

func DataTool() *Tool

DataTool reads logs and structured files through one entry.

func DelegateCancelTool added in v0.2.0

func DelegateCancelTool(dm *DelegateManager) *Tool

DelegateCancelTool 创建任务取消工具

func DelegateTaskTool added in v0.2.0

func DelegateTaskTool(dm *DelegateManager) *Tool

DelegateTaskTool 创建子代理委派工具

func DelegateToMCPTool added in v0.2.0

func DelegateToMCPTool(dm *DelegateManager) *Tool

DelegateToMCPTool creates a tool for delegating tasks to MCP servers.

func DelegateToSkillTool added in v0.2.0

func DelegateToSkillTool(dm *DelegateManager) *Tool

DelegateToSkillTool creates a tool for delegating tasks to skills.

func DocumentReadTool

func DocumentReadTool(policies ...FilesystemPolicy) *Tool

func FileDeleteTool

func FileDeleteTool() *Tool

func FileListTool

func FileListTool(policies ...FilesystemPolicy) *Tool

func FileMkdirTool

func FileMkdirTool() *Tool

func FileMoveTool

func FileMoveTool() *Tool

func FilePatchTool

func FilePatchTool() *Tool

func FileReadTool

func FileReadTool(policies ...FilesystemPolicy) *Tool

func FileWriteTool

func FileWriteTool() *Tool

func HTTPRequestTool

func HTTPRequestTool() *Tool

HTTPRequestTool performs a controlled HTTP request and returns the response body.

func ImageAnalyzeTool added in v0.2.0

func ImageAnalyzeTool(processor *multimodal.Processor, defaultProvider string) *Tool

ImageAnalyzeTool analyzes images, screenshots, and simple documents through the multimodal processor.

func ImageGenerateTool added in v0.2.0

func ImageGenerateTool(generator multimodal.ImageGenerator, defaults ImageGenerationDefaults) *Tool

ImageGenerateTool generates images from text prompts and can optionally edit an input image.

func ImageReadTool added in v0.2.0

func ImageReadTool() *Tool

ImageReadTool returns image content to the current model without invoking another model. The agent exposes it only on turns using primary vision.

func ImageTool added in v0.2.0

func ImageTool(processor *multimodal.Processor, defaultProvider string, generator multimodal.ImageGenerator, defaults ImageGenerationDefaults) *Tool

ImageTool inspects or creates images through one entry.

func ListTasksTool added in v0.2.0

func ListTasksTool(dm *DelegateManager) *Tool

ListTasksTool 创建任务列表工具

func LogTool

func LogTool() *Tool

LogTool reads the tail of a local log or searches it for matching lines.

func MemoryHygieneTool

func MemoryHygieneTool(handler func(args map[string]any) (string, error)) *Tool

MemoryHygieneTool audits or cleans dirty memories from the durable vault.

func MemoryTool

func MemoryTool(remember, hygiene func(args map[string]any) (string, error), recall func(args map[string]any) (string, error), recallDetailed func(args map[string]any) (ToolCallResult, error)) *Tool

MemoryTool stores, searches, and cleans durable memory through one entry.

func NapCatReadGroupTool added in v0.2.0

func NapCatReadGroupTool(reader NapCatGroupReader, cfg NapCatCrossGroupReadConfig) *Tool

NapCatReadGroupTool creates the model-visible, policy-enforced cross-group history tool. It must only be registered by an active NapCat gateway when cross_group_read.enabled is true.

func OpenCLITool

func OpenCLITool(cfg *OpenCLIConfig, fallbackCfg *WebSearchConfig) *Tool

OpenCLITool exposes OpenCLI as one entrypoint for website adapters, browser automation, URL-to-Markdown extraction, and raw passthrough commands.

func RAGIndexTool

func RAGIndexTool(handler func(args map[string]any) (string, error)) *Tool

RAGIndexTool indexes a file or directory into the local knowledge base.

func RAGSearchTool

func RAGSearchTool(handler func(args map[string]any) (string, error)) *Tool

RAGSearchTool searches the local indexed knowledge base.

func RecallTool

func RecallTool(handler func(args map[string]any) (string, error), detailed ...func(args map[string]any) (ToolCallResult, error)) *Tool

RecallTool 搜索记忆工具

func RememberTool

func RememberTool(handler func(args map[string]any) (string, error)) *Tool

RememberTool 保存记忆工具

func RequestCredentialTool

func RequestCredentialTool() *Tool

RequestCredentialTool asks the host to collect a secret through a masked form and store it in the local credential vault. The agent loop intercepts this name before the handler runs, so the model never sees the value.

func SQLQueryTool

func SQLQueryTool() *Tool

SQLQueryTool executes a read-only SQL query against a local SQLite database.

func SubagentTool added in v0.2.0

func SubagentTool(dm *DelegateManager) *Tool

SubagentTool creates, inspects, waits for, and cancels delegated tasks.

func TaskStatusTool added in v0.2.0

func TaskStatusTool(dm *DelegateManager) *Tool

TaskStatusTool 创建任务状态查询工具

func TerminalTool

func TerminalTool() *Tool

func TextToSpeechTool added in v0.2.0

func TextToSpeechTool(synthesizer multimodal.SpeechSynthesizer, defaults TTSDefaults) *Tool

TextToSpeechTool synthesizes speech audio from text and saves it to disk.

func WaitForTasksTool added in v0.2.0

func WaitForTasksTool(dm *DelegateManager) *Tool

WaitForTasksTool waits until every requested delegated task reaches a terminal state. It is read-only and intentionally auto-approved.

func WebFetchTool

func WebFetchTool(cfg *WebSearchConfig) *Tool

func WebSearchTool

func WebSearchTool(cfg *WebSearchConfig) *Tool

func (*Tool) EffectivePermission

func (t *Tool) EffectivePermission(args map[string]any) PermissionLevel

EffectivePermission returns the permission that applies to one call.

func (*Tool) ToOpenAIFormat

func (t *Tool) ToOpenAIFormat() map[string]any

ToOpenAIFormat 转换为 OpenAI function calling 格式

type ToolCallResult

type ToolCallResult struct {
	Output       string
	Metadata     map[string]any
	Observations []Observation
}

type ToolRouter

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

ToolRouter 工具路由器 根据工具名、分类、来源等条件路由到正确的工具

func NewToolRouter

func NewToolRouter(registry *Registry) *ToolRouter

NewToolRouter 创建工具路由器

func (*ToolRouter) AddAlias

func (r *ToolRouter) AddAlias(alias, target string) error

AddAlias 添加别名

func (*ToolRouter) AddRoute

func (r *ToolRouter) AddRoute(rule RouteRule)

AddRoute 添加路由规则

func (*ToolRouter) DisableRoute

func (r *ToolRouter) DisableRoute(name string) error

DisableRoute 禁用路由规则

func (*ToolRouter) EnableRoute

func (r *ToolRouter) EnableRoute(name string) error

EnableRoute 启用路由规则

func (*ToolRouter) FormatRoutes

func (r *ToolRouter) FormatRoutes() string

FormatRoutes 格式化路由规则列表

func (*ToolRouter) ListAliases

func (r *ToolRouter) ListAliases() map[string]string

ListAliases 列出所有别名

func (*ToolRouter) ListRoutes

func (r *ToolRouter) ListRoutes() []RouteRule

ListRoutes 列出所有路由规则

func (*ToolRouter) RemoveAlias

func (r *ToolRouter) RemoveAlias(alias string)

RemoveAlias 移除别名

func (*ToolRouter) RemoveRoute

func (r *ToolRouter) RemoveRoute(name string)

RemoveRoute 移除路由规则

func (*ToolRouter) Resolve

func (r *ToolRouter) Resolve(name string) (string, error)

Resolve 解析工具名(别名 → 路由 → 原名)

type TraceRecord

type TraceRecord struct {
	ID         string `json:"id,omitempty"`
	Status     string `json:"status,omitempty"` // pending | completed | failed
	Name       string `json:"name"`
	Arguments  string `json:"arguments,omitempty"`
	Result     string `json:"result,omitempty"`
	Success    bool   `json:"success"`
	Error      string `json:"error,omitempty"`
	DurationMS int64  `json:"duration_ms,omitempty"`
	Annotation string `json:"annotation"`
}

TraceRecord is a user-safe tool call summary. Pending session calls have no result yet; Success is meaningful only for completed or failed calls.

func NewTraceRecord

func NewTraceRecord(name, arguments, result string, duration time.Duration) TraceRecord

NewTraceRecord creates a trace entry with a deterministic natural-language annotation. It never sends tool data to a model.

func NewTraceRecordWithTemplates

func NewTraceRecordWithTemplates(name, arguments, result string, duration time.Duration, templates map[string]string) TraceRecord

NewTraceRecordWithTemplates creates a trace entry and applies an optional per-tool annotation override before falling back to built-in templates.

type TrialOptions

type TrialOptions struct {
	// ProbeCLI enables the `<script> --help` probe. It executes the staged
	// skill's code, so callers must only set it after the static scan is clean.
	ProbeCLI     bool
	ProbeTimeout time.Duration
	TotalBudget  time.Duration
}

TrialOptions configures the isolated load of a staged skill.

type TrialResult

type TrialResult struct {
	Info       *SkillInfo
	Capability *CapabilitySummary
}

TrialResult is what a user reviews before confirming.

func TrialLoad

func TrialLoad(stagingRoot string, opts TrialOptions) (*TrialResult, error)

TrialLoad parses a staged skill in isolation and reports what it would contribute. stagingRoot is the *parent* of the skill directory: SkillLoader iterates its directory and descends one level, so pointing it at the skill itself would find nothing.

Isolation comes from a throwaway tool.Registry — the live registry is never touched, so a partial or failed trial leaves nothing behind to clean up.

type UsageRecord

type UsageRecord struct {
	ToolName  string        `json:"tool_name"`
	Timestamp time.Time     `json:"timestamp"`
	Duration  time.Duration `json:"duration"`
	Success   bool          `json:"success"`
}

UsageRecord 单次使用记录

type UsageStats

type UsageStats struct {
	ToolName      string        `json:"tool_name"`
	TotalCalls    int           `json:"total_calls"`
	SuccessCalls  int           `json:"success_calls"`
	FailedCalls   int           `json:"failed_calls"`
	TotalDuration time.Duration `json:"total_duration"`
	AvgDuration   time.Duration `json:"avg_duration"`
	LastUsed      time.Time     `json:"last_used"`
}

UsageStats 使用统计

func (UsageStats) Format

func (s UsageStats) Format() string

Format 格式化统计

type UsageTracker

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

UsageTracker 工具使用计量追踪器

func NewUsageTracker

func NewUsageTracker() *UsageTracker

NewUsageTracker 创建用量追踪器

func (*UsageTracker) CheckQuota

func (t *UsageTracker) CheckQuota(userID, toolName string) bool

CheckQuota 检查是否还有配额

func (*UsageTracker) GetAllUsage

func (t *UsageTracker) GetAllUsage(userID string) []UsageStats

GetAllUsage 获取用户所有工具使用统计

func (*UsageTracker) GetQuota

func (t *UsageTracker) GetQuota(userID, toolName string) *Quota

GetQuota 获取配额信息

func (*UsageTracker) GetUsage

func (t *UsageTracker) GetUsage(userID, toolName string) UsageStats

GetUsage 获取用户对某工具的使用统计

func (*UsageTracker) IncrementUsage

func (t *UsageTracker) IncrementUsage(userID, toolName string)

IncrementUsage 增加使用计数(由 Gateway 调用)

func (*UsageTracker) ListQuotas

func (t *UsageTracker) ListQuotas(userID string) []Quota

ListQuotas 列出用户所有配额

func (*UsageTracker) Record

func (t *UsageTracker) Record(userID, toolName string, duration time.Duration, success bool)

Record 记录一次工具使用

func (*UsageTracker) RemoveQuota

func (t *UsageTracker) RemoveQuota(userID, toolName string)

RemoveQuota 移除配额限制

func (*UsageTracker) SetQuota

func (t *UsageTracker) SetQuota(userID, toolName, window string, limit int) error

SetQuota 设置工具使用配额

type UserSubscription

type UserSubscription struct {
	UserID    string    `json:"user_id"`
	Tier      SubTier   `json:"tier"`
	StartedAt time.Time `json:"started_at"`
	ExpiresAt time.Time `json:"expires_at"`
	AutoRenew bool      `json:"auto_renew"`
}

UserSubscription 用户订阅

func (*UserSubscription) IsActive

func (s *UserSubscription) IsActive() bool

IsActive 检查订阅是否有效

type WebSearchConfig

type WebSearchConfig struct {
	Provider   string
	APIKey     string
	BaseURL    string
	MaxResults int
	Proxy      string
}

Directories

Path Synopsis
Package approval defines provider-neutral permission request values.
Package approval defines provider-neutral permission request values.
Package autonomy preserves the legacy tools import path.
Package autonomy preserves the legacy tools import path.
Package codex contains the small JSON-RPC bridge used by LuckyAgent to drive a local `codex app-server` process.
Package codex contains the small JSON-RPC bridge used by LuckyAgent to drive a local `codex app-server` process.
Package collab preserves the legacy tools import path.
Package collab preserves the legacy tools import path.
Package compact summarizes conversation history without owning a model, session store, runtime configuration, or transport.
Package compact summarizes conversation history without owning a model, session store, runtime configuration, or transport.
Package execpolicy evaluates per-turn tool constraints without executing tools.
Package execpolicy evaluates per-turn tool constraints without executing tools.
Package grok contains the small JSON-RPC bridge used by LuckyAgent to drive a local `grok agent stdio` process.
Package grok contains the small JSON-RPC bridge used by LuckyAgent to drive a local `grok agent stdio` process.
Package hitl coordinates in-process human approval and input requests.
Package hitl coordinates in-process human approval and input requests.
Package memory defines LuckyAgent-owned contracts and evidence values.
Package memory defines LuckyAgent-owned contracts and evidence values.
diagnostic
Package diagnostic holds optional backend inspection and tuning values.
Package diagnostic holds optional backend inspection and tuning values.
Package multimodal provides multi-modal input processing for LuckyAgent, supporting image, audio, and video understanding through pluggable providers.
Package multimodal provides multi-modal input processing for LuckyAgent, supporting image, audio, and video understanding through pluggable providers.
Package search — engine implementations (curl-based, no external Go deps).
Package search — engine implementations (curl-based, no external Go deps).
Package skillroute matches natural-language requests to immutable skill descriptions.
Package skillroute matches natural-language requests to immutable skill descriptions.
Package task preserves the legacy tools import path.
Package task preserves the legacy tools import path.
Package workflow provides DAG-based workflow orchestration for in-process applications.
Package workflow provides DAG-based workflow orchestration for in-process applications.

Jump to

Keyboard shortcuts

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