hooks

package
v0.68.2 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: AGPL-3.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HasToolParent added in v0.66.0

func HasToolParent(ctx context.Context) bool

func RedactSecretValues added in v0.66.0

func RedactSecretValues(s string, values []string) string

RedactToolText masks credential-like substrings before tool data crosses a durable or script-visible boundary. It is best-effort, not a replacement for capability controls. RedactSecretValues removes exact runtime secret values, longest first so a shorter value cannot partially reveal a longer credential. Callers supply a snapshot; this function never retains it.

func RedactToolText added in v0.66.0

func RedactToolText(s string) string

func TelemetryMetaFromContext added in v0.66.0

func TelemetryMetaFromContext(ctx context.Context) (channel, bindingID string)

func WithTelemetryMeta added in v0.66.0

func WithTelemetryMeta(ctx context.Context, channel, bindingID string) context.Context

WithTelemetryMeta carries transport metadata into memory operations without coupling the memory package to the agent runtime.

func WithToolParent added in v0.66.0

func WithToolParent(ctx context.Context) context.Context

WithToolParent marks a context whose current span should parent nested tool calls, used by the Code Mode outer call. Ordinary native tools continue to use the turn span as their parent.

Types

type ChildToolCallAudit added in v0.66.0

type ChildToolCallAudit struct {
	Count        int
	ErrorCount   int
	FailureClass string
}

PostToolCallContext is the typed payload for PostToolCall hooks.

type HookMeta

type HookMeta struct {
	SessionID string
	UserID    string
	AgentID   string
	Channel   string
	BindingID string
}

HookMeta carries shared metadata available to all hook invocations.

type HookPlugin

type HookPlugin interface {
	Name() string
	Priority() int // lower = runs first; ties broken by Name() lexicographic
}

HookPlugin is the unit of registration. A plugin implements this plus one or more of the typed hook interfaces above. The registry type-asserts to discover which hook points a plugin supports.

type HookPoint

type HookPoint string

HookPoint identifies where in the engine loop a hook fires.

const (
	PreAgentCall   HookPoint = "pre_agent_call"
	PostAgentCall  HookPoint = "post_agent_call"
	PreToolCall    HookPoint = "pre_tool_call"
	PostToolCall   HookPoint = "post_tool_call"
	PreLLMCall     HookPoint = "pre_llm_call"
	PostLLMCall    HookPoint = "post_llm_call"
	PreMemoryCall  HookPoint = "pre_memory_call"
	PostMemoryCall HookPoint = "post_memory_call"
)

type HookSet

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

HookSet holds pre-sorted hook slices for each hook point. It is immutable after construction and safe for concurrent use.

func NewHookSet

func NewHookSet(plugins []HookPlugin) *HookSet

NewHookSet builds a HookSet from a slice of HookPlugins. Plugins are sorted by Priority (ascending), then Name (lexicographic). Each plugin is type-asserted into the hook point slices it implements.

func (*HookSet) Empty

func (hs *HookSet) Empty() bool

Empty reports whether the HookSet has no hooks at any point.

func (*HookSet) RunPostAgentCall

func (hs *HookSet) RunPostAgentCall(ctx context.Context, hctx *PostAgentCallContext)

RunPostAgentCall executes all PostAgentCall hooks in priority order. All hooks always run; errors are logged but never short-circuit.

func (*HookSet) RunPostLLMCall

func (hs *HookSet) RunPostLLMCall(ctx context.Context, hctx *PostLLMCallContext)

RunPostLLMCall executes all PostLLMCall hooks in priority order. All hooks always run; errors are logged but never short-circuit.

func (*HookSet) RunPostMemoryCall

func (hs *HookSet) RunPostMemoryCall(ctx context.Context, hctx *PostMemoryCallContext)

RunPostMemoryCall executes all PostMemoryCall hooks in priority order. All hooks always run; errors are logged but never short-circuit.

func (*HookSet) RunPostToolCall

func (hs *HookSet) RunPostToolCall(ctx context.Context, hctx *PostToolCallContext)

RunPostToolCall executes all PostToolCall hooks in priority order. All hooks always run; errors are logged but never short-circuit.

func (*HookSet) RunPreAgentCall

func (hs *HookSet) RunPreAgentCall(ctx context.Context, hctx *PreAgentCallContext)

RunPreAgentCall executes all PreAgentCall hooks in priority order. All hooks always run; errors are logged but never short-circuit.

func (*HookSet) RunPreLLMCall

func (hs *HookSet) RunPreLLMCall(ctx context.Context, hctx *PreLLMCallContext) PreLLMCallResult

RunPreLLMCall executes all PreLLMCall hooks in priority order. Mutations from each hook are applied before the next hook runs.

Error policy: same as RunPreToolCall — log and skip.

func (*HookSet) RunPreMemoryCall added in v0.41.0

func (hs *HookSet) RunPreMemoryCall(ctx context.Context, hctx *PreMemoryCallContext) PreMemoryCallResult

RunPreMemoryCall executes all PreMemoryCall hooks in priority order. Mutations from each hook are applied before the next hook runs.

Error policy: same as RunPreToolCall — log and skip.

func (*HookSet) RunPreToolCall

func (hs *HookSet) RunPreToolCall(ctx context.Context, hctx *PreToolCallContext) PreToolCallResult

RunPreToolCall executes all PreToolCall hooks in priority order. If any hook sets Block=true, the chain short-circuits. Rewritten Arguments are passed to subsequent hooks.

Error policy: a failing hook is logged and skipped so that non-critical hooks never block tool execution. Security-critical checks must live in the core engine, not in disableable hook plugins.

type MemoryOp

type MemoryOp string

MemoryOp identifies the memory operation being traced.

const (
	MemoryOpBootstrap                  MemoryOp = "bootstrap"
	MemoryOpAppend                     MemoryOp = "append"
	MemoryOpAssemble                   MemoryOp = "assemble"
	MemoryOpStats                      MemoryOp = "stats"
	MemoryOpNeedsCompaction            MemoryOp = "needs_compaction"
	MemoryOpCompact                    MemoryOp = "compact"
	MemoryOpSearch                     MemoryOp = "search"
	MemoryOpDescribe                   MemoryOp = "describe"
	MemoryOpExpand                     MemoryOp = "expand"
	MemoryOpGetMessage                 MemoryOp = "get_message"
	MemoryOpGetProfile                 MemoryOp = "get_profile"
	MemoryOpGetProfileAt               MemoryOp = "get_profile_at"
	MemoryOpSetProfile                 MemoryOp = "set_profile"
	MemoryOpGetAgentSoul               MemoryOp = "get_agent_soul"
	MemoryOpGetAgentSoulAt             MemoryOp = "get_agent_soul_at"
	MemoryOpSetAgentSoul               MemoryOp = "set_agent_soul"
	MemoryOpSaveInfo                   MemoryOp = "save_info"
	MemoryOpArchiveInfo                MemoryOp = "archive_info"
	MemoryOpRotateInfo                 MemoryOp = "rotate_info"
	MemoryOpTouchActiveInfo            MemoryOp = "touch_active_info"
	MemoryOpLoadInfo                   MemoryOp = "load_info"
	MemoryOpListInfo                   MemoryOp = "list_info"
	MemoryOpListInfoForReview          MemoryOp = "list_info_for_review"
	MemoryOpLoadHistory                MemoryOp = "load_history"
	MemoryOpLoadReviewHistory          MemoryOp = "load_review_history"
	MemoryOpGetOrCreateSessionSnapshot MemoryOp = "get_or_create_session_snapshot"
	MemoryOpAdvanceSessionSnapshot     MemoryOp = "advance_session_snapshot"
	MemoryOpBuildReview                MemoryOp = "build_review"
)

type PostAgentCallContext

type PostAgentCallContext struct {
	HookMeta
	Duration time.Duration
	Error    error
}

PostAgentCallContext is the typed payload for PostAgentCall hooks. Fired when the chat stream completes (all events consumed and persisted).

type PostAgentCallHook

type PostAgentCallHook interface {
	Name() string
	Priority() int
	OnPostAgentCall(ctx context.Context, hctx *PostAgentCallContext)
}

PostAgentCallHook observes the completion of a chat request.

type PostLLMCallContext

type PostLLMCallContext struct {
	HookMeta
	CallID            string
	Model             string
	ProviderToolNames []string
	CodeCatalogSize   int
	Provider          string // provider display name (may be empty)
	API               string // provider API key (e.g. "anthropic", "openai")
	BaseURL           string // provider endpoint URL
	Usage             ai.Usage
	StopReason        ai.StopReason
	Duration          time.Duration
	TimeToFirstToken  time.Duration // zero if no streaming or first token not observed
	// Attempts is the number of provider HTTP requests this call took,
	// including SDK-internal retries. 1 means no retry; 0 means nothing
	// counted them (a stream that never went over HTTP, e.g. a test fake).
	Attempts      int
	ToolCallCount int
	Error         error
}

PostLLMCallContext is the typed payload for PostLLMCall hooks.

type PostLLMCallHook

type PostLLMCallHook interface {
	Name() string
	Priority() int
	OnPostLLMCall(ctx context.Context, hctx *PostLLMCallContext)
}

PostLLMCallHook observes LLM call results (telemetry, cost tracking).

type PostMemoryCallContext

type PostMemoryCallContext struct {
	HookMeta
	Op        MemoryOp
	SessionID string // memory session ID
	Duration  time.Duration
	Error     error
	// Operation-specific fields (zero values for irrelevant ops).
	MessageCount int // Append: number of messages; Assemble: returned count
	TokenCount   int // Assemble: total tokens; Stats: total tokens; Compact: tokens after
	TokenDelta   int // Compact: tokens saved (negative = reduction)
	SummaryCount int // Compact: summaries created; Stats: total summaries
	ResultCount  int // Search: number of results
	// Detail contains a human-readable dump of the operation's content.
	// Only populated when verbose tracing is enabled. Empty in normal mode.
	// Append: message roles/previews. Assemble: returned messages.
	// Search: query + results. Profile: content. Compact: result breakdown.
	Detail string
}

PostMemoryCallContext is the typed payload for PostMemoryCall hooks.

type PostMemoryCallHook

type PostMemoryCallHook interface {
	Name() string
	Priority() int
	OnPostMemoryCall(ctx context.Context, hctx *PostMemoryCallContext)
}

PostMemoryCallHook observes memory operations after execution.

type PostToolCallContext

type PostToolCallContext struct {
	HookMeta
	ToolName           string
	ToolCallID         string
	Arguments          map[string]any
	Result             string
	IsError            bool
	ChildToolCallAudit ChildToolCallAudit
	// ErrorKind classifies IsError (#1077): the tool itself failed
	// ("tool_error"), exited nonzero ("command_nonzero"), or hit its explicit
	// command timeout ("command_timeout").
	// Empty means unclassified — never assume a kind from IsError alone.
	ErrorKind ai.ToolErrorKind
	// ExitCode is the command's status when ErrorKind is command_nonzero or
	// command_timeout (-1), nil
	// otherwise. A pointer because 0 is a real exit code and must not double
	// as "unknown".
	ExitCode *int
	Duration time.Duration
}

type PostToolCallHook

type PostToolCallHook interface {
	Name() string
	Priority() int
	OnPostToolCall(ctx context.Context, hctx *PostToolCallContext)
}

PostToolCallHook observes tool call results after execution.

type PreAgentCallContext

type PreAgentCallContext struct {
	HookMeta
	MessageLen int    // length of the user message text
	Channel    string // channel the chat originated from (e.g. "cli", "telegram")
}

PreAgentCallContext is the typed payload for PreAgentCall hooks. Fired when a chat request enters the agent pool, before any memory or LLM work.

type PreAgentCallHook

type PreAgentCallHook interface {
	Name() string
	Priority() int
	OnPreAgentCall(ctx context.Context, hctx *PreAgentCallContext)
}

PreAgentCallHook observes the start of a chat request.

type PreLLMCallContext

type PreLLMCallContext struct {
	HookMeta
	CallID          string
	Model           string
	System          string
	ToolDefinitions []ai.ToolDefinition
	MessageCount    int // number of messages (avoid copying full history)

	// Model/request metadata for tracing.
	API         string   // provider API key (e.g. "anthropic", "openai")
	Provider    string   // provider display name
	BaseURL     string   // provider endpoint URL
	MaxTokens   *int     // nil = not set
	Temperature *float64 // nil = not set
}

PreLLMCallContext is the typed payload for PreLLMCall hooks.

type PreLLMCallHook

type PreLLMCallHook interface {
	Name() string
	Priority() int
	OnPreLLMCall(ctx context.Context, hctx *PreLLMCallContext) (PreLLMCallResult, error)
}

PreLLMCallHook intercepts LLM calls before they are sent.

type PreLLMCallResult

type PreLLMCallResult struct {
	System          *string             // non-nil = override system prompt
	ToolDefinitions []ai.ToolDefinition // non-nil = override tool definitions
	Model           *string             // non-nil = override model name
	Context         context.Context     // non-nil = enriched context for provider call (e.g. with trace span)
}

PreLLMCallResult carries mutations from a PreLLMCall hook.

type PreMemoryCallContext added in v0.41.0

type PreMemoryCallContext struct {
	HookMeta
	Op        MemoryOp
	SessionID string // memory session ID, empty for global/user memory ops
}

PreMemoryCallContext is the typed payload for PreMemoryCall hooks. Fired before the memory provider touches storage so hooks can enrich ctx; DB spans created inside the operation then nest under the memory span.

type PreMemoryCallHook added in v0.41.0

type PreMemoryCallHook interface {
	Name() string
	Priority() int
	OnPreMemoryCall(ctx context.Context, hctx *PreMemoryCallContext) (PreMemoryCallResult, error)
}

PreMemoryCallHook intercepts memory operations before storage access.

type PreMemoryCallResult added in v0.41.0

type PreMemoryCallResult struct {
	Context context.Context // non-nil = enriched context for the memory operation
}

PreMemoryCallResult carries mutations from a PreMemoryCall hook.

type PreToolCallContext

type PreToolCallContext struct {
	HookMeta
	ToolName   string
	ToolCallID string
	Arguments  map[string]any // read by hook; rewrite via result
}

PreToolCallContext is the typed payload for PreToolCall hooks.

type PreToolCallHook

type PreToolCallHook interface {
	Name() string
	Priority() int
	OnPreToolCall(ctx context.Context, hctx *PreToolCallContext) (PreToolCallResult, error)
}

PreToolCallHook intercepts tool calls before execution.

type PreToolCallResult

type PreToolCallResult struct {
	Arguments    map[string]any  // non-nil = rewritten args for next hook / execution
	Block        bool            // true = skip tool execution
	BlockMessage string          // synthetic result text when blocked
	Context      context.Context // non-nil = enriched context for tool execution (e.g. with trace span)
}

PreToolCallResult tells the engine what to do after a PreToolCall hook.

Jump to

Keyboard shortcuts

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