toolchain

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AgentNameFromContext = ctxkeys.AgentNameFromContext

AgentNameFromContext delegates to ctxkeys.AgentNameFromContext.

View Source
var WithAgentName = ctxkeys.WithAgentName

WithAgentName delegates to ctxkeys.WithAgentName so that a single canonical context key is used across the entire codebase.

Functions

func BuildApprovalSummary

func BuildApprovalSummary(toolName string, params map[string]interface{}) string

BuildApprovalSummary returns a human-readable description of what a tool invocation will do, suitable for display in approval messages.

func Chain

func Chain(tool *agent.Tool, middlewares ...Middleware) *agent.Tool

Chain applies middlewares to a single tool, returning a new tool with wrapped handler. Middlewares are applied in order: first middleware is outermost (executed first).

func ChainAll

func ChainAll(tools []*agent.Tool, middlewares ...Middleware) []*agent.Tool

ChainAll applies the same middleware stack to all tools.

func DefaultBlockedPatterns added in v0.6.0

func DefaultBlockedPatterns() []string

DefaultBlockedPatterns returns dangerous command patterns that are always blocked regardless of user configuration. These represent catastrophic operations that should never be executed by an AI agent.

func DefaultObservePatterns added in v0.7.0

func DefaultObservePatterns() []string

DefaultObservePatterns returns patterns that are legitimate but common obfuscation vectors. Commands matching these are allowed to execute but are flagged with an Observe action so callers can log or audit them.

func NeedsApproval

func NeedsApproval(t *agent.Tool, ic config.InterceptorConfig) bool

NeedsApproval determines whether a tool requires approval based on the configured policy, explicit exemptions, and sensitive tool lists.

func Truncate

func Truncate(s string, maxLen int) string

Truncate shortens s to maxLen characters, appending "..." if truncated.

Types

type AgentAccessControlHook added in v0.4.0

type AgentAccessControlHook struct {
	// AllowedTools maps agent name → set of allowed tool names.
	// An empty or missing entry means the agent has no restrictions (all tools allowed).
	AllowedTools map[string]map[string]bool

	// DeniedTools maps agent name → set of denied tool names.
	// Deny takes precedence over allow.
	DeniedTools map[string]map[string]bool
}

AgentAccessControlHook enforces per-agent tool ACL. Priority: 20 (runs after security filter but before execution).

func NewAgentAccessControlHook added in v0.4.0

func NewAgentAccessControlHook(allowedTools map[string]map[string]bool) *AgentAccessControlHook

NewAgentAccessControlHook creates an AgentAccessControlHook. Pass nil for allowedTools to start with no restrictions.

func (*AgentAccessControlHook) Name added in v0.4.0

func (h *AgentAccessControlHook) Name() string

Name returns the hook name.

func (*AgentAccessControlHook) Pre added in v0.4.0

Pre checks whether the current agent is allowed to use the tool.

func (*AgentAccessControlHook) Priority added in v0.4.0

func (h *AgentAccessControlHook) Priority() int

Priority returns 20.

type EventBusHook added in v0.4.0

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

EventBusHook publishes tool execution events to the event bus. It implements both PreToolHook and PostToolHook to measure duration. Priority: 50 (runs after security/access checks, observes results).

func NewEventBusHook added in v0.4.0

func NewEventBusHook(bus *eventbus.Bus) *EventBusHook

NewEventBusHook creates a new EventBusHook.

func (*EventBusHook) Name added in v0.4.0

func (h *EventBusHook) Name() string

Name returns the hook name.

func (*EventBusHook) Post added in v0.4.0

func (h *EventBusHook) Post(ctx HookContext, _ interface{}, toolErr error) error

Post publishes a ToolExecutedEvent to the event bus with measured duration.

func (*EventBusHook) Pre added in v0.5.0

Pre records the start time for duration measurement.

func (*EventBusHook) Priority added in v0.4.0

func (h *EventBusHook) Priority() int

Priority returns 50.

type HookContext added in v0.4.0

type HookContext struct {
	ToolName   string
	AgentName  string
	Params     map[string]interface{}
	SessionKey string
	Ctx        context.Context
}

HookContext provides metadata about the current tool execution to hooks.

type HookRegistry added in v0.4.0

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

HookRegistry holds and runs pre/post hooks in priority order.

func NewHookRegistry added in v0.4.0

func NewHookRegistry() *HookRegistry

NewHookRegistry creates a new HookRegistry ready for use.

func (*HookRegistry) PostHooks added in v0.4.0

func (r *HookRegistry) PostHooks() []PostToolHook

PostHooks returns the registered post-hooks (for diagnostics).

func (*HookRegistry) PreHooks added in v0.4.0

func (r *HookRegistry) PreHooks() []PreToolHook

PreHooks returns the registered pre-hooks (for diagnostics).

func (*HookRegistry) RegisterPost added in v0.4.0

func (r *HookRegistry) RegisterPost(hook PostToolHook)

RegisterPost adds a post-tool hook to the registry.

func (*HookRegistry) RegisterPre added in v0.4.0

func (r *HookRegistry) RegisterPre(hook PreToolHook)

RegisterPre adds a pre-tool hook to the registry.

func (*HookRegistry) RunPost added in v0.4.0

func (r *HookRegistry) RunPost(ctx HookContext, result interface{}, toolErr error) error

RunPost runs all post-hooks in priority order. Returns the first error encountered.

func (*HookRegistry) RunPre added in v0.4.0

func (r *HookRegistry) RunPre(ctx HookContext) (PreHookResult, error)

RunPre runs all pre-hooks in priority order. Returns the first Block result immediately. If multiple hooks return Modify, the last one's params win. Observe results are carried forward but do not stop execution — a subsequent Block still takes precedence. Returns Continue with nil params if no hook blocks, modifies, or observes.

type KnowledgeSaveHook added in v0.4.0

type KnowledgeSaveHook struct {

	// SaveableTools is the set of tool names whose results should be saved.
	// If empty, no results are saved (opt-in, not opt-out).
	SaveableTools map[string]bool
	// contains filtered or unexported fields
}

KnowledgeSaveHook auto-saves tool results as knowledge entries. Priority: 100 (runs last — after all other post-hooks).

func NewKnowledgeSaveHook added in v0.4.0

func NewKnowledgeSaveHook(saver KnowledgeSaver, saveableTools []string) *KnowledgeSaveHook

NewKnowledgeSaveHook creates a new KnowledgeSaveHook.

func (*KnowledgeSaveHook) Name added in v0.4.0

func (h *KnowledgeSaveHook) Name() string

Name returns the hook name.

func (*KnowledgeSaveHook) Post added in v0.4.0

func (h *KnowledgeSaveHook) Post(ctx HookContext, result interface{}, toolErr error) error

Post saves the tool result as knowledge if the tool is in the saveable set and the tool succeeded.

func (*KnowledgeSaveHook) Priority added in v0.4.0

func (h *KnowledgeSaveHook) Priority() int

Priority returns 100 (low priority — runs last).

type KnowledgeSaver added in v0.4.0

type KnowledgeSaver interface {
	SaveToolResult(ctx context.Context, sessionKey, toolName string, params map[string]interface{}, result interface{}) error
}

KnowledgeSaver is the interface for saving tool results as knowledge. This avoids a direct import of the knowledge package.

type Middleware

type Middleware func(tool *agent.Tool, next agent.ToolHandler) agent.ToolHandler

Middleware wraps a tool handler. It receives the tool (for metadata access) and the next handler.

func WithApproval

WithApproval returns a middleware that gates tool execution behind an approval flow. Uses fail-closed: denies execution unless explicitly approved. The Provider routes requests to the appropriate channel (Gateway, Telegram, Discord, Slack, TTY). The GrantStore tracks "always allow" grants to auto-approve repeat invocations within a session. When limiter is non-nil, payment tools with an amount below the auto-approve threshold are executed without explicit user confirmation.

func WithBrowserRecovery

func WithBrowserRecovery(sm *browser.SessionManager) Middleware

WithBrowserRecovery returns a middleware that provides panic recovery and auto-reconnect for browser tools. It only applies to tools whose name starts with "browser_"; other tools pass through unchanged.

func WithHooks added in v0.4.0

func WithHooks(registry *HookRegistry) Middleware

WithHooks returns a Middleware that integrates the HookRegistry into the existing middleware chain. Flow: RunPre -> (if Continue/Modify) next(params) -> RunPost.

func WithLearning

func WithLearning(observer learning.ToolResultObserver) Middleware

WithLearning returns a middleware that observes tool results for learning. After each handler execution the observer is called with session key, tool name, parameters, result, and any error.

func WithOutputManager added in v0.6.0

func WithOutputManager(cfg config.OutputManagerConfig, store ...OutputStorer) Middleware

WithOutputManager returns a middleware that manages tool output based on token budgets. It classifies output into tiers (small/medium/large) and applies content-aware compression when output exceeds the configured token budget. An optional OutputStorer stores large outputs for later retrieval via tool_output_get.

func WithPrincipal added in v0.7.0

func WithPrincipal() Middleware

WithPrincipal returns a Middleware that copies the agent name from context into the principal context key. This bridges the ADK agent-name injection (adk/tools.go) with the ontology ACL layer (ontology/service.go).

Injection point: B4c2 in the middleware chain (after WithHooks, before WithApproval). Programmatic callers (SeedDefaults, internal wiring) bypass this middleware, so PrincipalFromContext returns "" for them — treated as "system" by ACL.

func WithTracing added in v0.7.0

func WithTracing(tracer trace.Tracer) Middleware

WithTracing returns a middleware that wraps each tool invocation in an OpenTelemetry span. The span records the tool name, parameter count, and any error. It should be placed as the outermost middleware so that blocked calls (by policy/approval) are also traced.

func WithTruncate added in v0.6.0

func WithTruncate(maxChars int) Middleware

WithTruncate returns a middleware that caps tool result text size. Results exceeding maxChars are truncated with a marker.

type OutputStorer added in v0.6.0

type OutputStorer interface {
	Store(toolName, content string) string
}

OutputStorer is the subset of tooloutput.OutputStore used by the middleware.

type PostToolHook added in v0.4.0

type PostToolHook interface {
	Name() string
	Priority() int // Lower = runs first
	Post(ctx HookContext, result interface{}, toolErr error) error
}

PostToolHook runs after tool execution.

type PreHookAction added in v0.4.0

type PreHookAction int

PreHookAction determines what happens after a pre-hook runs.

const (
	// Continue indicates that tool execution should proceed normally.
	Continue PreHookAction = iota
	// Block indicates that tool execution should be stopped.
	Block
	// Modify indicates that tool execution should proceed with modified params.
	Modify
	// Observe indicates that tool execution should proceed but be logged for review.
	// Commands matching observe-level patterns are legitimate but common obfuscation
	// vectors, so they are allowed with a warning.
	Observe
)

type PreHookResult added in v0.4.0

type PreHookResult struct {
	Action         PreHookAction
	BlockReason    string                 // Used when Action == Block
	ObserveReason  string                 // Used when Action == Observe
	ModifiedParams map[string]interface{} // Used when Action == Modify
}

PreHookResult is returned by pre-hooks to control execution flow.

type PreToolHook added in v0.4.0

type PreToolHook interface {
	Name() string
	Priority() int // Lower = runs first
	Pre(ctx HookContext) (PreHookResult, error)
}

PreToolHook runs before tool execution.

type SecurityFilterHook added in v0.4.0

type SecurityFilterHook struct {
	// BlockedPatterns contains the original-case patterns (for error messages).
	BlockedPatterns []string

	// ObservePatterns contains patterns that trigger observe-level logging.
	// These commands are allowed but flagged as common obfuscation vectors.
	ObservePatterns []string

	// BlockedTools contains tool names that are unconditionally blocked.
	BlockedTools []string
	// contains filtered or unexported fields
}

SecurityFilterHook blocks dangerous command patterns before tool execution. Priority: 10 (runs early to reject bad requests fast).

func NewSecurityFilterHook added in v0.4.0

func NewSecurityFilterHook(blockedPatterns []string) *SecurityFilterHook

NewSecurityFilterHook creates a SecurityFilterHook with default dangerous patterns merged with the given user-configured blocked patterns.

func (*SecurityFilterHook) Name added in v0.4.0

func (h *SecurityFilterHook) Name() string

Name returns the hook name.

func (*SecurityFilterHook) Pre added in v0.4.0

Pre checks whether the tool invocation should be blocked based on tool name blocklist and dangerous command patterns.

func (*SecurityFilterHook) Priority added in v0.4.0

func (h *SecurityFilterHook) Priority() int

Priority returns 10 (high priority — runs early).

type ToolExecutedEvent added in v0.4.0

type ToolExecutedEvent struct {
	ToolName   string
	AgentName  string
	SessionKey string
	Duration   time.Duration
	Success    bool
	Error      string
}

ToolExecutedEvent is published when a tool finishes execution.

func (ToolExecutedEvent) EventName added in v0.4.0

func (e ToolExecutedEvent) EventName() string

EventName implements eventbus.Event.

Jump to

Keyboard shortcuts

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