tool

package
v0.0.0-...-820128f Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 46 Imported by: 0

Documentation

Overview

Package tool provides librecode-style built-in coding tools for local agent turns.

Index

Constants

View Source
const (
	// DefaultMaxLines is the default line limit for tool outputs.
	DefaultMaxLines = 2000
	// DefaultMaxBytes is the default byte limit for tool outputs.
	DefaultMaxBytes = 50 * units.KiB
	// GrepMaxLineLength is the maximum displayed length for one grep match line.
	GrepMaxLineLength = 500
)
View Source
const (
	// ContentTypeText is a plain text tool result block.
	ContentTypeText = "text"
	// ContentTypeImage is an inline base64 image result block.
	ContentTypeImage = "image"
)

Variables

View Source
var ErrDuplicateTool = errors.New("tool: duplicate tool")

ErrDuplicateTool is returned when a registry already has an executor for a tool name.

View Source
var ErrUnknownTool = errors.New("tool: unknown tool")

ErrUnknownTool is returned when a registry cannot resolve a tool name.

Functions

func ExpandPath

func ExpandPath(filePath string) string

ExpandPath normalizes model-supplied path shorthands.

func FormatSize

func FormatSize(byteCount int) string

FormatSize formats bytes for user-facing truncation notices.

func ResolveReadPath

func ResolveReadPath(filePath, cwd string) (string, error)

ResolveReadPath resolves a read path and tries common macOS filename variants.

func ResolveToCWD

func ResolveToCWD(filePath, cwd string) (string, error)

ResolveToCWD resolves relative paths against cwd after path shorthand expansion.

func TruncateLine

func TruncateLine(line string, maxCharacters int) (text string, wasTruncated bool)

TruncateLine limits one display line to maxCharacters runes.

Types

type ASTInput

type ASTInput struct {
	Line         *int   `json:"line,omitempty"`
	Depth        *int   `json:"depth,omitempty"`
	Path         string `json:"path"`
	Mode         string `json:"mode,omitempty" jsonschema:"enum=outline,enum=symbols,enum=query,enum=node,enum=tree"`
	Query        string `json:"query,omitempty"`
	AllowIgnored bool   `json:"allow_ignored,omitempty"`
}

ASTInput contains arguments for the ast tool.

type ASTTool

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

ASTTool inspects a source file's syntax tree via a pure-Go tree-sitter.

func NewASTTool

func NewASTTool(cwd string) *ASTTool

NewASTTool creates the ast tool for cwd.

func (*ASTTool) Definition

func (astTool *ASTTool) Definition() Definition

Definition returns ast tool metadata.

func (*ASTTool) Execute

func (astTool *ASTTool) Execute(ctx context.Context, input Arguments) (Result, error)

Execute runs the ast tool.

func (*ASTTool) Inspect

func (astTool *ASTTool) Inspect(ctx context.Context, input ASTInput) (Result, error)

Inspect parses one source file and returns the requested structural view.

type Arguments

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

Arguments is an immutable raw JSON object for tool input arguments.

func ArgumentsFromRaw

func ArgumentsFromRaw(raw []byte) (Arguments, error)

ArgumentsFromRaw validates and stores raw JSON object arguments.

func EmptyArguments

func EmptyArguments() Arguments

EmptyArguments returns an empty JSON object argument payload.

func (Arguments) Decode

func (arguments Arguments) Decode(target any) error

Decode unmarshals arguments into a concrete input struct.

func (Arguments) Fields

func (arguments Arguments) Fields() (map[string]json.RawMessage, error)

Fields decodes arguments as raw JSON object fields.

func (Arguments) HasField

func (arguments Arguments) HasField(name string) bool

HasField reports whether a top-level field is present.

func (Arguments) IsEmpty

func (arguments Arguments) IsEmpty() bool

IsEmpty reports whether arguments contain no fields.

func (Arguments) IsZero

func (arguments Arguments) IsZero() bool

IsZero reports whether arguments should be omitted from JSON payloads.

func (Arguments) MarshalJSON

func (arguments Arguments) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Arguments) RawMessage

func (arguments Arguments) RawMessage() json.RawMessage

RawMessage returns a defensive copy of the raw JSON object.

func (Arguments) String

func (arguments Arguments) String() string

String returns the raw JSON object string.

type BashInput

type BashInput struct {
	Timeout *float64 `json:"timeout,omitempty"`
	Command string   `json:"command"`
}

BashInput contains arguments for the bash tool.

type BashTool

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

BashTool executes shell commands in the configured working directory.

func NewBashTool

func NewBashTool(cwd string) *BashTool

NewBashTool creates the bash tool for cwd.

func (*BashTool) Bash

func (bashTool *BashTool) Bash(ctx context.Context, input BashInput) (Result, error)

Bash executes a command and returns combined stdout and stderr.

func (*BashTool) Definition

func (bashTool *BashTool) Definition() Definition

Definition returns bash tool metadata.

func (*BashTool) Execute

func (bashTool *BashTool) Execute(ctx context.Context, input Arguments) (Result, error)

Execute runs the bash tool.

type ContentBlock

type ContentBlock struct {
	Type     string `json:"type"`
	Text     string `json:"text,omitempty"`
	Data     string `json:"data,omitempty"`
	MIMEType string `json:"mime_type,omitempty"`
}

ContentBlock is one model-facing piece of tool output.

type Coordinator

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

Coordinator owns process-wide queues for conflicting workspace mutations. It coordinates one librecode process; SQLite task leases remain independent.

func NewCoordinator

func NewCoordinator() *Coordinator

NewCoordinator creates a process-local mutation coordinator.

type Definition

type Definition struct {
	Schema           Schema   `json:"schema"`
	Name             Name     `json:"name"`
	Label            string   `json:"label"`
	Description      string   `json:"description"`
	PromptSnippet    string   `json:"prompt_snippet"`
	PromptGuidelines []string `json:"prompt_guidelines"`
	ReadOnly         bool     `json:"read_only"`
}

Definition describes a built-in coding tool.

func AllDefinitions

func AllDefinitions() []Definition

AllDefinitions returns the definitions for all built-in tools.

type EditDetails

type EditDetails struct {
	Diff             string `json:"diff"`
	FirstChangedLine int    `json:"first_changed_line,omitempty"`
	Truncated        bool   `json:"truncated,omitempty"`
}

EditDetails describes the applied edit diff.

type EditInput

type EditInput struct {
	Path  string        `json:"path"`
	Edits []Replacement `json:"edits"`
}

EditInput contains arguments for the edit tool.

type EditTool

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

EditTool applies exact text replacements to files.

func NewEditTool

func NewEditTool(cwd string) *EditTool

NewEditTool creates the edit tool for cwd.

func (*EditTool) Definition

func (editTool *EditTool) Definition() Definition

Definition returns edit tool metadata.

func (*EditTool) Edit

func (editTool *EditTool) Edit(ctx context.Context, input EditInput) (Result, error)

Edit applies one or more replacements to one file.

func (*EditTool) Execute

func (editTool *EditTool) Execute(ctx context.Context, input Arguments) (Result, error)

Execute runs the edit tool.

type Executor

type Executor interface {
	Definition() Definition
	Execute(ctx context.Context, input Arguments) (Result, error)
}

Executor runs a built-in tool with raw JSON object input.

type FetchInput

type FetchInput struct {
	Timeout *int   `json:"timeout,omitempty"`
	Offset  *int   `json:"offset,omitempty"`
	Limit   *int   `json:"limit,omitempty"`
	URL     string `json:"url"`
	Format  string `json:"format,omitempty" jsonschema:"enum=markdown,enum=text,enum=html"`
}

FetchInput contains arguments for the fetch tool.

type FetchTool

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

FetchTool fetches explicit HTTP(S) URLs.

func NewFetchTool

func NewFetchTool() *FetchTool

NewFetchTool creates the fetch tool.

func (*FetchTool) Definition

func (fetchTool *FetchTool) Definition() Definition

Definition returns fetch tool metadata.

func (*FetchTool) Execute

func (fetchTool *FetchTool) Execute(ctx context.Context, input Arguments) (Result, error)

Execute runs the fetch tool.

func (*FetchTool) Fetch

func (fetchTool *FetchTool) Fetch(ctx context.Context, input FetchInput) (Result, error)

Fetch fetches one explicit HTTP(S) URL.

type FindInput

type FindInput struct {
	Limit   *int   `json:"limit,omitempty"`
	Pattern string `json:"pattern"`
	Path    string `json:"path,omitempty"`
}

FindInput contains arguments for the find tool.

type FindTool

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

FindTool searches file paths by glob pattern.

func NewFindTool

func NewFindTool(cwd string) *FindTool

NewFindTool creates the find tool for cwd.

func (*FindTool) Definition

func (findTool *FindTool) Definition() Definition

Definition returns find tool metadata.

func (*FindTool) Execute

func (findTool *FindTool) Execute(ctx context.Context, input Arguments) (Result, error)

Execute runs the find tool.

func (*FindTool) Find

func (findTool *FindTool) Find(ctx context.Context, input FindInput) (Result, error)

Find searches for file paths that match the requested glob pattern.

type GrepInput

type GrepInput struct {
	Context    *int   `json:"context,omitempty"`
	Limit      *int   `json:"limit,omitempty"`
	Pattern    string `json:"pattern"`
	Path       string `json:"path,omitempty"`
	Glob       string `json:"glob,omitempty"`
	IgnoreCase bool   `json:"ignore_case,omitempty"`
	Literal    bool   `json:"literal,omitempty"`
}

GrepInput contains arguments for the grep tool.

type GrepTool

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

GrepTool searches text files for patterns.

func NewGrepTool

func NewGrepTool(cwd string) *GrepTool

NewGrepTool creates the grep tool for cwd.

func (*GrepTool) Definition

func (grepTool *GrepTool) Definition() Definition

Definition returns grep tool metadata.

func (*GrepTool) Execute

func (grepTool *GrepTool) Execute(ctx context.Context, input Arguments) (Result, error)

Execute runs the grep tool.

func (*GrepTool) Grep

func (grepTool *GrepTool) Grep(ctx context.Context, input GrepInput) (Result, error)

Grep searches text files for matching lines.

type LSInput

type LSInput struct {
	Limit *int   `json:"limit,omitempty"`
	Path  string `json:"path,omitempty"`
}

LSInput contains arguments for the ls tool.

type LSTool

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

LSTool lists directory entries.

func NewLSTool

func NewLSTool(cwd string) *LSTool

NewLSTool creates the ls tool for cwd.

func (*LSTool) Definition

func (lsTool *LSTool) Definition() Definition

Definition returns ls tool metadata.

func (*LSTool) Execute

func (lsTool *LSTool) Execute(ctx context.Context, input Arguments) (Result, error)

Execute runs the ls tool.

func (*LSTool) LS

func (lsTool *LSTool) LS(ctx context.Context, input LSInput) (Result, error)

LS lists a directory alphabetically and marks directories with a slash.

type Name

type Name string

Name identifies a built-in coding tool.

const (
	// NameRead reads a file from disk.
	NameRead Name = "read"
	// NameBash executes a shell command.
	NameBash Name = "bash"
	// NameEdit applies exact text replacements to one file.
	NameEdit Name = "edit"
	// NameWrite writes a complete file.
	NameWrite Name = "write"
	// NameGrep searches file contents.
	NameGrep Name = "grep"
	// NameFind finds file paths by glob.
	NameFind Name = "find"
	// NameLS lists directory entries.
	NameLS Name = "ls"
	// NameAST inspects a file's syntax tree structure.
	NameAST Name = "ast"
	// NameFetch fetches explicit HTTP(S) URLs.
	NameFetch Name = "fetch"
)

type PreparedCall

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

PreparedCall is a validated tool invocation ready for execution. A call must not be used by multiple goroutines concurrently. Batch callers may Admit in source order, Execute on a worker, then Release after execution completes.

func (*PreparedCall) Admit

func (call *PreparedCall) Admit()

Admit reserves any source-ordered resources needed by the call. Callers preparing a batch must admit calls in source order before executing them concurrently.

func (*PreparedCall) Execute

func (call *PreparedCall) Execute(ctx context.Context) (Result, error)

Execute runs the prepared call.

func (*PreparedCall) Release

func (call *PreparedCall) Release()

Release abandons resources reserved by Admit. It is safe to call after Execute.

func (PreparedCall) Sequential

func (call PreparedCall) Sequential() bool

Sequential reports whether this call requires the whole batch to run in source order.

func (*PreparedCall) TryAdmit

func (call *PreparedCall) TryAdmit() bool

TryAdmit reserves resources only when they are immediately available. A false result leaves the call prepared and may be retried later.

type ReadInput

type ReadInput struct {
	Offset       *int   `json:"offset,omitempty"`
	Limit        *int   `json:"limit,omitempty"`
	Path         string `json:"path"`
	AllowIgnored bool   `json:"allow_ignored,omitempty"`
}

ReadInput contains arguments for the read tool.

type ReadTool

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

ReadTool reads text and image files from disk.

func NewReadTool

func NewReadTool(cwd string) *ReadTool

NewReadTool creates the read tool for cwd.

func (*ReadTool) Definition

func (readTool *ReadTool) Definition() Definition

Definition returns read tool metadata.

func (*ReadTool) Execute

func (readTool *ReadTool) Execute(ctx context.Context, input Arguments) (Result, error)

Execute runs the read tool.

func (*ReadTool) Read

func (readTool *ReadTool) Read(ctx context.Context, input ReadInput) (Result, error)

Read reads one text or supported image file.

type Registry

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

Registry owns built-in tool executors for a working directory.

func NewRegistry

func NewRegistry(cwd string) *Registry

NewRegistry creates a registry with every built-in tool enabled.

func NewRegistryWithCoordinator

func NewRegistryWithCoordinator(cwd string, names []Name, coordinator *Coordinator) (*Registry, error)

NewRegistryWithCoordinator creates a registry sharing process-wide mutation coordination.

func NewRegistryWithTools

func NewRegistryWithTools(cwd string, names []Name) (*Registry, error)

NewRegistryWithTools creates a registry containing only the named built-in tools.

func (*Registry) CWD

func (registry *Registry) CWD() string

CWD returns the registry working directory.

func (*Registry) Definitions

func (registry *Registry) Definitions() []Definition

Definitions returns sorted tool definitions.

func (*Registry) DenyMutations

func (registry *Registry) DenyMutations()

DenyMutations makes the registry reject tools not marked read-only. It is intended for non-interactive background executions that cannot ask for approval.

func (*Registry) Execute

func (registry *Registry) Execute(ctx context.Context, name string, input Arguments) (Result, error)

Execute runs a named tool with raw JSON object arguments.

func (*Registry) ExecuteJSON

func (registry *Registry) ExecuteJSON(ctx context.Context, name string, payload []byte) (Result, error)

ExecuteJSON runs a named tool with raw JSON object arguments.

func (*Registry) Has

func (registry *Registry) Has(name Name) bool

Has reports whether a tool is registered under name.

func (*Registry) Prepare

func (registry *Registry) Prepare(name string, input Arguments) (PreparedCall, error)

Prepare resolves and validates a named tool invocation without executing it.

func (*Registry) Register

func (registry *Registry) Register(executor Executor) error

Register adds a tool executor to the registry.

func (*Registry) Wrap

func (registry *Registry) Wrap(name Name, decorate func(Executor) Executor) error

Wrap replaces an executor with a decorator that preserves its definition name.

type Replacement

type Replacement struct {
	OldText string `json:"old_text"`
	NewText string `json:"new_text"`
}

Replacement is one exact text replacement for the edit tool.

type Result

type Result struct {
	Details map[string]any `json:"details"`
	Content []ContentBlock `json:"content"`
}

Result is returned by every built-in tool.

func TextResult

func TextResult(text string, details map[string]any) Result

TextResult creates a text-only tool result.

func (Result) Text

func (result Result) Text() string

Text joins all text blocks in a tool result.

type Schema

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

Schema is an immutable JSON Schema document.

func EmptySchema

func EmptySchema() Schema

EmptySchema returns the zero schema, meaning no explicit schema was provided.

func SchemaFromRaw

func SchemaFromRaw(raw []byte) (Schema, error)

SchemaFromRaw validates and stores a raw JSON Schema document.

func (Schema) IsEmpty

func (schema Schema) IsEmpty() bool

IsEmpty reports whether the schema is unset.

func (Schema) MarshalJSON

func (schema Schema) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Schema) RawMessage

func (schema Schema) RawMessage() json.RawMessage

RawMessage returns a defensive copy of the raw JSON schema.

type TruncatedBy

type TruncatedBy string

TruncatedBy identifies the limit that caused truncation.

const (
	// TruncatedByNone means content was not truncated.
	TruncatedByNone TruncatedBy = ""
	// TruncatedByLines means the line limit was reached first.
	TruncatedByLines TruncatedBy = "lines"
	// TruncatedByBytes means the byte limit was reached first.
	TruncatedByBytes TruncatedBy = "bytes"
)

type TruncationOptions

type TruncationOptions struct {
	MaxLines int `json:"max_lines"`
	MaxBytes int `json:"max_bytes"`
}

TruncationOptions controls head or tail truncation.

type TruncationResult

type TruncationResult struct {
	TruncatedBy           TruncatedBy `json:"truncated_by"`
	Content               string      `json:"content"`
	TotalLines            int         `json:"total_lines"`
	TotalBytes            int         `json:"total_bytes"`
	OutputLines           int         `json:"output_lines"`
	OutputBytes           int         `json:"output_bytes"`
	MaxLines              int         `json:"max_lines"`
	MaxBytes              int         `json:"max_bytes"`
	Truncated             bool        `json:"truncated"`
	LastLinePartial       bool        `json:"last_line_partial"`
	FirstLineExceedsLimit bool        `json:"first_line_exceeds_limit"`
}

TruncationResult describes how content was truncated.

func TruncateHead

func TruncateHead(content string, options TruncationOptions) TruncationResult

TruncateHead keeps the first complete lines that fit within both limits.

func TruncateTail

func TruncateTail(content string, options TruncationOptions) TruncationResult

TruncateTail keeps the last complete lines that fit within both limits.

type WriteInput

type WriteInput struct {
	Content *string `json:"content"`
	Path    string  `json:"path"`
}

WriteInput contains arguments for the write tool.

type WriteTool

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

WriteTool creates or overwrites complete files.

func NewWriteTool

func NewWriteTool(cwd string) *WriteTool

NewWriteTool creates the write tool for cwd.

func (*WriteTool) Definition

func (writeTool *WriteTool) Definition() Definition

Definition returns write tool metadata.

func (*WriteTool) Execute

func (writeTool *WriteTool) Execute(ctx context.Context, input Arguments) (Result, error)

Execute runs the write tool.

func (*WriteTool) Write

func (writeTool *WriteTool) Write(ctx context.Context, input WriteInput) (Result, error)

Write creates or overwrites one file.

Jump to

Keyboard shortcuts

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