contract

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Index

Constants

View Source
const PermissionRuleMatcherKey = "permission_rule_matcher"

PermissionRuleMatcherKey is the metadata key used to pass a prepared matcher through runtime metadata.

View Source
const ResolvedToolMetadataKey = "resolved_tool"

ResolvedToolMetadataKey is the metadata key used to pass the resolved tool through runtime metadata.

Variables

This section is empty.

Functions

func AttachPermissionMatcherMetadata

func AttachPermissionMatcherMetadata(metadata map[string]any, resolvedTool Tool, matcher func(string) bool) map[string]any

AttachPermissionMatcherMetadata clones metadata and injects optional tool permission matching context.

func BuildPermissionMatcher

func BuildPermissionMatcher(ctx context.Context, resolvedTool Tool, input map[string]any) (func(string) bool, error)

BuildPermissionMatcher prepares a content-specific permission matcher when the tool supports it.

func ExecutesInPlanMode

func ExecutesInPlanMode(t Tool, input map[string]any) bool

ExecutesInPlanMode returns true when a tool should execute while the session is in plan mode. Read-only tools are always allowed so the agent can inspect the codebase, and specific control tools can opt in explicitly.

func IsValidToolName

func IsValidToolName(name string) bool

IsValidToolName validates a tool name

func PermissionMatcherFromMetadata

func PermissionMatcherFromMetadata(metadata map[string]any) func(string) bool

PermissionMatcherFromMetadata extracts a prepared permission matcher from metadata when available.

func RequiresUserInteraction

func RequiresUserInteraction(t Tool) bool

RequiresUserInteraction returns true if the tool requires explicit user interaction even in bypass mode. Returns false if the tool does not implement RequiresUserInteractionTool or if it returns false.

Types

type CallInput

type CallInput struct {
	// Raw is the raw input string (for backward compatibility)
	Raw string `json:"raw,omitempty"`

	// Parsed is the structured input
	Parsed map[string]any `json:"parsed,omitempty"`

	// ToolUseID identifies which tool use this is for
	ToolUseID string `json:"tool_use_id,omitempty"`

	// SessionID identifies the session
	SessionID types.SessionID `json:"session_id,omitempty"`

	// TurnID identifies the turn
	TurnID types.TurnID `json:"turn_id,omitempty"`

	// ToolContext carries the runtime tool context for advanced execution paths.
	ToolContext *ToolUseContext `json:"-"`
}

CallInput represents the input to a tool call

func (CallInput) ToolContextValue

func (i CallInput) ToolContextValue() ToolUseContext

ToolContextValue returns the runtime tool context carried by the call input, or a default context.

type CallResult

type CallResult struct {
	// Data is the result data
	Data any `json:"data"`

	// ContentType indicates the type of result
	ContentType ContentType `json:"content_type"`

	// Content is the formatted content (for text results)
	Content string `json:"content,omitempty"`

	// Error contains any error that occurred
	Error error `json:"error,omitempty"`

	// Metadata contains additional result information
	Metadata *ResultMetadata `json:"metadata,omitempty"`

	// ProgressUpdates contains any progress updates made during execution
	ProgressUpdates []types.ToolProgress `json:"progress_updates,omitempty"`

	// NewMessages contains any follow-up runtime messages emitted by the tool.
	NewMessages []types.Message `json:"new_messages,omitempty"`

	// ContextModifier mutates runtime context after successful execution.
	ContextModifier ContextModifier `json:"-"`
}

CallResult represents the result of a tool call

func NewErrorResult

func NewErrorResult(err error) CallResult

NewErrorResult creates a new error result

func NewJSONResult

func NewJSONResult(data any) CallResult

NewJSONResult creates a new JSON result

func NewTextResult

func NewTextResult(content string) CallResult

NewTextResult creates a new text result

func (CallResult) GetContent

func (r CallResult) GetContent() string

GetContent returns the content as a string

func (CallResult) GetData

func (r CallResult) GetData() any

GetData returns the data

func (CallResult) IsError

func (r CallResult) IsError() bool

IsError returns true if the tool call failed

func (CallResult) IsSuccess

func (r CallResult) IsSuccess() bool

IsSuccess returns true if the tool call succeeded

func (CallResult) String

func (r CallResult) String() string

String returns the string representation of a tool result

type ContentType

type ContentType string

ContentType represents the type of tool result

const (
	ContentTypeText   ContentType = "text"
	ContentTypeJSON   ContentType = "json"
	ContentTypeBinary ContentType = "binary"
	ContentTypeStream ContentType = "stream"
	ContentTypeMixed  ContentType = "mixed"
)

type ContextModifier

type ContextModifier func(ToolUseContext) ToolUseContext

ContextModifier mutates the tool runtime context after a tool call.

type Definition

type Definition struct {
	// Name is the unique identifier for this tool
	Name string `json:"name"`

	// DisplayName is a human-readable name
	DisplayName string `json:"display_name,omitempty"`

	// Description explains what the tool does
	Description string `json:"description"`

	// Prompt provides detailed guidance on when and how to use the tool
	// This is used by the AI to understand the tool's usage patterns
	Prompt string `json:"prompt,omitempty"`

	// SearchHint provides a hint for tool search functionality
	SearchHint string `json:"search_hint,omitempty"`

	// Category groups related tools together
	Category string `json:"category,omitempty"`

	// InputSchema defines the expected input structure
	InputSchema schema.JSONSchema `json:"input_schema"`

	// IsReadOnly indicates if the tool doesn't modify state
	IsReadOnly bool `json:"is_read_only"`

	// IsDestructive indicates if the tool can cause destructive changes
	IsDestructive bool `json:"is_destructive"`

	// IsConcurrencySafe indicates if the tool can run concurrently with others
	IsConcurrencySafe bool `json:"is_concurrency_safe"`

	// RequiresPermission indicates if the tool requires permission checks
	RequiresPermission bool `json:"requires_permission"`

	// Aliases are alternative names for this tool
	Aliases []string `json:"aliases,omitempty"`

	// MaxResultSize is the maximum number of characters allowed in the tool
	// result content. When exceeded the runtime truncates and records a
	// ContentReplacementState (equivalent to OpenClaude's maxResultSizeChars).
	// A value of 0 means unlimited.
	MaxResultSize int `json:"max_result_size,omitempty"`

	// ShouldDefer indicates this tool must be loaded via ToolSearch before calling.
	ShouldDefer bool `json:"should_defer,omitempty"`

	// AlwaysLoad indicates this tool should always be loaded in the initial prompt.
	AlwaysLoad bool `json:"always_load,omitempty"`

	// IsMCP indicates this is an MCP tool.
	IsMCP bool `json:"is_mcp,omitempty"`

	// Metadata contains additional tool metadata
	Metadata map[string]any `json:"metadata,omitempty"`
}

Definition defines a tool's metadata and schema

func (Definition) Validate

func (d Definition) Validate() error

Validate validates a tool definition

type PermissionMatcherTool

type PermissionMatcherTool interface {
	PreparePermissionMatcher(ctx context.Context, input map[string]any) (func(ruleContent string) bool, error)
}

PermissionMatcherTool is an optional capability for tools that support content-specific permission-rule matching.

type PlanModeExecutableTool

type PlanModeExecutableTool interface {
	ExecutesInPlanMode(input map[string]any) bool
}

PlanModeExecutableTool is an optional capability for tools that must still execute while the session is in plan mode, even if they are not read-only. This is primarily for plan control-flow tools such as ExitPlanMode.

type RequiresUserInteractionTool

type RequiresUserInteractionTool interface {
	RequiresUserInteraction() bool
}

RequiresUserInteractionTool is an optional capability for tools that require explicit user interaction even in bypass mode. When a tool implements this interface and RequiresUserInteraction returns true, the permission pipeline will not auto-allow the tool in bypass mode. Aligned with OpenClaude's tool.requiresUserInteraction?().

type ResultMetadata

type ResultMetadata struct {
	// ExecutionDuration is how long the tool took to run (milliseconds)
	ExecutionDuration int64 `json:"execution_duration_ms"`

	// ContentReplacement indicates if content was replaced due to size
	ContentReplacement *types.ContentReplacementState `json:"content_replacement,omitempty"`

	// Additional metadata
	Additional map[string]any `json:"additional,omitempty"`
}

ResultMetadata contains metadata about a tool result

type Tool

type Tool interface {
	// Definition returns the tool's definition.
	Definition() Definition

	// Call executes the tool with the given input.
	// The returned error is reserved for truly unrecoverable system failures
	// (e.g. context cancellation). Tool-level errors should be returned inside
	// CallResult.Error so that the runtime always produces a tool_result message.
	Call(ctx context.Context, input CallInput, permissionCheck types.CanUseToolFn) (CallResult, error)

	// Description returns a human-readable description of what this tool does.
	Description(ctx context.Context) (string, error)

	// ValidateInput validates and optionally normalizes tool input before execution.
	ValidateInput(ctx context.Context, input map[string]any) (map[string]any, error)

	// CheckPermissions performs tool-specific permission checks before the global
	// permission pipeline. Return types.Passthrough to delegate to global checks.
	CheckPermissions(ctx context.Context, input map[string]any, toolCtx ToolUseContext) types.PermissionResult

	// IsConcurrencySafe returns whether this specific tool use can run concurrently.
	IsConcurrencySafe(input map[string]any) bool

	// IsReadOnly returns whether this specific tool use is read-only.
	IsReadOnly(input map[string]any) bool

	// IsEnabled returns whether this tool is currently active.
	// Disabled tools are skipped during execution. Default: true.
	IsEnabled() bool

	// FormatResult serialises the tool output into the string that will be sent
	// back to the model inside a tool_result content block. Each tool controls
	// its own serialisation (equivalent to OpenClaude's mapToolResultToToolResultBlockParam).
	// Default: fmt.Sprintf("%v", data) when Content is empty.
	FormatResult(data any) string

	// BackfillInput enriches a shallow clone of the parsed input with derived
	// fields that should be visible to hooks and permissions but are NOT passed
	// to tool.Call() (equivalent to OpenClaude's backfillObservableInput).
	// The returned map is the enriched copy. Default: returns input unchanged.
	BackfillInput(ctx context.Context, input map[string]any) map[string]any
}

Tool represents a tool that can be called by the AI.

This interface is aligned with OpenClaude's Tool contract. Every method beyond the core seven (Definition, Call, Description, ValidateInput, CheckPermissions, IsConcurrencySafe, IsReadOnly) has a sensible default provided by baseTool so that simple tools only implement what they need.

func ToolFromMetadata

func ToolFromMetadata(metadata map[string]any) Tool

ToolFromMetadata extracts a resolved tool from metadata when available.

type ToolSurface

type ToolSurface struct {
	// Name is the unique identifier for this tool
	Name string `json:"name"`

	// DisplayName is a human-readable name
	DisplayName string `json:"display_name,omitempty"`

	// Description explains what the tool does
	Description string `json:"description"`

	// Prompt provides detailed guidance on when and how to use the tool
	// This is used by the AI to understand the tool's usage patterns
	Prompt string `json:"prompt,omitempty"`

	// SearchHint provides a hint for tool search functionality
	SearchHint string `json:"search_hint,omitempty"`

	// Category groups related tools together
	Category string `json:"category,omitempty"`

	// InputSchema defines the expected input structure
	InputSchema schema.JSONSchema `json:"input_schema"`

	// IsReadOnly indicates if the tool doesn't modify state
	IsReadOnly bool `json:"is_read_only"`

	// IsDestructive indicates if the tool can cause destructive changes
	IsDestructive bool `json:"is_destructive"`

	// IsConcurrencySafe indicates if the tool can run concurrently with others
	IsConcurrencySafe bool `json:"is_concurrency_safe"`

	// RequiresPermission indicates if the tool requires permission checks
	RequiresPermission bool `json:"requires_permission"`

	// Aliases are alternative names for this tool
	Aliases []string `json:"aliases,omitempty"`

	// MaxResultSize is the maximum number of characters allowed in the tool
	// result content. When exceeded the runtime truncates and records a
	// ContentReplacementState (equivalent to OpenClaude's maxResultSizeChars).
	// A value of 0 means unlimited.
	MaxResultSize int `json:"max_result_size,omitempty"`

	// Metadata contains additional tool metadata
	Metadata map[string]any `json:"metadata,omitempty"`
}

ToolSurface represents the tool surface exposed to the model. This contains all the information needed to display and use a tool in the AI interface.

func FromJSON

func FromJSON(data []byte) (*ToolSurface, error)

FromJSON creates a ToolSurface from JSON format.

func NewToolSurfaceFromDefinition

func NewToolSurfaceFromDefinition(def Definition) ToolSurface

NewToolSurfaceFromDefinition creates a ToolSurface from a Tool Definition.

func (ToolSurface) IsEnabled

func (s ToolSurface) IsEnabled() bool

IsEnabled returns whether the tool is enabled (always true for surfaces).

func (ToolSurface) MatchesName

func (s ToolSurface) MatchesName(name string) bool

MatchesName checks if this tool matches the given name or any alias.

func (ToolSurface) ToJSON

func (s ToolSurface) ToJSON() ([]byte, error)

ToJSON converts the ToolSurface to JSON format.

func (ToolSurface) ToMap

func (s ToolSurface) ToMap() map[string]any

ToMap converts the ToolSurface to a map representation.

type ToolUseContext

type ToolUseContext struct {
	// SessionID identifies the session
	SessionID types.SessionID `json:"session_id"`

	// TurnID identifies the turn
	TurnID types.TurnID `json:"turn_id"`

	// ToolUseID identifies this specific tool use
	ToolUseID string `json:"tool_use_id"`

	// PermissionMode is the current permission mode (who approves)
	PermissionMode types.PermissionMode `json:"permission_mode"`

	// ExecutionMode is the current execution mode (agent behavior: plan, execute, browse)
	// Separated from PermissionMode for clean separation of concerns.
	ExecutionMode string `json:"execution_mode,omitempty"`

	// PrePlanMode stores the mode that was active before entering plan mode.
	PrePlanMode types.PermissionMode `json:"pre_plan_mode,omitempty"`

	// IsAutoModeAvailable indicates whether auto mode is available for the session.
	IsAutoModeAvailable bool `json:"is_auto_mode_available,omitempty"`

	// WorkingDirectory is the current working directory
	WorkingDirectory string `json:"working_directory,omitempty"`

	// Workspace is the enforced filesystem boundary for file-aware tools.
	Workspace *workspace.Context `json:"-"`

	// AdditionalWorkingDirectories holds extra working directories that the
	// tool may access (equivalent to OpenClaude's additionalWorkingDirectories).
	AdditionalWorkingDirectories map[string]string `json:"additional_working_directories,omitempty"`

	// EnableSandbox indicates whether the tool should run in a sandbox.
	// Used for sandbox auto-allow permission logic.
	EnableSandbox bool `json:"enable_sandbox,omitempty"`

	// CanUseTool is the permission check function
	CanUseTool types.CanUseToolFn `json:"-"`

	// RequestPrompt is a function to prompt the user
	RequestPrompt types.PromptFn `json:"-"`

	// Metadata contains additional context
	Metadata map[string]any `json:"metadata,omitempty"`

	// IsBypassPermissionsModeAvailable indicates whether bypass mode was
	// available at the start of the session. Used by plan mode to determine
	// whether it should behave like bypass mode or ask for permissions.
	IsBypassPermissionsModeAvailable bool `json:"is_bypass_permissions_mode_available,omitempty"`
}

ToolUseContext provides context for tool execution. Aligned with OpenClaude's ToolUseContext (headless-relevant subset).

func NewToolUseContext

func NewToolUseContext(
	sessionID types.SessionID,
	turnID types.TurnID,
	toolUseID string,
	permissionMode types.PermissionMode,
) ToolUseContext

NewToolUseContext creates a new ToolUseContext

type Toolset

type Toolset interface {
	// Name returns a stable identifier for this toolset (used in logs/traces).
	Name() string
	// Tools returns the tools that should be available for this iteration.
	// Implementations must be fast; they are called every loop iteration.
	Tools(ctx context.Context) []Tool
}

Toolset is a named group of tools resolved dynamically at call time.

Unlike static tool registration (once at session creation), a Toolset is evaluated at the beginning of each loop iteration so that the set of available tools can change based on runtime context — the current session state, user preferences, permissions, or any other dynamic condition.

Usage:

RunRequest.Toolsets = []contract.Toolset{myDynamicSet}

The loop merges the returned tools with the static Tools map each iteration. If a Toolset returns a tool whose name already exists in the static map the Toolset version takes precedence (allows overriding defaults at runtime).

Jump to

Keyboard shortcuts

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