tools

package
v4.0.19 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package tools defines local tool registration, permission metadata, and authority-gated execution.

Registry is safe for concurrent definition reads and tool execution. Registration validates tool names, effects, permission modes, and reserved control names. Strictly safe read-only tools may omit Permission.Mode and are exposed as allowed tools. Mutating, destructive, open-world, shell, and network tools must declare explicit permission behavior. Host authorization is supplied through runtime.EffectAuthorizationGate; this package does not expose a standalone approval callback. PermissionDeny tools remain callable only as explicit host-side disabled tools and are not exposed to providers. Ordinary calls returned in one model batch execute concurrently; the model expresses dependencies by emitting dependent calls in later turns.

Index

Constants

View Source
const (
	DefaultToolVisibleMaxBytes = 64 * 1024
	DefaultToolVisibleMaxLines = 0
	DefaultToolOutputStrategy  = OutputTail
	DefaultPreserveFull        = true
	DefaultArtifactKind        = "tool_output"
	DefaultArtifactMIME        = "text/plain; charset=utf-8"
)
View Source
const (
	ControlAskUser      = "ask_user"
	ControlTaskComplete = "task_complete"
)
View Source
const (
	AnnotationRepeatPolicy                   = "repeat_policy"
	AnnotationRepeatIdentityIgnoredArguments = "repeat_identity_ignored_arguments"
	RepeatPolicyPolling                      = "polling"
	ResultMetadataProgressToken              = "progress_token"
)
View Source
const ResultOutcomeDeclined = "declined"

Variables

View Source
var ErrDuplicate = errors.New("duplicate tool name")
View Source
var ErrEffectDispatcherRequired = errors.New("tool effect authority dispatcher is required")
View Source
var ErrInvalid = errors.New("invalid tool")
View Source
var ErrRejected = errors.New("tool call rejected")
View Source
var ErrSchema = errors.New("schema validation failed")

Functions

func ActivityDurationMS

func ActivityDurationMS(in *ActivityPresentation) int64

ActivityDurationMS returns a typed renderer duration when one exists.

func ActivityHasPending

func ActivityHasPending(in *ActivityPresentation) bool

ActivityHasPending reports whether presentation data still describes unsettled host-owned work.

func ActivityStatus

func ActivityStatus(in *ActivityPresentation) (string, bool)

ActivityStatus returns renderer-authored status without requiring callers to know which payload variant carries it.

func Array

func Array(items map[string]any, description string) map[string]any

func Boolean

func Boolean(description string) map[string]any

func Enum

func Enum(values ...string) map[string]any

func Integer

func Integer(description string) map[string]any

func InvalidArgumentsText

func InvalidArgumentsText(name string, err error) string

func IsReservedName

func IsReservedName(name string) bool

func NormalizeInputSchema

func NormalizeInputSchema(schema map[string]any) (map[string]any, error)

func Nullable

func Nullable(schema map[string]any) map[string]any

func Number

func Number(description string) map[string]any

func PendingToolResultMetadata

func PendingToolResultMetadata(p PendingToolResult) map[string]any

func PendingToolResultText

func PendingToolResultText(p PendingToolResult) string

func StrictObject

func StrictObject(properties map[string]any, required []string) map[string]any

func String

func String(description string) map[string]any

func Validate

func Validate(schema map[string]any, raw []byte) (map[string]any, error)

func ValidateStructured

func ValidateStructured(schema map[string]any, value any) error

Types

type ActivityChip

type ActivityChip struct {
	Kind  string `json:"kind"`
	Label string `json:"label"`
	Value string `json:"value,omitempty"`
	Tone  string `json:"tone,omitempty"`
}

type ActivityError

type ActivityError struct {
	Message string `json:"message"`
}

type ActivityPayload

type ActivityPayload interface {
	// contains filtered or unexported methods
}

ActivityPayload is the closed set of renderer-specific presentation data. Downstream packages can consume the variants but cannot add unvalidated ones.

type ActivityPresentation

type ActivityPresentation struct {
	Label       string              `json:"label,omitempty"`
	Description string              `json:"description,omitempty"`
	Renderer    ActivityRenderer    `json:"renderer,omitempty"`
	Chips       []ActivityChip      `json:"chips,omitempty"`
	TargetRefs  []ActivityTargetRef `json:"target_refs,omitempty"`
	Payload     ActivityPayload     `json:"payload,omitempty"`
}

ActivityPresentation is display data authored by the tool that owns the invocation. Its renderer is the discriminator for exactly one payload type.

func ClearPendingActivity

func ClearPendingActivity(in *ActivityPresentation) *ActivityPresentation

ClearPendingActivity removes transient pending presentation after a terminal fact.

func CloneActivityPresentation

func CloneActivityPresentation(in *ActivityPresentation) *ActivityPresentation

CloneActivityPresentation returns a detached copy of tool-authored display data so observers cannot mutate invocation state.

func FinalizeActivityPresentation

func FinalizeActivityPresentation(in *ActivityPresentation, status string) *ActivityPresentation

FinalizeActivityPresentation applies a terminal status and removes transient pending markers without exposing renderer payload mutation to callers.

func MergeActivityPresentations

func MergeActivityPresentations(left, right *ActivityPresentation) *ActivityPresentation

MergeActivityPresentations combines successive facts for one invocation. Renderer changes replace the payload; equal renderers merge typed fields.

func (ActivityPresentation) MarshalJSON

func (presentation ActivityPresentation) MarshalJSON() ([]byte, error)

func (*ActivityPresentation) UnmarshalJSON

func (presentation *ActivityPresentation) UnmarshalJSON(data []byte) error

func (ActivityPresentation) Validate

func (presentation ActivityPresentation) Validate() error

type ActivityRenderer

type ActivityRenderer string
const (
	ActivityRendererStructured ActivityRenderer = "structured"
	ActivityRendererTerminal   ActivityRenderer = "terminal"
	ActivityRendererFile       ActivityRenderer = "file"
	ActivityRendererPatch      ActivityRenderer = "patch"
	ActivityRendererWebSearch  ActivityRenderer = "web_search"
	ActivityRendererTodos      ActivityRenderer = "todos"
	ActivityRendererQuestion   ActivityRenderer = "question"
	ActivityRendererCompletion ActivityRenderer = "completion"
	ActivityRendererSubAgent   ActivityRenderer = "subagent"
)

type ActivityTargetRef

type ActivityTargetRef struct {
	Kind  string `json:"kind"`
	Label string `json:"label"`
	URI   string `json:"uri,omitempty"`
	Path  string `json:"path,omitempty"`
	Line  int    `json:"line,omitempty"`
}

type ActivityUpdate

type ActivityUpdate struct {
	Activity *ActivityPresentation
	Metadata map[string]any
}

type ArtifactRef

type ArtifactRef struct {
	ID        string `json:"id,omitempty"`
	SafeLabel string `json:"safe_label,omitempty"`
	Kind      string `json:"kind,omitempty"`
	MIME      string `json:"mime,omitempty"`
	SizeBytes int64  `json:"size_bytes,omitempty"`
	SHA256    string `json:"sha256,omitempty"`
}

type CompletionActivityPayload

type CompletionActivityPayload struct {
	Status  string `json:"status,omitempty"`
	Summary string `json:"summary,omitempty"`
}

type Definition

type Definition struct {
	Name         string
	Title        string
	Description  string
	InputSchema  map[string]any
	OutputSchema map[string]any
	Activity     func(Invocation[any]) (*ActivityPresentation, error)
	// InvalidActivity may derive presentation-only metadata from a JSON object
	// rejected by InputSchema. It never participates in permission or dispatch.
	InvalidActivity func(Invocation[map[string]any]) (*ActivityPresentation, error)

	Effects     []Effect
	ReadOnly    bool
	Destructive bool
	OpenWorld   bool

	Permission    PermissionSpec
	PermissionFor PermissionResolver
	OutputPolicy  OutputPolicy
	Annotations   map[string]any
}

func ValidateDefinition

func ValidateDefinition(def Definition) (Definition, error)

type DispatchOptions

type DispatchOptions struct {
	RunID         identity.RunID
	ThreadID      identity.ThreadID
	TurnID        identity.TurnID
	PromptScopeID identity.PromptScopeID
	Step          int
	BatchIndex    int
	BatchSize     int
	Labels        map[string]string
	HostContext   map[string]string

	DispatchStarted      func(DispatchStart)
	ActivityUpdated      func(ToolActivityUpdate)
	EffectBatchPreflight EffectBatchPreflight
	EffectDispatcher     EffectDispatcher
}

type DispatchStart

type DispatchStart struct {
	CallID        string
	Name          string
	RawArgs       string
	RunID         identity.RunID
	ThreadID      identity.ThreadID
	TurnID        identity.TurnID
	PromptScopeID identity.PromptScopeID
	Step          int
	Labels        map[string]string
	HostContext   map[string]string
}

type Effect

type Effect string
const (
	EffectRead    Effect = "read"
	EffectWrite   Effect = "write"
	EffectShell   Effect = "shell"
	EffectNetwork Effect = "network"
)

type EffectBatchPreflight

type EffectBatchPreflight func(context.Context, []EffectDispatchRequest) error

type EffectDispatchRequest

type EffectDispatchRequest struct {
	CallID        string
	Name          string
	RawArgs       string
	RunID         identity.RunID
	ThreadID      identity.ThreadID
	TurnID        identity.TurnID
	PromptScopeID identity.PromptScopeID
	Step          int
	BatchIndex    int
	BatchSize     int
	Labels        map[string]string
	HostContext   map[string]string
	// Activity is detached tool-authored display data. It is never authority.
	Activity    *ActivityPresentation
	Resources   []ResourceRef
	Effects     []Effect
	Permission  PermissionSpec
	ReadOnly    bool
	Destructive bool
	OpenWorld   bool
}

type EffectDispatcher

type EffectDispatcher func(context.Context, EffectDispatchRequest, func(context.Context) Result) Result

EffectDispatcher authorizes one prepared effect and chooses the execution context used by the tool handler. A lifecycle-owning dispatcher is responsible for bounding that selected context by its caller's execution lifetime.

type FileActivityPayload

type FileActivityPayload struct {
	Path      string         `json:"path,omitempty"`
	Operation string         `json:"operation,omitempty"`
	Status    string         `json:"status,omitempty"`
	Summary   string         `json:"summary,omitempty"`
	SizeBytes int64          `json:"size_bytes,omitempty"`
	Error     *ActivityError `json:"error,omitempty"`
}

type FullOutputPlan

type FullOutputPlan struct {
	Text string
	Kind string
	MIME string
}

FullOutputPlan is a side-effect-free request to admit the complete tool output together with its canonical result. It is not a durable artifact ref.

type Invocation

type Invocation[T any] struct {
	CallID          string
	Name            string
	RawArgs         string
	Args            T
	RunID           identity.RunID
	ThreadID        identity.ThreadID
	TurnID          identity.TurnID
	PromptScopeID   identity.PromptScopeID
	Step            int
	Labels          map[string]string
	HostContext     map[string]string
	ActivityUpdater func(ActivityUpdate)
}

func (Invocation[T]) UpdateActivity

func (i Invocation[T]) UpdateActivity(update ActivityUpdate)

type OutputPolicy

type OutputPolicy struct {
	VisibleMaxBytes int
	VisibleMaxLines int
	Strategy        OutputStrategy
	PreserveFull    bool
	PreserveFullSet bool
	ArtifactKind    string
	ArtifactMIME    string
}

func DefaultOutputPolicy

func DefaultOutputPolicy() OutputPolicy

func MergeOutputPolicy

func MergeOutputPolicy(base OutputPolicy, override *OutputPolicy) OutputPolicy

func NormalizeOutputPolicy

func NormalizeOutputPolicy(policy OutputPolicy) OutputPolicy

type OutputProjection

type OutputProjection struct {
	VisibleText    string
	Truncated      bool
	OriginalBytes  int
	VisibleBytes   int
	OriginalLines  int
	VisibleLines   int
	Strategy       OutputStrategy
	ContentSHA256  string
	FullOutput     *ArtifactRef
	FullOutputPlan *FullOutputPlan
}

func BuildOutputProjection

func BuildOutputProjection(result Result, policy OutputPolicy) OutputProjection

type OutputStrategy

type OutputStrategy string
const (
	OutputHead OutputStrategy = "head"
	OutputTail OutputStrategy = "tail"
)

type PatchActivityPayload

type PatchActivityPayload struct {
	Path    string         `json:"path,omitempty"`
	Diff    string         `json:"diff,omitempty"`
	Status  string         `json:"status,omitempty"`
	Summary string         `json:"summary,omitempty"`
	Error   *ActivityError `json:"error,omitempty"`
}

type PendingToolResult

type PendingToolResult struct {
	// Handle is the provider-visible continuation token. Hosts should put the
	// exact token here that the model should reuse for later tool calls.
	Handle string
	State  PendingToolResultState
	// Summary and Instruction are provider-visible text.
	Summary     string
	Instruction string
	// Metadata is observation-only pending state. It is not rendered into the
	// provider-visible pending result text.
	Metadata map[string]string
}

PendingToolResult is returned by a tool handler after the host has started work whose lifecycle remains owned by the host application.

func (PendingToolResult) Validate

func (p PendingToolResult) Validate() error

type PendingToolResultState

type PendingToolResultState string
const (
	// PendingToolResultRunning marks host-owned work that is still active outside Floret.
	PendingToolResultRunning PendingToolResultState = "running"
)

type PermissionMode

type PermissionMode string
const (
	PermissionAllow PermissionMode = "allow"
	PermissionAsk   PermissionMode = "ask"
	PermissionDeny  PermissionMode = "deny"
)

type PermissionRequest

type PermissionRequest struct {
	CallID        string
	Name          string
	RawArgs       string
	Args          any
	RunID         identity.RunID
	ThreadID      identity.ThreadID
	TurnID        identity.TurnID
	PromptScopeID identity.PromptScopeID
	Step          int
	Labels        map[string]string
	HostContext   map[string]string
}

type PermissionResolver

type PermissionResolver func(PermissionRequest) (PermissionSpec, error)

type PermissionSpec

type PermissionSpec struct {
	Mode          PermissionMode
	ResourceKinds []string
}

type QuestionActivityAnswer

type QuestionActivityAnswer struct {
	QuestionID string   `json:"question_id"`
	Values     []string `json:"values,omitempty"`
	Redacted   bool     `json:"redacted,omitempty"`
}

QuestionActivityAnswer is a host-authored, presentation-safe answer summary. Secret answers must set Redacted and omit Values.

type QuestionActivityItem

type QuestionActivityItem struct {
	ID       string                   `json:"id"`
	Question string                   `json:"question"`
	Options  []QuestionActivityOption `json:"options,omitempty"`
}

type QuestionActivityOption

type QuestionActivityOption struct {
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
}

type QuestionActivityPayload

type QuestionActivityPayload struct {
	PromptID  string                   `json:"prompt_id,omitempty"`
	Questions []QuestionActivityItem   `json:"questions,omitempty"`
	Answers   []QuestionActivityAnswer `json:"answers,omitempty"`
}

type Registry

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

func NewRegistry

func NewRegistry(items ...Tool) *Registry

func NewRegistryE

func NewRegistryE(items ...Tool) (*Registry, error)

func (*Registry) ActivityForCall

func (r *Registry) ActivityForCall(call ToolCall, opts DispatchOptions) (*ActivityPresentation, error)

func (*Registry) Definition

func (r *Registry) Definition(name string) (Definition, bool)

func (*Registry) Definitions

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

func (*Registry) Dispatch

func (r *Registry) Dispatch(ctx context.Context, call ToolCall, opts DispatchOptions) Result

func (*Registry) DispatchBatch

func (r *Registry) DispatchBatch(ctx context.Context, calls []ToolCall, opts DispatchOptions) []Result

func (*Registry) ExposedDefinitions

func (r *Registry) ExposedDefinitions() []ToolDefinition

func (*Registry) OutputPolicyFor

func (r *Registry) OutputPolicyFor(name string) OutputPolicy

func (*Registry) Register

func (r *Registry) Register(t Tool) error

func (*Registry) Seal

func (r *Registry) Seal()

Seal prevents further registration while preserving definition reads and dispatch for the existing immutable tool snapshot. It is idempotent.

type ResourceRef

type ResourceRef struct {
	Kind  string
	Value string
}

type Result

type Result struct {
	CallID       string
	Name         string
	Title        string
	Text         string
	Structured   map[string]any
	Metadata     map[string]any
	Activity     *ActivityPresentation
	Artifacts    []ArtifactRef
	OutputPolicy *OutputPolicy
	Pending      *PendingToolResult
	IsError      bool
	DispatchErr  error
	// contains filtered or unexported fields
}

func DeclinedResult

func DeclinedResult(callID, name string) Result

DeclinedResult reports a normal user decision that prevented execution. It is provider-visible, but it is not a tool dispatch or execution failure.

func ErrorResult

func ErrorResult(callID, name, text string) Result

func (Result) RequiresEffectFinalization

func (r Result) RequiresEffectFinalization() bool

RequiresEffectFinalization reports whether the result crossed the effect authority dispatcher and therefore requires its atomic result finalizer.

type StructuredActivityPayload

type StructuredActivityPayload struct {
	Status      string                  `json:"status,omitempty"`
	Operation   string                  `json:"operation,omitempty"`
	DisplayName string                  `json:"display_name,omitempty"`
	Summary     string                  `json:"summary,omitempty"`
	DurationMS  int64                   `json:"duration_ms,omitempty"`
	Error       *ActivityError          `json:"error,omitempty"`
	Rows        []StructuredActivityRow `json:"rows,omitempty"`
}

type StructuredActivityRow added in v4.0.18

type StructuredActivityRow struct {
	Title   string                      `json:"title,omitempty"`
	Meta    string                      `json:"meta,omitempty"`
	Content string                      `json:"content,omitempty"`
	Format  StructuredActivityRowFormat `json:"format,omitempty"`
}

StructuredActivityRow is one ordered, product-neutral display row for a structured tool activity. Hosts author already-sanitized display text.

type StructuredActivityRowFormat added in v4.0.18

type StructuredActivityRowFormat string

StructuredActivityRowFormat describes how a structured activity row's content should be presented by a host.

const (
	StructuredActivityRowFormatText     StructuredActivityRowFormat = "text"
	StructuredActivityRowFormatMarkdown StructuredActivityRowFormat = "markdown"
	StructuredActivityRowFormatCode     StructuredActivityRowFormat = "code"
)

type SubAgentActivityPayload

type SubAgentActivityPayload struct {
	ThreadID        identity.ThreadID `json:"thread_id"`
	Path            string            `json:"path,omitempty"`
	TaskName        string            `json:"task_name,omitempty"`
	TaskDescription string            `json:"task_description,omitempty"`
	Title           string            `json:"title,omitempty"`
	HostProfileRef  string            `json:"host_profile_ref,omitempty"`
	ForkMode        string            `json:"fork_mode,omitempty"`
	Status          string            `json:"status"`
	LastMessage     string            `json:"last_message,omitempty"`
	WaitingPrompt   string            `json:"waiting_prompt,omitempty"`
	QueuedInputs    int               `json:"queued_inputs,omitempty"`
	ParentThreadID  identity.ThreadID `json:"parent_thread_id"`
	ParentTurnID    identity.TurnID   `json:"parent_turn_id,omitempty"`
	LatestTurnID    identity.TurnID   `json:"latest_turn_id,omitempty"`
	CreatedAtUnixMS int64             `json:"created_at_unix_ms,omitempty"`
	UpdatedAtUnixMS int64             `json:"updated_at_unix_ms,omitempty"`
	Closed          bool              `json:"closed,omitempty"`
	CanSendInput    bool              `json:"can_send_input"`
	CanInterrupt    bool              `json:"can_interrupt"`
	CanClose        bool              `json:"can_close"`
}

SubAgentActivityPayload describes the durable child-thread fact rendered by a parent activity view. Child execution details remain in the child stream.

type TerminalActivityPayload

type TerminalActivityPayload struct {
	Command       string         `json:"command,omitempty"`
	Status        string         `json:"status,omitempty"`
	ProcessID     string         `json:"process_id,omitempty"`
	LatestOutput  string         `json:"latest_output,omitempty"`
	Output        string         `json:"output,omitempty"`
	Stdout        string         `json:"stdout,omitempty"`
	Stderr        string         `json:"stderr,omitempty"`
	ExitCode      *int           `json:"exit_code,omitempty"`
	DurationMS    int64          `json:"duration_ms,omitempty"`
	Truncated     bool           `json:"truncated,omitempty"`
	PendingResult string         `json:"pending_result,omitempty"`
	Terminated    bool           `json:"terminated,omitempty"`
	Error         *ActivityError `json:"error,omitempty"`
}

type TodoActivityItem

type TodoActivityItem struct {
	Text   string `json:"text"`
	Status string `json:"status"`
}

type TodosActivityPayload

type TodosActivityPayload struct {
	Operation string             `json:"operation,omitempty"`
	Items     []TodoActivityItem `json:"items,omitempty"`
}

type Tool

type Tool struct {
	Definition Definition
	// contains filtered or unexported fields
}

func Define

func Define[T any](
	def Definition,
	decode func([]byte) (T, error),
	resources func(Invocation[T]) ([]ResourceRef, error),
	handler func(context.Context, Invocation[T]) (Result, error),
) Tool

type ToolActivityUpdate

type ToolActivityUpdate struct {
	CallID        string
	Name          string
	RawArgs       string
	RunID         identity.RunID
	ThreadID      identity.ThreadID
	TurnID        identity.TurnID
	PromptScopeID identity.PromptScopeID
	Step          int
	Labels        map[string]string
	HostContext   map[string]string
	Activity      *ActivityPresentation
	Metadata      map[string]any
}

type ToolCall

type ToolCall struct {
	ID        string
	Name      string
	Args      string
	Reasoning string
}

type ToolDefinition

type ToolDefinition struct {
	Name         string         `json:"name"`
	Title        string         `json:"title,omitempty"`
	Description  string         `json:"description"`
	InputSchema  map[string]any `json:"input_schema"`
	OutputSchema map[string]any `json:"output_schema,omitempty"`
	Strict       bool           `json:"strict,omitempty"`
	Annotations  map[string]any `json:"annotations,omitempty"`
}

type WebSearchActivityPayload

type WebSearchActivityPayload struct {
	Query   string                    `json:"query,omitempty"`
	Status  string                    `json:"status,omitempty"`
	Results []WebSearchActivityResult `json:"results,omitempty"`
	Error   *ActivityError            `json:"error,omitempty"`
}

type WebSearchActivityResult

type WebSearchActivityResult struct {
	Title string `json:"title"`
	URL   string `json:"url"`
}

Jump to

Keyboard shortcuts

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