tool

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: AGPL-3.0 Imports: 5 Imported by: 0

Documentation

Overview

Package tool defines the core tool execution framework for ore.

It provides the universal contracts for tool registration (Registry), tool functions (ToolFunc), remote tool sources (RemoteSource), and schema validation (ValidateSchema).

Sandboxes

Sandbox interfaces enable per-tool-call isolation. The handler resolves a sandbox for each tool call and passes it to the ToolFunc. Tools opt into available capabilities via type assertions on the received Sandbox.

  • Sandbox — base interface with Name(). A nil Sandbox means no isolation; tools execute against the host filesystem and process space.
  • FileSandbox — extends Sandbox with ResolvePath(path) (string, error) and WorkingDirectory() string. Tools type-assert to FileSandbox when they need path resolution and working directory constraints.
  • ExecSandbox — extends Sandbox with Run(ctx, cmd, dir, timeout) which delegates command execution to the sandbox. Tools type-assert to ExecSandbox when they need process isolation.

SandboxRegistry (see registry.go) extends Registry with methods to register, look up, and set a default sandbox. Handlers type-assert the registry to SandboxRegistry to resolve sandboxes per tool call. If the registry does not implement SandboxRegistry, all tool calls receive a nil sandbox.

Concrete tool implementations, discovery mechanisms, and the loop.Handler bridge live in the x/tool/ extension packages. This package defines only the contracts that core packages (cognitive/, junk/, loop/) can import without creating dependency cycles.

This separation is intentional: placing the handler bridge in x/tool/ prevents the core contracts from importing loop/ or provider/, preserving the framework's cycle-free dependency graph.

The default in-memory Registry implementation is analogous to state.Buffer: it is not goroutine-safe, and concurrency control is a future middleware concern.

Index

Constants

View Source
const FrameworkDefaultMaxBytes = 50_000

FrameworkDefaultMaxBytes is the framework's default byte cap. It matches pi's truncate.ts default of 50 KB.

View Source
const FrameworkDefaultMaxLines = 2000

FrameworkDefaultMaxLines is the framework's default line cap. It matches pi's truncate.ts default of 2000 lines.

Variables

This section is empty.

Functions

func ValidateSchema

func ValidateSchema(schema map[string]any) error

ValidateSchema checks that a JSON Schema intended for OpenAI-compatible function calling is structurally sound. It returns a descriptive error if the schema violates common requirements.

Rules:

  • nil or empty schema is valid (no parameters).
  • The schema must be JSON-serializable.
  • If the schema has any keys, the root type must be "object".
  • All top-level keys must be known JSON Schema keywords; any other key is treated as a misplaced parameter definition and results in an error.

Types

type Example added in v0.7.1

type Example struct {
	// Input is the JSON arguments passed to the tool.
	Input map[string]any
	// Output is the expected result produced by the tool.
	Output any
	// Explanation is a human-readable note describing why the example
	// produces the given output.
	Explanation string
}

Example describes a single few-shot usage example for a tool.

type ExecSandbox added in v0.0.2

type ExecSandbox interface {
	Sandbox
	Run(ctx context.Context, cmd, dir string, timeout time.Duration) (stdout, stderr string, exitCode int, err error)
}

ExecSandbox provides process isolation for tool execution. Tools type-assert the received Sandbox to ExecSandbox when they need to delegate command execution to the sandbox.

type FileSandbox added in v0.0.2

type FileSandbox interface {
	Sandbox
	ResolvePath(path string) (string, error)
	WorkingDirectory() string
}

FileSandbox provides filesystem isolation for tool execution. Tools type-assert the received Sandbox to FileSandbox when they need path resolution or working directory constraints.

type Format added in v0.8.0

type Format struct {
	// Truncate configures byte and line caps on the LLM-facing string.
	// Zero values fall back to framework defaults. Use MaxBytes and/or
	// MaxLines to override; the smaller of the two caps wins.
	Truncate TruncateConfig

	// Style controls head-vs-tail truncation. The zero value is
	// StyleTail, which retains the END of the result (matching
	// terminal output conventions). StyleHead retains the START,
	// matching file-read conventions.
	Style TruncationStyle

	// RecoveryHint is a template string appended to a truncated
	// result. The framework substitutes {name} placeholders against
	// the truncation metadata; unknown placeholders are left
	// as-is. Examples:
	//
	//   "Use offset={next_offset} to continue reading."
	//   "Full output at {path}. Use grep/tail/head to extract."
	RecoveryHint string
}

Format declares how a tool's result should be rendered before being returned to the LLM. The zero value of Format is meaningful: it instructs the framework handler to apply default truncation (50 KB / 2000 lines, tail style) and no recovery hint. Tools that know their output is intentionally small (e.g. arithmetic) populate Format with TruncateConfig{} and an empty RecoveryHint to document that intent explicitly; the handler still consults the framework default, which is large enough not to truncate the result.

func (Format) ResolvedTruncateConfig added in v0.8.0

func (f Format) ResolvedTruncateConfig() TruncateConfig

ResolvedTruncateConfig returns the effective TruncateConfig for a Format. Zero fields are filled in from the framework defaults. The framework handler calls this before invoking the truncator.

type Option

type Option func(*registry)

Option is a functional-options setter that configures a Registry instance at creation time.

func WithMCPServer

func WithMCPServer(source RemoteSource) Option

WithMCPServer registers a remote tool source with the registry. Remote tools are namespaced under the source's Name() prefix.

type Registry

type Registry interface {
	// Register adds a tool to the registry.
	Register(t Tool, fn ToolFunc) error
	// Tools returns a merged list of all registered tools.
	Tools() []Tool
	// Lookup returns the tool descriptor, the tool function, and true if the
	// tool is registered locally.
	Lookup(name string) (Tool, ToolFunc, bool)
	// LookupRemoteSource finds a remote source by its namespace prefix.
	LookupRemoteSource(namespace string) RemoteSource
}

Registry is the interface for tool registration and lookup.

func NewRegistry

func NewRegistry(opts ...Option) Registry

NewRegistry creates an empty tool registry ready for tool registration. The returned registry is not safe for concurrent use; callers must serialize accesses or provide their own synchronization.

type RemoteSource

type RemoteSource interface {
	// Name returns the namespace prefix for tools from this source.
	Name() string
	// Tools returns the list of tools available from this source (un-namespaced).
	Tools() []Tool
	// Call invokes a tool by name with the given arguments.
	Call(ctx context.Context, name string, args map[string]any) (any, error)
}

RemoteSource represents an external source of tools (e.g., an MCP server). The Registry consumes this interface without importing the concrete MCP package, allowing clean extension without import cycles.

type Sandbox added in v0.0.2

type Sandbox interface {
	Name() string
}

Sandbox is the base interface for all sandbox implementations. A nil sandbox means no isolation (tools execute against the host).

type SandboxRegistry added in v0.0.2

type SandboxRegistry interface {
	Registry
	// RegisterSandbox adds a named sandbox to the registry. If a sandbox with
	// the same name already exists, it is overwritten.
	RegisterSandbox(name string, sb Sandbox)
	// SetDefaultSandbox sets the default sandbox used when no explicit
	// "sandbox" argument is present in a tool call.
	SetDefaultSandbox(sb Sandbox)
	// LookupSandbox returns the named sandbox and true if found.
	LookupSandbox(name string) (Sandbox, bool)
	// DefaultSandbox returns the default sandbox (may be nil).
	DefaultSandbox() Sandbox
}

SandboxRegistry extends Registry with sandbox management capabilities. Handlers type-assert the registry to SandboxRegistry to resolve sandboxes per tool call. If the registry does not implement this interface, all tool calls receive a nil sandbox.

type Tool added in v0.4.0

type Tool struct {
	Name        string
	Description string
	// Schema defines the JSON Schema for the tool's parameters.
	Schema map[string]any
	// DisplayHint is an optional formatter that receives parsed JSON
	// arguments and returns a displayable value for human rendering
	// (TUI, exporters, log viewers). The return value is purely a
	// display artifact: it is attached to ToolCall.Display by the loop
	// pipeline's applyDisplayHints step and read only by display-layer
	// consumers. It has no effect on the wire format sent to the
	// provider — the wire format is always derived from Arguments,
	// the JSON the model streamed. Implementing MarkdownRenderer is
	// recommended for rich rendering; returning a string is the common
	// case for simple labels; returning nil is also valid (the
	// consumer falls back to raw Arguments). When DisplayHint itself
	// is nil, no Display value is set.
	DisplayHint func(map[string]any) any
	// Examples is an optional list of few-shot input/output pairs that
	// illustrate how the tool should be used. They are not sent to the
	// provider by default; applications may opt-in via systemprompt
	// transforms or other middleware.
	Examples []Example
	// Format declares how the tool's result should be rendered for the
	// LLM. The zero value instructs the framework handler to apply
	// default truncation (50 KB / 2000 lines, tail style) and no
	// recovery hint. Tools that implement artifact.LLMRenderer opt
	// out of Format entirely; the handler respects their output
	// as-is.
	Format Format
}

Tool describes a callable tool exposed to an LLM provider.

type ToolFunc

type ToolFunc func(ctx context.Context, sb Sandbox, args map[string]any) (any, error)

ToolFunc is a callable tool implementation. It receives a resolved sandbox (may be nil if no sandbox is configured) and parsed JSON arguments as a map[string]any and returns any result value, which is JSON-serialized before being sent back to the LLM.

type TruncateConfig added in v0.8.0

type TruncateConfig struct {
	// MaxBytes is the maximum number of bytes to retain in the
	// LLM-facing result. Zero means use the framework default.
	MaxBytes int

	// MaxLines is the maximum number of newline-terminated lines to
	// retain. Zero means use the framework default. A trailing line
	// without a newline is not counted.
	MaxLines int
}

TruncateConfig configures the byte and line caps on a tool result. Zero values mean "use framework defaults" — the handler will substitute DefaultTruncateConfig() at application time.

func DefaultTruncateConfig added in v0.8.0

func DefaultTruncateConfig() TruncateConfig

DefaultTruncateConfig returns the framework's default byte and line caps. The handler uses this when a tool's Format.Truncate has zero values.

type TruncationStyle added in v0.8.0

type TruncationStyle int

TruncationStyle selects whether the kept portion of a truncated result is the head (start) or tail (end).

const (
	// StyleTail retains the END of the result. This is the zero
	// value and the default for most tools because terminal output
	// (errors, summaries) tends to live at the end.
	StyleTail TruncationStyle = iota

	// StyleHead retains the START of the result. Suitable for
	// tools that read the beginning of files or listings.
	StyleHead
)

func (TruncationStyle) String added in v0.8.0

func (s TruncationStyle) String() string

String returns a stable name for the truncation style. Used for observability metadata and the Style field on artifact.Truncation.

Jump to

Keyboard shortcuts

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