tool

package
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2025 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package tool provides tool infrastructure for the gains library.

This package includes:

  • Registry and Handler types for tool management
  • Function binding with automatic schema generation from struct tags
  • Built-in tools for common operations (file, HTTP, search)
  • Client tools wrapping gains client capabilities (image, embedding, chat)

Basic Usage

Define tool arguments as a struct with tags, then use Bind or BindTo:

type WeatherArgs struct {
    Location string `json:"location" desc:"City name" required:"true"`
    Unit     string `json:"unit" desc:"Temperature unit" enum:"celsius,fahrenheit"`
}

// Create tool and handler
t, h := tool.MustBind("get_weather", "Get current weather",
    func(ctx context.Context, args WeatherArgs) (string, error) {
        return fmt.Sprintf(`{"temp": 72, "location": %q}`, args.Location), nil
    })

// Register to a registry
registry := tool.NewRegistry()
registry.MustRegister(t, h)

Supported Struct Tags

The following tags are supported for schema generation:

json:"name"      - Property name (required for inclusion)
desc:"text"      - Description for the model
required:"true"  - Mark field as required
enum:"a,b,c"     - Allowed values (comma-separated)
min:"0"          - Minimum value (numbers)
max:"100"        - Maximum value (numbers)
minLength:"1"    - Minimum string length
maxLength:"100"  - Maximum string length
pattern:"regex"  - String pattern
default:"value"  - Default value
minItems:"1"     - Minimum array items
maxItems:"10"    - Maximum array items

Built-in Tools

The package provides several built-in tools:

File Tools:

  • read_file: Read file contents
  • write_file: Write content to a file
  • list_directory: List directory contents

HTTP Tool:

  • http_request: Make HTTP requests

Search Tool:

  • search_files: Search for patterns in files

Client Tools (require gains client):

  • generate_image: Generate images from text
  • embed_text: Generate text embeddings
  • ask_assistant: Make LLM calls (sub-agent pattern)

Using Built-in Tools

registry := tool.NewRegistry()

// Register file tools with restrictions
tool.RegisterAll(registry, tool.FileTools(
    tool.WithBasePath("/workspace"),
    tool.WithAllowedExtensions(".go", ".md"),
))

// Register all standard tools
tool.RegisterAll(registry, tool.AllTools(client,
    tool.WithFileOptions(tool.WithBasePath("/workspace")),
    tool.WithHTTPOptions(tool.WithAllowedHosts("api.example.com")),
))

Tool Sets

Pre-configured tool collections are available:

  • FileTools(): read, write, list directory
  • WebTools(): HTTP requests
  • SearchTools(): file search
  • ClientTools(): image, embedding, chat (requires client)
  • StandardTools(): file, HTTP, search (no client required)
  • AllTools(): all tools including client tools

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BindTo

func BindTo[T any](r *Registry, name, description string, fn TypedHandler[T]) error

BindTo creates a tool from a typed function and registers it directly to a Registry. This is a convenience function combining Bind and Registry.Register.

Example:

type SearchArgs struct {
    Query string `json:"query" desc:"Search query" required:"true"`
    Limit int    `json:"limit" desc:"Max results" min:"1" max:"100"`
}

err := tool.BindTo(registry, "search", "Search the web",
    func(ctx context.Context, args SearchArgs) (string, error) {
        return doSearch(args.Query, args.Limit), nil
    })

func GenerateUserInterfaceTool added in v0.2.9

func GenerateUserInterfaceTool() ai.Tool

GenerateUserInterfaceTool creates a client-side tool for generating UI. This tool is handled by the frontend - it renders the specified component and returns the user's interaction as the tool result.

Example usage in agent:

registry.RegisterClientTool(tool.GenerateUserInterfaceTool())

The agent can then call generateUserInterface to show dynamic UI:

{
    "type": "form",
    "title": "User Details",
    "fields": [
        {"name": "email", "type": "email", "label": "Email", "required": true}
    ],
    "actions": [
        {"id": "submit", "label": "Submit", "primary": true}
    ]
}

func MustBindTo

func MustBindTo[T any](r *Registry, name, description string, fn TypedHandler[T])

MustBindTo is like BindTo but panics on error.

func MustRegisterAll

func MustRegisterAll(r *Registry, pairs []ToolPair)

MustRegisterAll is like RegisterAll but panics on error.

func MustRegisterFunc

func MustRegisterFunc[T any](r *Registry, name, description string, fn TypedHandler[T])

MustRegisterFunc is like RegisterFunc but panics on error.

func MustSchemaFor

func MustSchemaFor[T any]() json.RawMessage

MustSchemaFor is like SchemaFor but panics on error. This is a convenience re-export of gains.MustSchemaFor.

func RegisterAll

func RegisterAll(r *Registry, pairs []ToolPair) error

RegisterAll registers all tool pairs to a registry. Returns the first error encountered, or nil if all registrations succeed.

func RegisterFunc

func RegisterFunc[T any](r *Registry, name, description string, fn TypedHandler[T]) error

RegisterFunc registers a tool with a typed handler that automatically unmarshals the arguments JSON into the specified type T.

Example:

type SearchArgs struct {
    Query string `json:"query" desc:"Search query" required:"true"`
}

tool.RegisterFunc(registry, "search", "Search the web",
    func(ctx context.Context, args SearchArgs) (string, error) {
        return doSearch(args.Query), nil
    },
)

func SchemaFor

func SchemaFor[T any]() (json.RawMessage, error)

SchemaFor generates a JSON schema from a struct type T. This is a convenience re-export of gains.SchemaFor. See gains.SchemaFor for full documentation.

Types

type AllToolsOption

type AllToolsOption func(*allToolsConfig)

AllToolsOption configures the AllTools function.

func WithClientOptions

func WithClientOptions(opts ...ClientToolsOption) AllToolsOption

WithClientOptions sets options for client tools in AllTools.

func WithFileOptions

func WithFileOptions(opts ...FileToolOption) AllToolsOption

WithFileOptions sets options for file tools in AllTools.

func WithHTTPOptions

func WithHTTPOptions(opts ...HTTPToolOption) AllToolsOption

WithHTTPOptions sets options for HTTP tool in AllTools.

func WithSearchOptions

func WithSearchOptions(opts ...SearchToolOption) AllToolsOption

WithSearchOptions sets options for search tool in AllTools.

type ChatToolOption

type ChatToolOption func(*chatToolConfig)

ChatToolOption configures the chat tool.

func WithChatDefaults

func WithChatDefaults(opts ...ai.Option) ChatToolOption

WithChatDefaults sets default options for chat requests.

func WithChatName

func WithChatName(name string) ChatToolOption

WithChatName sets a custom name for the chat tool. Default is "ask_assistant".

func WithSystemPrompt

func WithSystemPrompt(prompt string) ChatToolOption

WithSystemPrompt sets a system prompt for the chat tool.

type ClientToolsOption

type ClientToolsOption func(*clientToolsConfig)

ClientToolsOption configures the ClientTools function.

func WithChatToolOptions

func WithChatToolOptions(opts ...ChatToolOption) ClientToolsOption

WithChatToolOptions sets options for the chat tool in ClientTools.

func WithEmbeddingToolOptions

func WithEmbeddingToolOptions(opts ...EmbeddingToolOption) ClientToolsOption

WithEmbeddingToolOptions sets options for the embedding tool in ClientTools.

func WithImageToolOptions

func WithImageToolOptions(opts ...ImageToolOption) ClientToolsOption

WithImageToolOptions sets options for the image tool in ClientTools.

type EmbeddingClient

type EmbeddingClient interface {
	Embed(ctx context.Context, texts []string, opts ...ai.EmbeddingOption) (*ai.EmbeddingResponse, error)
}

EmbeddingClient is the interface for embedding capabilities.

type EmbeddingToolOption

type EmbeddingToolOption func(*embeddingToolConfig)

EmbeddingToolOption configures the embedding tool.

func WithEmbeddingDefaults

func WithEmbeddingDefaults(opts ...ai.EmbeddingOption) EmbeddingToolOption

WithEmbeddingDefaults sets default options for embedding generation.

func WithEmbeddingName

func WithEmbeddingName(name string) EmbeddingToolOption

WithEmbeddingName sets a custom name for the embedding tool. Default is "embed_text".

type ErrClientTool

type ErrClientTool struct {
	Name string
}

ErrClientTool is returned when Execute is called on a client-side tool. Client tools should be executed by the frontend, not the backend.

func (*ErrClientTool) Error

func (e *ErrClientTool) Error() string

Error returns a formatted error message indicating this is a client tool.

type ErrToolAlreadyRegistered

type ErrToolAlreadyRegistered struct {
	Name string
}

ErrToolAlreadyRegistered is returned when registering a tool with a duplicate name.

func (*ErrToolAlreadyRegistered) Error

func (e *ErrToolAlreadyRegistered) Error() string

Error returns a formatted error message including the duplicate tool name.

type ErrToolExecution

type ErrToolExecution struct {
	Name string
	Err  error
}

ErrToolExecution wraps errors from tool handler execution.

func (*ErrToolExecution) Error

func (e *ErrToolExecution) Error() string

Error returns a formatted error message including the tool name and cause.

func (*ErrToolExecution) Unwrap

func (e *ErrToolExecution) Unwrap() error

Unwrap returns the underlying error for use with errors.Is and errors.As.

type ErrToolNotFound

type ErrToolNotFound struct {
	Name string
}

ErrToolNotFound is returned when a tool call references an unregistered tool.

func (*ErrToolNotFound) Error

func (e *ErrToolNotFound) Error() string

Error returns a formatted error message including the tool name.

type FileToolOption

type FileToolOption func(*fileToolConfig)

FileToolOption configures file tools.

func WithAllowedExtensions

func WithAllowedExtensions(exts ...string) FileToolOption

WithAllowedExtensions restricts file operations to specific file extensions.

func WithBasePath

func WithBasePath(path string) FileToolOption

WithBasePath restricts file operations to a specific directory. All paths will be resolved relative to this base path.

func WithMaxFileSize

func WithMaxFileSize(bytes int64) FileToolOption

WithMaxFileSize sets the maximum file size for read/write operations. Default is 10MB.

type HTTPToolOption

type HTTPToolOption func(*httpToolConfig)

HTTPToolOption configures the HTTP tool.

func WithAllowedHosts

func WithAllowedHosts(hosts ...string) HTTPToolOption

WithAllowedHosts restricts requests to specific hosts only.

func WithBlockedHosts

func WithBlockedHosts(hosts ...string) HTTPToolOption

WithBlockedHosts blocks requests to specific hosts.

func WithHTTPClient

func WithHTTPClient(c *http.Client) HTTPToolOption

WithHTTPClient sets a custom HTTP client.

func WithHTTPTimeout

func WithHTTPTimeout(d time.Duration) HTTPToolOption

WithHTTPTimeout sets the request timeout. Default is 30 seconds.

func WithMaxResponseSize

func WithMaxResponseSize(bytes int64) HTTPToolOption

WithMaxResponseSize sets the maximum response body size. Default is 1MB.

type Handler

type Handler func(ctx context.Context, call ai.ToolCall) (string, error)

Handler is a function that executes a tool call and returns a result. The context supports cancellation and timeout. The call contains the tool name, ID, and arguments as a JSON string. Returns the result content string, or an error if execution failed.

func Bind

func Bind[T any](name, description string, fn TypedHandler[T]) (ai.Tool, Handler, error)

Bind creates a Tool and Handler from a typed function. The JSON schema for tool parameters is automatically generated from struct tags on type T.

Example:

type TranslateArgs struct {
    Text string `json:"text" desc:"Text to translate" required:"true"`
    From string `json:"from" desc:"Source language" required:"true"`
    To   string `json:"to" desc:"Target language" required:"true"`
}

t, h := tool.Bind("translate", "Translate text between languages",
    func(ctx context.Context, args TranslateArgs) (string, error) {
        // implementation
        return translated, nil
    })

func MustBind

func MustBind[T any](name, description string, fn TypedHandler[T]) (ai.Tool, Handler)

MustBind is like Bind but panics on error. This is useful for initialization code where errors should be fatal.

func NewChatTool

func NewChatTool(c chat.Client, opts ...ChatToolOption) (ai.Tool, Handler)

NewChatTool creates a tool that makes LLM calls (sub-agent pattern). This allows an agent to delegate tasks to another LLM call.

func NewEditFileTool

func NewEditFileTool(opts ...FileToolOption) (ai.Tool, Handler)

NewEditFileTool creates a tool for editing file contents. Supports string replacement and line operations (insert, delete, replace).

func NewEmbeddingTool

func NewEmbeddingTool(c EmbeddingClient, opts ...EmbeddingToolOption) (ai.Tool, Handler)

NewEmbeddingTool creates a tool for generating text embeddings. The tool accepts an array of texts and returns their embedding vectors.

func NewHTTPTool

func NewHTTPTool(opts ...HTTPToolOption) (ai.Tool, Handler)

NewHTTPTool creates a tool for making HTTP requests.

func NewImageTool

func NewImageTool(c ImageClient, opts ...ImageToolOption) (ai.Tool, Handler)

NewImageTool creates a tool for generating images. The tool accepts a prompt and optional size, quality, and style parameters.

func NewListDirTool

func NewListDirTool(opts ...FileToolOption) (ai.Tool, Handler)

NewListDirTool creates a tool for listing directory contents.

func NewReadFileTool

func NewReadFileTool(opts ...FileToolOption) (ai.Tool, Handler)

NewReadFileTool creates a tool for reading file contents.

func NewSearchTool

func NewSearchTool(opts ...SearchToolOption) (ai.Tool, Handler)

NewSearchTool creates a tool for searching file contents with regex.

func NewWriteFileTool

func NewWriteFileTool(opts ...FileToolOption) (ai.Tool, Handler)

NewWriteFileTool creates a tool for writing file contents.

type ImageClient

type ImageClient interface {
	GenerateImage(ctx context.Context, prompt string, opts ...ai.ImageOption) (*ai.ImageResponse, error)
}

ImageClient is the interface for image generation capabilities.

type ImageToolOption

type ImageToolOption func(*imageToolConfig)

ImageToolOption configures the image generation tool.

func WithImageDefaults

func WithImageDefaults(opts ...ai.ImageOption) ImageToolOption

WithImageDefaults sets default options for image generation.

func WithImageName

func WithImageName(name string) ImageToolOption

WithImageName sets a custom name for the image tool. Default is "generate_image".

type ReadStateArgs added in v0.2.9

type ReadStateArgs struct {
	Field string `json:"field,omitempty" desc:"Optional field path to read (e.g. '/counter'). If empty, returns entire state."`
}

ReadStateArgs are the arguments for the read_state tool.

type Registration

type Registration struct {
	Tool    ai.Tool
	Handler Handler
}

Registration holds a tool and its handler for fluent registration.

func Func

func Func[T any](name, description string, fn TypedHandler[T]) Registration

Func creates a Registration with automatic schema generation from the typed handler. Panics if schema generation fails.

Example:

registry := tool.NewRegistry().Add(
    tool.Func("weather", "Get weather", func(ctx context.Context, args WeatherArgs) (string, error) {
        return getWeather(args.Location), nil
    }),
    tool.Func("search", "Search web", searchHandler),
)

func SharedStateTools added in v0.2.9

func SharedStateTools() []Registration

SharedStateTools returns tools for reading and updating shared UI state. These tools enable the LLM to interact with frontend state via AG-UI protocol.

Tools provided:

  • read_state: Read the current shared state
  • write_state: Replace the entire shared state
  • update_state: Update specific fields

The tools automatically emit STATE_SNAPSHOT/STATE_DELTA events to sync with the frontend. No manual event emission is needed.

Usage:

// In handler, set up shared state in context
sharedState := event.NewSharedState(prepared.State)
ctx = event.WithSharedState(ctx, sharedState)

// Register tools
registry.Add(tool.SharedStateTools()...)

func WithHandler

func WithHandler(name, description string, schema json.RawMessage, h Handler) Registration

WithHandler creates a Registration from a Handler and schema. Use this when you have a pre-built Handler implementation.

func WithTool

func WithTool(t ai.Tool, h Handler) Registration

WithTool creates a Registration from an existing Tool and Handler. Use this when you have pre-built tool definitions.

type Registry

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

Registry manages registered tools and their handlers. It is safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty tool registry.

func (*Registry) Add

func (r *Registry) Add(regs ...Registration) *Registry

Add registers one or more tools to the registry. Panics if any tool is already registered. Returns the registry for fluent chaining.

Example:

registry := tool.NewRegistry().Add(
    tool.Func("weather", "Get weather", weatherFn),
    tool.Func("search", "Search web", searchFn),
    tool.Func("calc", "Calculate", calcFn),
)

func (*Registry) ClientToolNames

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

ClientToolNames returns the names of all registered client tools.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, call ai.ToolCall) (ai.ToolResult, error)

Execute runs the handler for a tool call and returns a ToolResult. If the tool is not found, returns ErrToolNotFound. If the tool is a client-side tool, returns ErrClientTool. If the handler returns an error, the error is captured in ToolResult.IsError and the error message is returned as the content (allowing the model to recover).

func (*Registry) Get

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

Get retrieves a handler by tool name. Returns the handler and true if found, or nil and false if not found.

func (*Registry) GetTool

func (r *Registry) GetTool(name string) (ai.Tool, bool)

GetTool retrieves a tool definition by name. Returns the tool and true if found, or empty tool and false if not found.

func (*Registry) IsClientTool

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

IsClientTool returns true if the named tool is a client-side tool.

func (*Registry) Len

func (r *Registry) Len() int

Len returns the number of registered tools.

func (*Registry) MustRegister

func (r *Registry) MustRegister(tool ai.Tool, handler Handler)

MustRegister is like Register but panics on error.

func (*Registry) Names

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

Names returns the names of all registered tools.

func (*Registry) Register

func (r *Registry) Register(tool ai.Tool, handler Handler) error

Register adds a tool with its handler to the registry. Returns an error if a tool with the same name is already registered.

func (*Registry) RegisterClientTool

func (r *Registry) RegisterClientTool(tool ai.Tool) error

RegisterClientTool registers a tool definition without a handler. Client tools are executed by the frontend/client, not the backend. When the agent encounters a call to a client tool, it emits events but does not execute locally.

func (*Registry) RegisterClientTools

func (r *Registry) RegisterClientTools(tools []ai.Tool) error

RegisterClientTools registers multiple client tool definitions.

func (*Registry) Tools

func (r *Registry) Tools() []ai.Tool

Tools returns all registered tool definitions. This is used to pass the tools to the ChatProvider.

func (*Registry) Unregister

func (r *Registry) Unregister(name string)

Unregister removes a tool from the registry. It is a no-op if the tool is not registered.

type SearchToolOption

type SearchToolOption func(*searchToolConfig)

SearchToolOption configures the search tool.

func WithExcludePatterns

func WithExcludePatterns(patterns ...string) SearchToolOption

WithExcludePatterns sets glob patterns for files to exclude.

func WithIncludePatterns

func WithIncludePatterns(patterns ...string) SearchToolOption

WithIncludePatterns sets glob patterns for files to include.

func WithMaxResults

func WithMaxResults(n int) SearchToolOption

WithMaxResults limits the number of search results. Default is 100.

func WithSearchPath

func WithSearchPath(path string) SearchToolOption

WithSearchPath sets the base path for searches.

type ToolPair

type ToolPair struct {
	Tool    ai.Tool
	Handler Handler
}

ToolPair holds a tool definition and its handler for easy registration.

func AllTools

func AllTools(c *client.Client, opts ...AllToolsOption) []ToolPair

AllTools returns all standard tools: file, HTTP, search, and client tools. Pass nil for the client parameter to exclude client-specific tools.

func ClientTools

func ClientTools(c *client.Client, opts ...ClientToolsOption) []ToolPair

ClientTools returns tools for image, embedding, and chat capabilities. Only tools for supported features are returned.

func FileTools

func FileTools(opts ...FileToolOption) []ToolPair

FileTools returns read, write, edit, and list directory tools.

func SearchTools

func SearchTools(opts ...SearchToolOption) []ToolPair

SearchTools returns the search tool.

func StandardTools

func StandardTools(opts ...AllToolsOption) []ToolPair

StandardTools returns non-client tools: file, HTTP, and search tools. Use this when you don't need image, embedding, or chat tools.

func WebTools

func WebTools(opts ...HTTPToolOption) []ToolPair

WebTools returns the HTTP request tool.

type TypedHandler

type TypedHandler[T any] func(ctx context.Context, args T) (string, error)

TypedHandler is a function that executes a tool call with typed arguments. The args parameter is automatically unmarshaled from the tool call's JSON arguments.

type UIAction added in v0.2.9

type UIAction struct {
	ID      string `json:"id" desc:"Action identifier" required:"true"`
	Label   string `json:"label" desc:"Button label" required:"true"`
	Primary bool   `json:"primary,omitempty" desc:"Whether this is the primary action"`
	Danger  bool   `json:"danger,omitempty" desc:"Whether this is a destructive action"`
}

UIAction defines an action button.

type UIComponent added in v0.2.9

type UIComponent struct {
	// Type specifies the kind of component to render.
	Type UIComponentType `json:"type" desc:"Type of UI component" required:"true" enum:"form,confirmation,card,list,progress,custom"`

	// Title is the component's heading or title.
	Title string `json:"title,omitempty" desc:"Component title or heading"`

	// Description provides additional context.
	Description string `json:"description,omitempty" desc:"Additional description or context"`

	// Fields defines form fields (for form type).
	Fields []UIField `json:"fields,omitempty" desc:"Form fields for type=form"`

	// Items defines list items (for list type).
	Items []UIListItem `json:"items,omitempty" desc:"List items for type=list"`

	// Actions defines available actions/buttons.
	Actions []UIAction `json:"actions,omitempty" desc:"Action buttons"`

	// Progress is the progress value 0-100 (for progress type).
	Progress int `json:"progress,omitempty" desc:"Progress percentage 0-100 for type=progress"`

	// CustomType is the custom component identifier (for custom type).
	CustomType string `json:"customType,omitempty" desc:"Custom component type identifier"`

	// CustomData is arbitrary data for custom components.
	CustomData json.RawMessage `json:"customData,omitempty" desc:"Custom component data"`

	// Metadata is additional metadata for the component.
	Metadata map[string]any `json:"metadata,omitempty" desc:"Additional component metadata"`
}

UIComponent defines a UI component for the frontend to render. This is the schema for the generateUserInterface tool arguments.

type UIComponentType added in v0.2.9

type UIComponentType string

UIComponentType identifies the kind of UI component to generate.

const (
	// UIComponentForm renders a form with input fields.
	UIComponentForm UIComponentType = "form"

	// UIComponentConfirmation renders a confirmation dialog.
	UIComponentConfirmation UIComponentType = "confirmation"

	// UIComponentCard renders an information card.
	UIComponentCard UIComponentType = "card"

	// UIComponentList renders a selectable list.
	UIComponentList UIComponentType = "list"

	// UIComponentProgress renders a progress indicator.
	UIComponentProgress UIComponentType = "progress"

	// UIComponentCustom renders a custom component (frontend-specific).
	UIComponentCustom UIComponentType = "custom"
)

type UIField added in v0.2.9

type UIField struct {
	// Name is the field identifier (used in result).
	Name string `json:"name" desc:"Field identifier" required:"true"`

	// Type is the field type.
	Type UIFieldType `json:"type" desc:"Field type" required:"true" enum:"text,number,email,password,textarea,select,checkbox,radio,date,file"`

	// Label is the field's display label.
	Label string `json:"label,omitempty" desc:"Display label"`

	// Placeholder is the placeholder text.
	Placeholder string `json:"placeholder,omitempty" desc:"Placeholder text"`

	// Default is the default value.
	Default string `json:"default,omitempty" desc:"Default value"`

	// Required indicates if the field is required.
	Required bool `json:"required,omitempty" desc:"Whether field is required"`

	// Options are the choices for select/radio fields.
	Options []UIOption `json:"options,omitempty" desc:"Options for select/radio fields"`

	// Validation contains validation rules.
	Validation *UIValidation `json:"validation,omitempty" desc:"Validation rules"`
}

UIField defines a form field.

type UIFieldType added in v0.2.9

type UIFieldType string

UIFieldType identifies the kind of form field.

const (
	UIFieldText     UIFieldType = "text"
	UIFieldNumber   UIFieldType = "number"
	UIFieldEmail    UIFieldType = "email"
	UIFieldPassword UIFieldType = "password"
	UIFieldTextarea UIFieldType = "textarea"
	UIFieldSelect   UIFieldType = "select"
	UIFieldCheckbox UIFieldType = "checkbox"
	UIFieldRadio    UIFieldType = "radio"
	UIFieldDate     UIFieldType = "date"
	UIFieldFile     UIFieldType = "file"
)

type UIListItem added in v0.2.9

type UIListItem struct {
	ID          string `json:"id" desc:"Item identifier" required:"true"`
	Title       string `json:"title" desc:"Item title" required:"true"`
	Description string `json:"description,omitempty" desc:"Item description"`
	Icon        string `json:"icon,omitempty" desc:"Icon identifier"`
	Selectable  bool   `json:"selectable,omitempty" desc:"Whether item is selectable"`
}

UIListItem defines an item in a list component.

type UIOption added in v0.2.9

type UIOption struct {
	Value string `json:"value" desc:"Option value" required:"true"`
	Label string `json:"label" desc:"Display label" required:"true"`
}

UIOption defines an option for select/radio fields.

type UIResult added in v0.2.9

type UIResult struct {
	// Action is the action that was triggered (for button clicks).
	Action string `json:"action,omitempty"`

	// Values contains form field values.
	Values map[string]any `json:"values,omitempty"`

	// SelectedItems contains selected list item IDs.
	SelectedItems []string `json:"selectedItems,omitempty"`

	// Cancelled indicates if the user dismissed the UI.
	Cancelled bool `json:"cancelled,omitempty"`
}

UIResult is the result returned from a UI component interaction.

func ParseUIResult added in v0.2.9

func ParseUIResult(result string) (*UIResult, error)

ParseUIResult parses the tool result from a generateUserInterface call.

type UIValidation added in v0.2.9

type UIValidation struct {
	MinLength int    `json:"minLength,omitempty" desc:"Minimum text length"`
	MaxLength int    `json:"maxLength,omitempty" desc:"Maximum text length"`
	Min       int    `json:"min,omitempty" desc:"Minimum numeric value"`
	Max       int    `json:"max,omitempty" desc:"Maximum numeric value"`
	Pattern   string `json:"pattern,omitempty" desc:"Regex pattern for validation"`
	Message   string `json:"message,omitempty" desc:"Custom validation error message"`
}

UIValidation defines validation rules for a field.

type UpdateStateArgs added in v0.2.9

type UpdateStateArgs struct {
	Path  string `json:"path" desc:"JSON Pointer path to update (e.g. '/counter')" required:"true"`
	Value any    `json:"value" desc:"The new value to set" required:"true"`
}

UpdateStateArgs are the arguments for the update_state tool.

type WriteStateArgs added in v0.2.9

type WriteStateArgs struct {
	State map[string]any `json:"state" desc:"The new state to set" required:"true"`
}

WriteStateArgs are the arguments for the write_state tool.

Jump to

Keyboard shortcuts

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