callhandler

package
v1.162.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package callhandler is what the three tool-call handler kinds share (#2436, #2634, #2635): a policy decides whether a tool call runs, a transform changes what it returns, and a watch runs a script after it. Each is a managed script bound by an administrator to a match the platform checks, never script: a connection, operations, who the handler applies to, and optional equalities on the call's arguments.

A replica keeps every enabled handler in memory (Index) and answers a call no handler matches from that alone: no database read and no script.

Index

Constants

View Source
const (
	KindPolicy    = "policy"
	KindTransform = "transform"
	KindWatch     = "watch"
)

The kinds of tool-call handler.

View Source
const (
	// FailHold holds a policy's call for an administrator's approval.
	FailHold = "hold"
	// FailDeny refuses a policy's call.
	FailDeny = "deny"
	// FailCall fails a transform's call, naming the handler.
	FailCall = "fail"
	// FailOriginal returns the result the transform was given.
	FailOriginal = "original"
)

What a handler does when its script fails or runs out of time.

View Source
const (
	InPath  = "path"
	InBody  = "body"
	InQuery = "query"
)

Where a condition reads its value.

View Source
const (
	DefaultTimeoutMS = 2000
	MaxTimeoutMS     = 60000
)

Bounds a handler is held to.

View Source
const (
	// DecideName is a policy's: decide(call) returns platform.allow(),
	// platform.deny(reason) or platform.require_approval(approvers, summary).
	DecideName = "decide"
	// TransformName is a transform's: transform(call, result) returns the
	// result the caller gets.
	TransformName = "transform"
	// WatchEntry is a watch's: main(), reading the call from run.call.
	WatchEntry = "main"
)

The functions each kind's script defines.

View Source
const Channel = "call_handlers"

Channel is the NOTIFY channel migration 000248's trigger announces a changed handler on.

View Source
const DefaultMaxAge = 10 * time.Second

DefaultMaxAge is the longest the Index answers from one read with no change heard: a NOTIFY sent while a replica's LISTEN connection was down is lost, and this bounds how long it can miss a changed handler.

View Source
const FailureRetention = 7 * 24 * time.Hour

FailureRetention is how long a failure is kept.

View Source
const MaxWindow = 31 * 24 * time.Hour

MaxWindow is the longest window a count reaches back over; counts older than it are swept.

Variables

View Source
var ErrInvalid = errors.New("invalid call handler")

ErrInvalid is a handler that names something wrongly.

View Source
var ErrNotFound = errors.New("no such call handler")

ErrNotFound is a handler that does not exist.

Functions

func CheckPolicy

func CheckPolicy(source string) error

CheckPolicy refuses a source a policy could not run.

func CheckTransform

func CheckTransform(source string) error

CheckTransform refuses a source a transform could not run.

func CheckWatch

func CheckWatch(source string) error

CheckWatch refuses a source a watch could not run.

func ConnectionMatches

func ConnectionMatches(pattern, name string) bool

ConnectionMatches reports whether a handler's connection pattern applies to the named connection.

func Contract

func Contract(kind string) string

Contract is the functions a script defines to hold a handler of kind, as a refusal names them.

func IsKind

func IsKind(name string) bool

IsKind reports whether name is a tool-call handler kind.

func ItemCount

func ItemCount(body any, itemsPath string) int

ItemCount is how many items a call carries: the length of the array at itemsPath in its body, or one.

func Lookup

func Lookup(v any, dotted string) any

Lookup reads a dotted path out of a decoded JSON value, nil when any step is missing.

func Within

func Within(ctx context.Context) bool

Within reports whether ctx is a tool-call handler's own run.

func WithinHandler

func WithinHandler(ctx context.Context) context.Context

WithinHandler marks ctx as a tool-call handler's own run: the calls its script makes are not evaluated by tool-call handlers, which is what keeps a policy's read from being decided by a policy, and a handler from deciding its own calls.

Types

type Call

type Call struct {
	Tool       string            `json:"tool"`
	Connection string            `json:"connection"`
	Operation  string            `json:"operation"`
	Method     string            `json:"method"`
	Path       string            `json:"path"`
	PathParams map[string]string `json:"path_params"`
	Query      map[string]any    `json:"query"`
	// Arguments are the call's arguments as the caller sent them, before
	// any stored secret is filled.
	Arguments map[string]any `json:"arguments"`
	// Body is the call's body, a string of JSON read as the value it holds.
	Body  any    `json:"body"`
	Items int    `json:"items"`
	Write bool   `json:"write"`
	User  string `json:"user"`
	// Persona is the persona the caller's call was authorized under.
	Persona string    `json:"persona"`
	Time    time.Time `json:"time"`
	// SQL is a SQL tool's statement; Tables are the tables it names.
	SQL string `json:"sql,omitempty"`
}

Call is what the platform knows of one tool call before it runs: what a handler is matched against, and what a script is given.

type Condition

type Condition struct {
	In     string `json:"in"`
	Name   string `json:"name"`
	Equals string `json:"equals"`
}

Condition is one equality a call's argument must meet for the handler to apply: the path parameter, body field (dotted) or query parameter Name equal to Equals.

type Failure

type Failure struct {
	ID         string         `json:"id"`
	HandlerID  string         `json:"handler_id"`
	Version    int            `json:"version"`
	User       string         `json:"user"`
	Call       map[string]any `json:"call"`
	Prints     string         `json:"prints"`
	Error      string         `json:"error"`
	Outcome    string         `json:"outcome"`
	DurationMS int            `json:"duration_ms"`
	At         time.Time      `json:"at"`
}

Failure is what a policy or transform was given and printed when it failed.

type Handler

type Handler struct {
	ID       string `json:"id"`
	ScriptID string `json:"script_id"`
	Kind     string `json:"kind"`
	// Connection is a connection name or a pattern matching names.
	Connection string `json:"connection"`
	// Operations are operation ids, tool names or "METHOD path" patterns;
	// none is every call on the connection.
	Operations []string `json:"operations"`
	// Personas and Users are who it applies to; both empty is everyone.
	Personas   []string        `json:"personas"`
	Users      []string        `json:"users"`
	Conditions []Condition     `json:"conditions"`
	Args       map[string]any  `json:"args"`
	TimeoutMS  int             `json:"timeout_ms"`
	OnFailure  string          `json:"on_failure"`
	ItemsPath  string          `json:"items_path"`
	Writes     map[string]bool `json:"writes"`
	Protected  []string        `json:"protected"`
	Order      int             `json:"order"`
	Enabled    bool            `json:"enabled"`
	CreatedBy  string          `json:"created_by"`
	UpdatedBy  string          `json:"updated_by"`
	CreatedAt  time.Time       `json:"created_at"`
	UpdatedAt  time.Time       `json:"updated_at"`
}

Handler is one tool-call handler.

func (*Handler) IsWrite

func (h *Handler) IsWrite(c *Call) bool

IsWrite reports whether c writes, by its method or the handler's override for its operation.

func (*Handler) Matches

func (h *Handler) Matches(c *Call) bool

Matches reports whether h applies to c. It is the whole of what a call no handler applies to pays.

func (*Handler) Normalize

func (h *Handler) Normalize()

Normalize trims h's fields and fills its defaults for its kind.

func (*Handler) Validate

func (h *Handler) Validate() error

Validate refuses a handler its kind could not run, naming what is wrong.

type Index

type Index struct {
	Reader Reader
	MaxAge time.Duration
	// contains filtered or unexported fields
}

Index is every enabled handler, kept in memory so a call no handler matches costs the match and nothing else. It never makes a call wait for a read once it has one: a stale snapshot answers while a fresh one is read in the background, after a change is heard (Notify) or the snapshot ages past MaxAge.

func (*Index) Any

func (x *Index) Any(connection string) bool

Any reports whether any enabled handler could apply to a call on connection, whatever its operation and caller: the first, cheapest check.

func (*Index) Load

func (x *Index) Load(ctx context.Context) error

Load reads the handlers once, before the first call, so a replica that just started does not answer its first calls as if there were none.

func (*Index) Match

func (x *Index) Match(c *Call, kind string) []Handler

Match is every enabled handler of kind that applies to c, in the order they run. A call nothing applies to gets nil.

func (*Index) Notify

func (x *Index) Notify()

Notify marks the snapshot stale: the next lookup reads it again in the background. It is the pglisten.Notifier a LISTEN on Channel wakes.

func (*Index) On

func (x *Index) On(connection string) []Handler

On is every enabled handler on connection, whatever it matches: what the test panel names as not applying to a call it does not match.

type Patch

type Patch struct {
	Connection *string
	Operations *[]string
	Personas   *[]string
	Users      *[]string
	Conditions *[]Condition
	Args       map[string]any
	TimeoutMS  *int
	OnFailure  *string
	ItemsPath  *string
	Writes     *map[string]bool
	Protected  *[]string
	Order      *int
}

Patch is a change to a handler's match and settings: a nil field is left as it is, so handler_set naming a handler changes only what it sends.

func (Patch) Apply

func (p Patch) Apply(h *Handler)

Apply writes p's fields onto h.

type Reader

type Reader interface {
	Enabled(ctx context.Context) ([]Handler, error)
}

Reader reads every enabled handler (Store).

type Stat

type Stat struct {
	Matched int     `json:"matched"`
	Denied  int     `json:"denied"`
	Held    int     `json:"held"`
	Errors  int     `json:"errors"`
	Queued  int     `json:"queued"`
	P50MS   float64 `json:"p50_ms"`
	P99MS   float64 `json:"p99_ms"`
}

Stat is one handler's last day on its calls, read from the audit rows of the calls it matched.

type Statement

type Statement struct {
	User, Persona, Connection, Tool, SQL string
}

Statement is a script's application database statement as the handlers are asked about it: who runs it, under which persona, on which connection, through which binding, and its SQL.

type Store

type Store struct {
	DB *sql.DB
}

Store keeps handlers, their counts and their failures in PostgreSQL.

func NewStore

func NewStore(db *sql.DB) *Store

NewStore is the store over db, nil without one.

func (*Store) All

func (s *Store) All(ctx context.Context) ([]Handler, error)

All is every handler, enabled or not.

func (*Store) ByScript

func (s *Store) ByScript(ctx context.Context, scriptID string) ([]Handler, error)

ByScript is every handler a script holds.

func (*Store) Count

func (s *Store) Count(ctx context.Context, t Tally) (int, error)

Count adds the tally's amount for its call under the handler's key and returns the total over the window, this call included. The read and the write are one transaction under a lock on the key, so two replicas counting one key count one after the other.

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, id string) error

Delete removes a handler, its counts and its failures.

func (*Store) Enabled

func (s *Store) Enabled(ctx context.Context) ([]Handler, error)

Enabled is every enabled handler: what an Index holds.

func (*Store) Failures

func (s *Store) Failures(ctx context.Context, handlerID string, limit int) ([]Failure, error)

Failures is a handler's newest failures, at most limit.

func (*Store) Get

func (s *Store) Get(ctx context.Context, id string) (*Handler, error)

Get is one handler.

func (*Store) Insert

func (s *Store) Insert(ctx context.Context, h *Handler) error

Insert writes a new handler, filling its id and times.

func (*Store) RecordFailure

func (s *Store) RecordFailure(ctx context.Context, f Failure) error

RecordFailure keeps one failure.

func (*Store) Release

func (s *Store) Release(ctx context.Context, callID string) error

Release removes what callID counted: a call the handlers did not let run is not counted against anyone.

func (*Store) SetEnabled

func (s *Store) SetEnabled(ctx context.Context, id string, enabled bool, by string) error

SetEnabled turns a handler on or off.

func (*Store) SetOrder

func (s *Store) SetOrder(ctx context.Context, ids []string, by string) error

SetOrder sets the order transforms run in: each id's place in ids.

func (*Store) Stats

func (s *Store) Stats(ctx context.Context, connection string) (map[string]Stat, error)

Stats is every handler's last day on a connection's calls, by handler id.

func (*Store) Sweep

func (s *Store) Sweep(ctx context.Context, now time.Time) error

Sweep removes counts older than MaxWindow and failures older than FailureRetention, as of now.

func (*Store) Update

func (s *Store) Update(ctx context.Context, h *Handler) error

Update writes a handler's match and settings; its kind, script and state are not changed here.

type Tally

type Tally struct {
	HandlerID, Key, CallID string
	Amount                 int
	Window                 time.Duration
}

Tally is one count a policy makes: amount for CallID under the handler's Key, totalled over Window.

type TestRequest

type TestRequest struct {
	Connection string
	Tool       string
	Arguments  map[string]any
	// User or Persona is who would call.
	User    string
	Persona string
	// At is when, in RFC 3339; empty is now.
	At string
	// Result is a result for transforms to change.
	Result any
}

TestRequest is a call the test panel asks about: what every handler on a connection would make of it, without the upstream being called or any counter or allowance spent.

Jump to

Keyboard shortcuts

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