tools

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: May 13, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func RunShellArgumentsContainNetworkTarget

func RunShellArgumentsContainNetworkTarget(rawArguments string) bool

RunShellArgumentsContainNetworkTarget reports whether serialized run_shell tool arguments (JSON) contain a network-targeted command.

func RunShellCommandHasNetworkTarget

func RunShellCommandHasNetworkTarget(command string) bool

RunShellCommandHasNetworkTarget reports whether a run_shell command string contains an explicit network target URL.

func RunWorkerProcess

func RunWorkerProcess(ctx context.Context, stdin io.Reader, stdout io.Writer) error

func ValidateSystemSandboxRuntime

func ValidateSystemSandboxRuntime(sandboxEnabled bool, mode string) error

ValidateSystemSandboxRuntime verifies whether the configured system sandbox mode is usable in the current runtime. It is fail-closed for required mode.

func ValidateToolSpec

func ValidateToolSpec(spec ToolSpec) error

Types

type AgentInfo added in v0.1.8

type AgentInfo struct {
	Name        string
	Description string
}

type ApplyPatchTool

type ApplyPatchTool struct{}

func (ApplyPatchTool) Definition

func (ApplyPatchTool) Definition() llm.ToolDefinition

func (ApplyPatchTool) Run

Example
workspace, err := os.MkdirTemp("", "apply-patch-example")
if err != nil {
	fmt.Println("error:", err)
	return
}
defer os.RemoveAll(workspace)

path := filepath.Join(workspace, "sample.txt")
if err := os.WriteFile(path, []byte("alpha\nbeta\n"), 0o644); err != nil {
	fmt.Println("error:", err)
	return
}

tool := ApplyPatchTool{}
payload, _ := json.Marshal(map[string]any{
	"patch": "*** Begin Patch\n*** Update File: sample.txt\n@@\n alpha\n-beta\n+gamma\n*** End Patch",
})
if _, err := tool.Run(context.Background(), payload, &ExecutionContext{Workspace: workspace, Session: session.New(workspace)}); err != nil {
	fmt.Println("error:", err)
	return
}

data, err := os.ReadFile(path)
if err != nil {
	fmt.Println("error:", err)
	return
}
fmt.Print(string(data))
Output:
alpha
gamma

type ApprovalDecision added in v0.1.6

type ApprovalDecision struct {
	Disposition ApprovalDisposition
}

func NormalizeApprovalDecision added in v0.1.6

func NormalizeApprovalDecision(d ApprovalDecision) ApprovalDecision

func (ApprovalDecision) Approved added in v0.1.6

func (d ApprovalDecision) Approved() bool

func (ApprovalDecision) ReusableForAllTools added in v0.1.6

func (d ApprovalDecision) ReusableForAllTools() bool

func (ApprovalDecision) ReusableForSameTool added in v0.1.6

func (d ApprovalDecision) ReusableForSameTool() bool

type ApprovalDisposition added in v0.1.6

type ApprovalDisposition string
const (
	ApprovalApproveOnce            ApprovalDisposition = "approve_once"
	ApprovalApproveSameToolSession ApprovalDisposition = "approve_same_tool_session"
	ApprovalApproveAllSession      ApprovalDisposition = "approve_all_session"
	ApprovalDeny                   ApprovalDisposition = "deny"
)

type ApprovalHandler

type ApprovalHandler func(ApprovalRequest) (ApprovalDecision, error)

type ApprovalRequest

type ApprovalRequest struct {
	ToolName string
	Command  string
	Reason   string
}

type ArgumentDecoder

type ArgumentDecoder interface {
	Decode(string, ResolvedTool) (json.RawMessage, error)
}

type DelegateSubAgentError

type DelegateSubAgentError struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	Retryable bool   `json:"retryable"`
}

type DelegateSubAgentRequest

type DelegateSubAgentRequest struct {
	Agent           string                `json:"agent"`
	Task            string                `json:"task"`
	Scope           DelegateSubAgentScope `json:"scope"`
	Timeout         string                `json:"timeout"`
	Isolation       string                `json:"isolation"`
	Output          string                `json:"output"`
	RunInBackground bool                  `json:"run_in_background"`
	ResumeSessionID string                `json:"resume_session_id,omitempty"`
}

type DelegateSubAgentResult

type DelegateSubAgentResult struct {
	OK                  bool                   `json:"ok"`
	Status              string                 `json:"status,omitempty"`
	InvocationID        string                 `json:"invocation_id"`
	Agent               string                 `json:"agent"`
	TaskID              string                 `json:"task_id,omitempty"`
	ResultReadTool      string                 `json:"result_read_tool,omitempty"`
	StopTool            string                 `json:"stop_tool,omitempty"`
	Summary             string                 `json:"summary,omitempty"`
	Content             string                 `json:"content,omitempty"`
	Error               *DelegateSubAgentError `json:"error,omitempty"`
	Transcript          []TranscriptMessage    `json:"transcript,omitempty"`
	TranscriptSessionID string                 `json:"transcript_session_id,omitempty"`
	Task                string                 `json:"task,omitempty"`
	ModifiedFiles       []string               `json:"modified_files,omitempty"`
	Worktree            *WorktreeInfo          `json:"worktree,omitempty"`
	// ToolCalls carries structured tool call records from the subagent session.
	// Populated by the executor for TUI restoration; excluded from JSON via
	// json:"-" so it never reaches the parent LLM context.
	ToolCalls []SubAgentToolCallRecord `json:"-"`
}

type DelegateSubAgentScope

type DelegateSubAgentScope struct {
	Paths   []string `json:"paths"`
	Symbols []string `json:"symbols"`
}

type DelegateSubAgentTool

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

func NewDelegateSubAgentTool added in v0.1.8

func NewDelegateSubAgentTool(agents []AgentInfo) DelegateSubAgentTool

func (DelegateSubAgentTool) Definition

func (t DelegateSubAgentTool) Definition() llm.ToolDefinition

func (DelegateSubAgentTool) Run

func (DelegateSubAgentTool) Spec

type DiffFile added in v0.1.8

type DiffFile struct {
	Path       string     `json:"path"`
	NewPath    string     `json:"new_path,omitempty"`
	ChangeType string     `json:"change_type"` // add, delete, modify, move
	Added      int        `json:"added"`
	Removed    int        `json:"removed"`
	Hunks      []DiffHunk `json:"hunks"`
	Truncated  bool       `json:"truncated"`
}

DiffFile describes changes to a single file.

type DiffHunk added in v0.1.8

type DiffHunk struct {
	OldStart int      `json:"old_start"`
	OldLines int      `json:"old_lines"`
	NewStart int      `json:"new_start"`
	NewLines int      `json:"new_lines"`
	Lines    []string `json:"lines"`
}

DiffHunk represents one unified-diff hunk.

type DiffPreview added in v0.1.8

type DiffPreview struct {
	Files        []DiffFile `json:"files"`
	TotalFiles   int        `json:"total_files"`
	TotalAdded   int        `json:"total_added"`
	TotalRemoved int        `json:"total_removed"`
	Truncated    bool       `json:"truncated"`
}

DiffPreview carries structured code change detail for editing tools. It is an optional, backward-compatible field added to tool result JSON.

type ExecuteRequest

type ExecuteRequest struct {
	Name    string
	RawArgs string
	Mode    planpkg.AgentMode
	Context *ExecutionContext
}

type ExecuteResult

type ExecuteResult struct {
	Name   string
	Spec   ToolSpec
	Output string
}

type ExecutionContext

type ExecutionContext struct {
	Workspace                 string
	WritableRoots             []string
	ApprovalPolicy            string
	ApprovalMode              string
	AwayPolicy                string
	SandboxEnabled            bool
	SystemSandboxMode         string
	SkipShellApproval         bool
	SandboxEscalationApproved bool
	LeaseID                   string
	RunID                     string
	FSRead                    []string
	FSWrite                   []string
	ExecAllowlist             []sandboxpkg.ExecRule
	NetworkAllowlist          []sandboxpkg.NetworkRule
	Lease                     *sandboxpkg.Lease
	LeaseKeyring              map[string][]byte

	Approval    ApprovalHandler
	Session     *session.Session
	TaskManager runtimepkg.TaskManager
	// Extensions is an optional passthrough hook for callers that need extension context.
	// It stays untyped here to keep tools/extension packages decoupled.
	Extensions       any
	Mode             planpkg.AgentMode
	Stdin            io.Reader
	Stdout           io.Writer
	AllowedTools     map[string]struct{}
	DeniedTools      map[string]struct{}
	DelegateSubAgent DelegateSubAgentHandler
}

type Executor

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

func NewExecutor

func NewExecutor(registry *Registry) *Executor

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, name, rawArgs string, execCtx *ExecutionContext) (string, error)

func (*Executor) ExecuteForMode

func (e *Executor) ExecuteForMode(ctx context.Context, mode planpkg.AgentMode, name, rawArgs string, execCtx *ExecutionContext) (string, error)

func (*Executor) ExecuteRequest

func (e *Executor) ExecuteRequest(ctx context.Context, req ExecuteRequest) (ExecuteResult, error)

type GitDiffTool added in v1.0.0

type GitDiffTool struct{}

func (GitDiffTool) Definition added in v1.0.0

func (GitDiffTool) Definition() llm.ToolDefinition

func (GitDiffTool) Run added in v1.0.0

type GitStatusTool added in v1.0.0

type GitStatusTool struct{}

func (GitStatusTool) Definition added in v1.0.0

func (GitStatusTool) Definition() llm.ToolDefinition

func (GitStatusTool) Run added in v1.0.0

type ListFilesTool

type ListFilesTool struct{}

func (ListFilesTool) Definition

func (ListFilesTool) Definition() llm.ToolDefinition

func (ListFilesTool) Run

type OutputNormalizer

type OutputNormalizer interface {
	Normalize(string, ResolvedTool) string
}

type PermissionEngine

type PermissionEngine interface {
	Check(context.Context, ResolvedTool, *ExecutionContext) error
}

type ReadFileTool

type ReadFileTool struct{}

func (ReadFileTool) Definition

func (ReadFileTool) Definition() llm.ToolDefinition

func (ReadFileTool) Run

type RegisterOptions

type RegisterOptions struct {
	Source       RegistrationSource
	ExtensionID  string
	OriginalName string
	// AllowOriginalNameShadowBuiltin permits extension registrations to reuse an
	// existing builtin original tool name. This is only intended for bridge
	// aliases whose tool key is source-aware and unique.
	AllowOriginalNameShadowBuiltin bool
}

type RegistrationMeta

type RegistrationMeta struct {
	ToolKey          string
	StableToolKey    string
	OriginalToolName string
	Source           RegistrationSource
	ExtensionID      string
	ConflictPolicy   string
}

type RegistrationSource

type RegistrationSource string
const (
	RegistrationSourceBuiltin   RegistrationSource = "builtin"
	RegistrationSourceExtension RegistrationSource = "extension"
)

type Registry

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

func DefaultRegistry

func DefaultRegistry(agentInfos ...[]AgentInfo) *Registry

func (*Registry) Add

func (r *Registry) Add(tool Tool)

Add keeps backward compatibility with tests and call sites that used the old API.

func (*Registry) Count added in v1.0.1

func (r *Registry) Count() int

func (*Registry) Definitions

func (r *Registry) Definitions() []llm.ToolDefinition

func (*Registry) DefinitionsForMode

func (r *Registry) DefinitionsForMode(mode planpkg.AgentMode) []llm.ToolDefinition

func (*Registry) DefinitionsForModeWithFilters

func (r *Registry) DefinitionsForModeWithFilters(mode planpkg.AgentMode, allowlist, denylist []string) []llm.ToolDefinition

func (*Registry) FindByExtensionID

func (r *Registry) FindByExtensionID(extensionID string) []RegistrationMeta

func (*Registry) FindByOriginalName

func (r *Registry) FindByOriginalName(name string) []RegistrationMeta

func (*Registry) Get

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

func (*Registry) List

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

func (*Registry) Register

func (r *Registry) Register(tool Tool, opts RegisterOptions) error

func (*Registry) ResolveForMode

func (r *Registry) ResolveForMode(mode planpkg.AgentMode, name string) (ResolvedTool, error)

func (*Registry) ResolveForModeWithFilters

func (r *Registry) ResolveForModeWithFilters(mode planpkg.AgentMode, allowlist, denylist []string) []ResolvedTool

func (*Registry) Spec

func (r *Registry) Spec(name string) (ToolSpec, bool)

func (*Registry) Unregister

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

type RegistryError

type RegistryError struct {
	Code             RegistryErrorCode
	Message          string
	ToolKey          string
	OriginalToolName string
	Source           RegistrationSource
	ExtensionID      string
	ConflictWith     RegistrationMeta
	Cause            error
}

func (*RegistryError) Error

func (e *RegistryError) Error() string

func (*RegistryError) Unwrap

func (e *RegistryError) Unwrap() error

type RegistryErrorCode

type RegistryErrorCode string
const (
	RegistryErrorDuplicateName  RegistryErrorCode = "duplicate_name"
	RegistryErrorInvalidSource  RegistryErrorCode = "invalid_source"
	RegistryErrorInvalidSchema  RegistryErrorCode = "invalid_schema"
	RegistryErrorInvalidTool    RegistryErrorCode = "invalid_tool"
	RegistryErrorInvalidToolKey RegistryErrorCode = "invalid_tool_key"
	RegistryErrorNotFound       RegistryErrorCode = "not_found"
)

type ReplaceInFileTool

type ReplaceInFileTool struct{}

func (ReplaceInFileTool) Definition

func (ReplaceInFileTool) Definition() llm.ToolDefinition

func (ReplaceInFileTool) Run

type ResolvedTool

type ResolvedTool struct {
	Definition llm.ToolDefinition
	Spec       ToolSpec
	Tool       Tool
}

type RunShellTool

type RunShellTool struct{}

func (RunShellTool) Definition

func (RunShellTool) Definition() llm.ToolDefinition

func (RunShellTool) Run

type RunTestsTool added in v1.0.0

type RunTestsTool struct{}

func (RunTestsTool) Definition added in v1.0.0

func (RunTestsTool) Definition() llm.ToolDefinition

func (RunTestsTool) Run added in v1.0.0

func (RunTestsTool) Spec added in v1.0.0

func (RunTestsTool) Spec() ToolSpec

type SafetyClass

type SafetyClass string
const (
	SafetyClassSafe        SafetyClass = "safe"
	SafetyClassModerate    SafetyClass = "moderate"
	SafetyClassSensitive   SafetyClass = "sensitive"
	SafetyClassDestructive SafetyClass = "destructive"
)

type SearchTextTool

type SearchTextTool struct{}

func (SearchTextTool) Definition

func (SearchTextTool) Definition() llm.ToolDefinition

func (SearchTextTool) Run

type SubAgentToolCallRecord added in v0.1.8

type SubAgentToolCallRecord struct {
	ToolName    string   `json:"ToolName"`
	ToolCallID  string   `json:"ToolCallID"`
	CompactBody string   `json:"CompactBody"`
	Status      string   `json:"Status"`
	DetailLines []string `json:"DetailLines,omitempty"`
}

SubAgentToolCallRecord is a JSON-serializable record of a tool call made by a subagent. JSON tags match tui.SubAgentToolCall for direct unmarshal.

type SystemSandboxBackendCapabilities

type SystemSandboxBackendCapabilities struct {
	Name                   string
	Known                  bool
	ShellNetworkIsolation  bool
	WorkerNetworkIsolation bool
}

func SystemSandboxBackendCapabilitiesForName

func SystemSandboxBackendCapabilitiesForName(name string) SystemSandboxBackendCapabilities

type SystemSandboxRuntimeStatus

type SystemSandboxRuntimeStatus struct {
	SandboxEnabled         bool
	RequestedMode          string
	Mode                   string
	GOOS                   string
	BackendEnabled         bool
	BackendName            string
	RequiredCapable        bool
	CapabilityLevel        string
	ShellNetworkIsolation  bool
	WorkerNetworkIsolation bool
	Fallback               bool
	Message                string
}

SystemSandboxRuntimeStatus describes system sandbox runtime state after configuration and platform/backend probing are applied.

func ResolveSystemSandboxRuntimeStatus

func ResolveSystemSandboxRuntimeStatus(sandboxEnabled bool, mode string) (SystemSandboxRuntimeStatus, error)

ResolveSystemSandboxRuntimeStatus reports the effective runtime status of system sandbox mode under the current process OS and backend availability.

type TaskOutputTool

type TaskOutputTool struct{}

func (TaskOutputTool) Definition

func (TaskOutputTool) Definition() llm.ToolDefinition

func (TaskOutputTool) Run

func (TaskOutputTool) Spec

func (TaskOutputTool) Spec() ToolSpec

type TaskStopTool

type TaskStopTool struct{}

func (TaskStopTool) Definition

func (TaskStopTool) Definition() llm.ToolDefinition

func (TaskStopTool) Run

func (TaskStopTool) Spec

func (TaskStopTool) Spec() ToolSpec

type Tool

type Tool interface {
	Definition() llm.ToolDefinition
	Run(context.Context, json.RawMessage, *ExecutionContext) (string, error)
}

type ToolErrorCode

type ToolErrorCode string
const (
	ToolErrorInvalidArgs      ToolErrorCode = "invalid_args"
	ToolErrorPermissionDenied ToolErrorCode = "permission_denied"
	ToolErrorTimeout          ToolErrorCode = "timeout"
	ToolErrorToolFailed       ToolErrorCode = "tool_failed"
	ToolErrorInternal         ToolErrorCode = "internal_error"
)

type ToolExecError

type ToolExecError struct {
	Code      ToolErrorCode
	Message   string
	Retryable bool
	Cause     error
}

func AsToolExecError

func AsToolExecError(err error) (*ToolExecError, bool)

func NewToolExecError

func NewToolExecError(code ToolErrorCode, message string, retryable bool, cause error) *ToolExecError

func (*ToolExecError) Error

func (e *ToolExecError) Error() string

func (*ToolExecError) Unwrap

func (e *ToolExecError) Unwrap() error

type ToolSpec

type ToolSpec struct {
	Name            string
	ReadOnly        bool
	ConcurrencySafe bool
	Destructive     bool
	SafetyClass     SafetyClass
	StrictArgs      bool
	SearchHint      string
	AllowedModes    []planpkg.AgentMode
	DefaultTimeoutS int
	MaxTimeoutS     int
	MaxResultChars  int
}

func DefaultToolSpec

func DefaultToolSpec(def llm.ToolDefinition) ToolSpec

func MergeToolSpec

func MergeToolSpec(base, override ToolSpec) ToolSpec

func NormalizeToolSpec

func NormalizeToolSpec(spec ToolSpec) ToolSpec

type ToolSpecProvider

type ToolSpecProvider interface {
	Spec() ToolSpec
}

type TranscriptMessage added in v0.1.8

type TranscriptMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

TranscriptMessage represents a single message in a subagent's transcript.

type UpdatePlanTool

type UpdatePlanTool struct{}

func (UpdatePlanTool) Definition

func (UpdatePlanTool) Definition() llm.ToolDefinition

func (UpdatePlanTool) Run

type WebFetchTool

type WebFetchTool struct {
	HTTPClient *http.Client
}

func NewWebFetchTool

func NewWebFetchTool() WebFetchTool

func (WebFetchTool) Definition

func (WebFetchTool) Definition() llm.ToolDefinition

func (WebFetchTool) Run

type WebSearchTool

type WebSearchTool struct {
	BaseURL    string
	HTTPClient *http.Client
}

func NewWebSearchTool

func NewWebSearchTool() WebSearchTool

func (WebSearchTool) Definition

func (WebSearchTool) Definition() llm.ToolDefinition

func (WebSearchTool) Run

type WorktreeInfo added in v0.1.8

type WorktreeInfo struct {
	Path   string `json:"path,omitempty"`
	Branch string `json:"branch,omitempty"`
	State  string `json:"state,omitempty"` // "changed" | "unknown"
}

WorktreeInfo carries worktree isolation metadata in a subagent result.

type WriteFileTool

type WriteFileTool struct{}

func (WriteFileTool) Definition

func (WriteFileTool) Definition() llm.ToolDefinition

func (WriteFileTool) Run

Jump to

Keyboard shortcuts

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