hooks

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package hooks implements platform event hooks:

  • Observational (async): run_start, run_complete, tool_call, error, interrupt, policy_decision — Sink + Dispatch; never delays run creation (policy_decision is also fired from internal/policy).
  • Pre-flight (sync): before_run — Gate + CheckBeforeRun; can deny a run before thread auto-create, claim, or run row (fail-closed on timeout/error).

Config-driven: webhook sinks and preflight_hooks in langgraph.json. Library embedders can Register / RegisterGate directly on a Dispatcher.

Index

Constants

View Source
const DefaultPreflightTimeout = 2 * time.Second

DefaultPreflightTimeout is used when a webhook gate config omits timeout_ms.

Variables

This section is empty.

Functions

This section is empty.

Types

type DeadLetterStore

type DeadLetterStore interface {
	SaveWebhookDeadLetter(ctx context.Context, dl *models.WebhookDeadLetter) error
}

DeadLetterStore persists deliveries that failed every retry attempt, as part of webhook delivery's retry-and-dead-letter handling. Satisfied by state.Store.

type Decision

type Decision struct {
	Allow  bool   `json:"allow"`
	Reason string `json:"reason,omitempty"`
}

Decision is a Gate's allow/deny answer for one BeforeRun check.

type Dispatcher

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

Dispatcher fans an Event out to every registered Sink whose subscription matches the event's type, via a small bounded worker pool rather than one goroutine per sink per event. The pool exists specifically to bound worst-case resource use: a burst of run completions (e.g. many concurrent runs finishing around the same time), each fanning out to N configured webhook sinks, each of which can itself hold a goroutine open for up to ~30s while retrying with backoff against an unreachable endpoint (WebhookSink.Handle) -- unbounded goroutine-per-dispatch grows without limit under that combination, which is a real resource- exhaustion risk for a production deployment, not a purely theoretical one.

Dispatch itself stays non-blocking either way (preserving the original "hooks never delay run execution" contract): if every worker is busy AND the queue is already full, the job is dropped -- logged and counted in runkite_webhook_queue_dropped_total -- rather than blocking the caller (which would mean a webhook sink slowness starts delaying run completion itself) or growing the queue without bound (reintroducing the exact resource-exhaustion risk this exists to close). This does trade one new, narrower risk for the old unbounded one: because delivery attempts for every sink share this one pool, a genuinely slow or hung endpoint can occupy enough workers to delay (not silently lose -- WebhookSink's own retry+dead-letter path is unaffected once a job IS picked up) another, healthy sink's delivery. A well-sized pool makes this rare in practice; it is not eliminated.

func NewDispatcher

func NewDispatcher(opts ...Option) *Dispatcher

NewDispatcher returns an empty Dispatcher backed by a bounded worker pool (defaultWebhookWorkers workers, defaultWebhookQueueSize queue depth, unless overridden via WithWorkerPool). Dispatching to an empty Dispatcher (or a nil one -- see the nil-receiver methods below) still costs nothing beyond the nil/empty-sinks check; the pool's own workers sit idle blocked on an empty channel until something is registered and dispatched.

func (*Dispatcher) CheckBeforeRun

func (d *Dispatcher) CheckBeforeRun(ctx context.Context, event Event) error

CheckBeforeRun runs every registered Gate against event (Type should be BeforeRun). Returns nil if all allow, or *ErrDenied on the first deny / timeout / gate panic-equivalent failure. Fail-closed: a Gate that returns Allow=false, or whose Decide exceeds ctx, denies.

Safe on a nil Dispatcher (no-op allow). Empty gates = allow.

func (*Dispatcher) Close

func (d *Dispatcher) Close(ctx context.Context) error

Close stops the worker pool for graceful shutdown: closes the job queue (so every worker finishes whatever job it's currently running, then drains whatever was already queued behind it, then exits its range loop) and waits up to ctx's deadline for all of them to actually exit. Without this, the pool's workers previously ran for the whole process lifetime with no shutdown hook at all -- fine for the background loops elsewhere in this codebase that intentionally just die with the process (nothing there is externally-visible, in-flight work), but wrong here: a webhook delivery already queued or in progress when SIGTERM arrives would otherwise be silently abandoned mid-flight instead of getting the same "let it finish or run out of budget" treatment cmd/serve.go's own HTTP/gRPC drain gives every other kind of in-flight work.

Returns ctx.Err() if the deadline is hit before every worker exits -- same "best effort within a bounded budget, not a guarantee" contract as srv.Shutdown/grpcServer.GracefulStop in cmd/serve.go's own shutdown sequence; any delivery attempt still running past that point is abandoned when the process actually exits afterward, exactly as it always was before this existed.

Register/Dispatch must not be called after Close (closing an already-closed or in-use channel panics) -- in practice this is only ever called once, as the very last step of graceful shutdown, by which point nothing dispatches new events anymore. Safe to call on a nil Dispatcher (no-op, matching Dispatch/HasSinks).

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(event Event)

Dispatch fans event out to every subscribed sink. Safe to call on a nil Dispatcher (no-op) so callers never need to nil-check before dispatching.

func (*Dispatcher) HasGates

func (d *Dispatcher) HasGates() bool

HasGates reports whether any pre-flight Gate is registered.

func (*Dispatcher) HasSinks

func (d *Dispatcher) HasSinks() bool

HasSinks reports whether anything is registered at all, so callers doing extra bookkeeping only for hooks (e.g. tailing a run's event stream just to detect tool calls) can skip that work entirely when nothing is listening.

func (*Dispatcher) Register

func (d *Dispatcher) Register(sink Sink, events ...EventType)

Register adds sink, called for every event in events (or every event type at all, if events is empty).

func (*Dispatcher) RegisterGate

func (d *Dispatcher) RegisterGate(gate Gate)

RegisterGate adds a synchronous pre-flight Gate. Safe on a nil Dispatcher (no-op). Gates run in registration order; the first deny (or fail-closed timeout/error) rejects the run.

type ErrDenied

type ErrDenied struct {
	Reason string
}

ErrDenied is returned when a pre-flight Gate rejects a run (or times out / errors under fail-closed policy). Callers map it to HTTP 403.

func (*ErrDenied) Error

func (e *ErrDenied) Error() string

type Event

type Event struct {
	Type      EventType              `json:"type"`
	RunID     string                 `json:"run_id"`
	ThreadID  string                 `json:"thread_id"`
	AgentID   string                 `json:"agent_id"`
	TenantID  string                 `json:"tenant_id,omitempty"`
	Data      map[string]interface{} `json:"data,omitempty"`
	Timestamp time.Time              `json:"timestamp"`
}

Event is what gets dispatched to every registered Sink.

type EventType

type EventType string

EventType identifies which lifecycle moment fired a hook.

const (
	RunStart       EventType = "run_start"
	RunComplete    EventType = "run_complete"
	ToolCall       EventType = "tool_call"
	Error          EventType = "error"
	Interrupt      EventType = "interrupt"
	PolicyDecision EventType = "policy_decision" // async SIEM / observational export
	BudgetAlert    EventType = "budget_alert"    // soft warn / hard deny / soft_pct approach
	BeforeRun      EventType = "before_run"      // sync pre-flight only (Gate), not Dispatch/Sink
)

type Gate

type Gate interface {
	Decide(ctx context.Context, event Event) Decision
}

Gate is a synchronous pre-flight check. Unlike Sink (observational, async, never blocks run creation), Gate.Decide runs inline and can reject the run before any state is mutated.

type Option

type Option func(*dispatcherConfig)

Option configures a Dispatcher at construction time.

func WithWorkerPool

func WithWorkerPool(workers, queueSize int) Option

WithWorkerPool overrides the default worker count and queue depth. Mainly for tests that want to force queue-full behavior deterministically; production callers can use the default via plain NewDispatcher().

type Sink

type Sink interface {
	Handle(ctx context.Context, event Event)
}

Sink receives dispatched events. Implement this to hook into runkite from Go code; WebhookSink is the config-driven, HTTP-delivery implementation this package ships for the common case.

type WebhookConfig

type WebhookConfig struct {
	URL    string
	Secret string // HMAC-SHA256 signing secret; omit to send unsigned
	Events []EventType
}

WebhookConfig configures one webhook subscription.

type WebhookGate

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

WebhookGate POSTs the BeforeRun event JSON to URL and parses {"allow":bool,"reason":string}. Non-2xx, timeout, or malformed body → Allow=false (fail-closed). Same signing header as WebhookSink.

func NewWebhookGate

func NewWebhookGate(cfg WebhookGateConfig) *WebhookGate

NewWebhookGate builds a WebhookGate. Timeout defaults to 2s.

func (*WebhookGate) Decide

func (g *WebhookGate) Decide(ctx context.Context, event Event) Decision

Decide implements Gate.

type WebhookGateConfig

type WebhookGateConfig struct {
	URL     string
	Secret  string        // HMAC-SHA256; omit to send unsigned
	Timeout time.Duration // zero → DefaultPreflightTimeout
}

WebhookGateConfig configures one HTTP pre-flight guardrail endpoint.

type WebhookSink

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

WebhookSink delivers Events as signed HTTP POSTs, with exponential-backoff retry and a persisted dead-letter on exhaustion.

func NewWebhookSink

func NewWebhookSink(cfg WebhookConfig, deadLetter DeadLetterStore) *WebhookSink

func (*WebhookSink) DeliverOnce added in v0.7.0

func (w *WebhookSink) DeliverOnce(ctx context.Context, payload []byte, id string) error

DeliverOnce sends one evidence delivery without in-memory retries. Durable callers own retry/acknowledgement and preserve the same delivery ID.

func (*WebhookSink) Handle

func (w *WebhookSink) Handle(ctx context.Context, event Event)

Handle implements Sink. Runs on its own goroutine per Dispatcher.Dispatch call, so blocking here (across retries with backoff) never delays run execution or other sinks.

Jump to

Keyboard shortcuts

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