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

tool

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 43 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.1.0

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

The embedding host owns tool selection and approval prompts, Agent execution, memory and RAG backends, delegation, scheduled tasks, ephemeral credentials, computer/media backends, and external coding-agent bridges. 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.

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 . ./search

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.

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 SkillVersion = "v0.5.0"

SkillVersion is the current skill plugin system version.

Variables

This section is empty.

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 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 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 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 ApprovalOption

type ApprovalOption struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	Kind  string `json:"kind,omitempty"`
}

ApprovalOption is the client-facing choice for a pending external-agent permission request. ID is the exact value accepted by the provider bridge.

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 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 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 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 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 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 struct {
	Provider  string           `json:"provider"`
	ID        string           `json:"id"`
	Method    string           `json:"method,omitempty"`
	ThreadID  string           `json:"thread_id,omitempty"`
	SessionID string           `json:"session_id,omitempty"`
	TurnID    string           `json:"turn_id,omitempty"`
	Reason    string           `json:"reason,omitempty"`
	Summary   string           `json:"summary,omitempty"`
	Params    map[string]any   `json:"params,omitempty"`
	Options   []ApprovalOption `json:"options"`
	CreatedAt time.Time        `json:"created_at"`
}

PendingApproval is deliberately provider-neutral so HTTP and mobile clients do not need to know the Codex JSON-RPC or Grok ACP wire formats.

type PermissionLevel

type PermissionLevel int

PermissionLevel 工具权限级别

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

func (PermissionLevel) String

func (p PermissionLevel) String() string

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 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) 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 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 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
	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 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 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 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 TerminalTool

func TerminalTool() *Tool

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 search — engine implementations (curl-based, no external Go deps).
Package search — engine implementations (curl-based, no external Go deps).

Jump to

Keyboard shortcuts

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