tools

package
v1.14.0 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package tools provides the unified tool abstraction for Celeste CLI. This file implements StreamingToolExecutor, a state machine that accepts tool calls as they arrive during LLM streaming and dispatches them according to their concurrency safety.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RankDocs added in v1.14.0

func RankDocs(docs []string, query string) []int

RankDocs ranks free-text documents by BM25 against query and returns their indices, best match first. An empty query returns every index in original order (no filtering); a non-empty query returns only documents that score above zero. Shares the tokenizer + BM25 parameters with ToolIndex, so the skills browser ranks with the same relevance as find_tools.

Types

type AskFunc added in v1.13.0

type AskFunc func(ctx context.Context, req AskRequest) (AskResponse, error)

AskFunc is a blocking callback that presents an AskRequest and returns the user's answer. Installed only in interactive (TUI) mode; nil means headless, in which case Ask returns an error rather than deadlocking.

type AskOption added in v1.13.0

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

AskOption is one selectable choice presented by the ask tool.

type AskRequest added in v1.13.0

type AskRequest struct {
	Question    string      `json:"question"`
	Options     []AskOption `json:"options"`
	MultiSelect bool        `json:"multi_select"`
}

AskRequest is a structured question the model asks the user mid-turn.

type AskResponse added in v1.13.0

type AskResponse struct {
	Selected  []string // chosen option labels
	Cancelled bool
}

AskResponse carries the user's selection.

type ExecutorResult

type ExecutorResult struct {
	CallID   string     // The tool call ID from the LLM
	ToolName string     // The tool name
	State    ToolState  // Final state
	Result   ToolResult // Tool output (content and/or error)
	Err      error      // Go error if tool execution returned one
}

ExecutorResult holds the result of a single tool execution, including the call metadata and final state.

type HookResult added in v1.8.0

type HookResult struct {
	Decision string // "approve" or "block"
	Output   string
}

HookResult is the outcome of a pre/post tool hook.

type HookRunner added in v1.8.0

type HookRunner interface {
	RunPreToolUse(toolName string, input map[string]any) (*HookResult, error)
	RunPostToolUse(toolName string, input map[string]any) (*HookResult, error)
}

HookRunner is an interface for running pre/post tool hooks. This avoids a circular dependency between tools and hooks packages.

type InterruptBehavior

type InterruptBehavior int

InterruptBehavior defines how a tool responds to cancellation signals.

const (
	// InterruptCancel means the tool should be cancelled immediately.
	InterruptCancel InterruptBehavior = iota
	// InterruptBlock means the tool should block until completion.
	InterruptBlock
)

type PermissionRequest added in v1.10.0

type PermissionRequest struct {
	ToolName     string
	InputSummary string // short human-readable summary of what the tool will do
	RiskLevel    string // "read", "write", or "destructive"
}

PermissionRequest describes a pending tool invocation that requires user approval. It is passed to PromptFunc when the permission checker returns Ask.

type PermissionResponse added in v1.10.0

type PermissionResponse struct {
	Decision string // "allow_once", "always_allow", "deny", "always_deny"
	Pattern  string // rule pattern for "always" decisions
}

PermissionResponse carries the user's decision from an interactive prompt.

type ProgressEvent

type ProgressEvent struct {
	ToolName string  `json:"tool_name"`
	Message  string  `json:"message"`
	Percent  float64 `json:"percent"` // -1 for indeterminate
}

ProgressEvent represents a progress update from a running tool.

type PromptFunc added in v1.10.0

type PromptFunc func(req PermissionRequest) PermissionResponse

PromptFunc is a blocking callback invoked when a tool execution requires interactive approval. It runs in the tool-execution goroutine (off the Bubble Tea Update loop), so it may safely block until the user responds. Returning a zero-value PermissionResponse (empty Decision) is treated as deny.

type Registry

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

Registry manages the collection of available tools and their mode associations.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new empty tool registry.

func (*Registry) Activate added in v1.13.0

func (r *Registry) Activate(names ...string)

Activate re-exposes hidden tools for the rest of the session (called by find_tools after a BM25 match).

func (*Registry) Ask added in v1.13.0

func (r *Registry) Ask(ctx context.Context, req AskRequest) (AskResponse, error)

Ask presents a structured question to the user and blocks for the answer. Returns an error when no callback is installed (headless / one-shot / serve), so the caller can degrade gracefully instead of deadlocking.

func (*Registry) Count

func (r *Registry) Count() int

Count returns the number of registered tools.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, name string, input map[string]any) (ToolResult, error)

Execute runs a tool by name with input validation.

func (*Registry) ExecuteWithProgress

func (r *Registry) ExecuteWithProgress(ctx context.Context, name string, input map[string]any, progress chan<- ProgressEvent) (ToolResult, error)

ExecuteWithProgress runs a tool by name with input validation and a progress channel.

func (*Registry) Get

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

Get returns a tool by name.

func (*Registry) GetAll

func (r *Registry) GetAll() []Tool

GetAll returns all registered tools sorted by name.

func (*Registry) GetToolDefinitions

func (r *Registry) GetToolDefinitions() []map[string]any

GetToolDefinitions returns all tools in OpenAI function-calling format.

func (*Registry) GetToolDefinitionsForMode

func (r *Registry) GetToolDefinitionsForMode(mode RuntimeMode) []map[string]any

GetToolDefinitionsForMode returns tools for the given mode in OpenAI function-calling format.

func (*Registry) GetTools

func (r *Registry) GetTools(mode RuntimeMode) []Tool

GetTools returns tools available for the given mode, sorted by name.

func (*Registry) LoadCustomTools

func (r *Registry) LoadCustomTools(dir string) error

LoadCustomTools loads JSON tool definitions from a directory. This provides backwards compatibility with ~/.celeste/skills/*.json files.

func (*Registry) Register

func (r *Registry) Register(tool Tool)

Register adds a tool that is available in all modes.

func (*Registry) RegisterWithModes

func (r *Registry) RegisterWithModes(tool Tool, modes ...RuntimeMode)

RegisterWithModes adds a tool that is only available in the specified modes.

func (*Registry) SetAskFunc added in v1.13.0

func (r *Registry) SetAskFunc(fn AskFunc)

SetAskFunc installs the interactive ask callback (TUI-only).

func (*Registry) SetDiscoveryMode added in v1.13.0

func (r *Registry) SetDiscoveryMode(on bool)

SetDiscoveryMode toggles dynamic tool discovery. When off (default), the hidden/activated maps are ignored and every registered tool is offered.

func (*Registry) SetHidden added in v1.13.0

func (r *Registry) SetHidden(name string, hidden bool)

SetHidden marks a tool as hidden-until-activated. Only takes effect while discovery mode is on. find_tools itself must never be hidden.

func (*Registry) SetHookRunner added in v1.8.0

func (r *Registry) SetHookRunner(runner HookRunner)

SetHookRunner sets the hook runner used for pre/post tool hooks. If runner is nil, no hooks are executed (default behavior).

func (*Registry) SetPermissionChecker

func (r *Registry) SetPermissionChecker(checker *permissions.Checker)

SetPermissionChecker sets the permission checker used to gate tool execution. If checker is nil, all tools are allowed (default behavior).

func (*Registry) SetPromptFunc added in v1.10.0

func (r *Registry) SetPromptFunc(fn PromptFunc)

SetPromptFunc configures the interactive permission prompt callback. When the permission checker returns Ask for a tool, the registry calls fn to get the user's decision. fn runs in the tool-execution goroutine (off the Bubble Tea Update loop), so it may safely block. If fn is nil (the default), any Ask decision is treated as Deny — the gate cannot be silently bypassed in headless or non-TUI contexts.

func (*Registry) Unregister added in v1.13.0

func (r *Registry) Unregister(name string)

Unregister removes a tool by name. No-op if the tool is not present.

func (*Registry) UnregisterByPrefix added in v1.13.0

func (r *Registry) UnregisterByPrefix(prefix string) int

UnregisterByPrefix removes every tool whose name starts with prefix and returns the count removed. Used to drop all tools an MCP server contributed.

type RuntimeMode

type RuntimeMode int

RuntimeMode represents the execution mode of the CLI.

const (
	ModeChat RuntimeMode = iota
	ModeClaw
	ModeAgent
	ModeOrchestrator
)

type StreamingToolExecutor

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

StreamingToolExecutor accepts tool calls as they arrive during LLM streaming and dispatches them for execution. Concurrency-safe tools run in parallel goroutines; non-concurrent tools are queued and executed serially. Results are buffered and returned in original call order when Wait() is called.

func NewStreamingToolExecutor

func NewStreamingToolExecutor(registry *Registry) *StreamingToolExecutor

NewStreamingToolExecutor creates a new executor bound to the given registry. The executor uses a background context; cancel it to abort all running tools.

func NewStreamingToolExecutorWithContext

func NewStreamingToolExecutorWithContext(ctx context.Context, registry *Registry) *StreamingToolExecutor

NewStreamingToolExecutorWithContext creates a new executor with a parent context. Cancelling the parent context will abort all running tools.

func (*StreamingToolExecutor) AddTool

func (e *StreamingToolExecutor) AddTool(callID, toolName, inputJSON string)

AddTool submits a tool call for execution. This method is non-blocking. It parses the input JSON, looks up the tool in the registry, determines concurrency safety, and either launches a goroutine or enqueues for serial execution. If the tool is not found, the entry is immediately marked Failed.

inputJSON is the raw JSON arguments string from the LLM.

func (*StreamingToolExecutor) Cancel

func (e *StreamingToolExecutor) Cancel()

Cancel aborts all running and queued tools.

func (*StreamingToolExecutor) Done

func (e *StreamingToolExecutor) Done()

Done signals that no more tool calls will be added. Must be called before Wait() will return.

func (*StreamingToolExecutor) OnProgress

func (e *StreamingToolExecutor) OnProgress(fn func(ProgressEvent))

OnProgress registers a callback for tool progress events. Must be called before AddTool. Not safe to call concurrently with AddTool.

func (*StreamingToolExecutor) SetCascadeOnFailure

func (e *StreamingToolExecutor) SetCascadeOnFailure(enabled bool)

SetCascadeOnFailure enables cascading failure mode. When enabled, if any tool fails, all queued and executing sibling tools are cancelled via context cancellation.

func (*StreamingToolExecutor) States

func (e *StreamingToolExecutor) States() map[string]ToolState

States returns a snapshot of current tool states.

func (*StreamingToolExecutor) Wait

Wait blocks until all tool calls have completed and returns results in the original call order. Callers must call Done() before or concurrently with Wait(), otherwise Wait() will block forever.

type Tool

type Tool interface {
	Name() string
	Description() string
	Parameters() json.RawMessage
	IsConcurrencySafe(input map[string]any) bool
	IsReadOnly() bool
	ValidateInput(input map[string]any) error
	Execute(ctx context.Context, input map[string]any, progress chan<- ProgressEvent) (ToolResult, error)
	InterruptBehavior() InterruptBehavior
}

Tool defines the interface that all tools must implement.

type ToolIndex added in v1.13.0

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

ToolIndex is a BM25 index over tool name+description text.

func BuildToolIndex added in v1.13.0

func BuildToolIndex(ts []Tool) *ToolIndex

BuildToolIndex indexes each tool's name+description for BM25 search.

func (*ToolIndex) Search added in v1.13.0

func (ix *ToolIndex) Search(query string, topN int) []string

Search returns up to topN tool names ranked by BM25 score. Zero-score documents are excluded, so a query with no term overlap returns nothing.

type ToolResult

type ToolResult struct {
	Content  string         `json:"content"`
	Error    bool           `json:"error,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

ToolResult represents the output of a tool execution.

type ToolState

type ToolState int

ToolState represents the lifecycle state of a tool execution.

const (
	// ToolStateQueued means the tool is waiting to be executed.
	ToolStateQueued ToolState = iota
	// ToolStateExecuting means the tool is currently running.
	ToolStateExecuting
	// ToolStateCompleted means the tool finished successfully.
	ToolStateCompleted
	// ToolStateFailed means the tool finished with an error.
	ToolStateFailed
	// ToolStateAborted means the tool was cancelled (cascading failure or interrupt).
	ToolStateAborted
)

func (ToolState) String

func (s ToolState) String() string

String returns a human-readable name for the tool state.

Directories

Path Synopsis
Package builtin provides Alchemy blockchain API handler implementation
Package builtin provides Alchemy blockchain API handler implementation
cmd/celeste/tools/mcp/adapter.go
cmd/celeste/tools/mcp/adapter.go

Jump to

Keyboard shortcuts

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