operations

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0, MIT Imports: 20 Imported by: 0

Documentation

Overview

Package operations is the catalog of WeKnora HTTP API operations an agent may run on behalf of the signed-in user.

The catalog is the allow-list: nothing outside it is reachable. Entries are declared with x-agent annotations on the handlers and compiled from the Swagger document (see FromSpec). An operation names a registered route, its risk, the parameters the model may supply and the slice of the response the model gets back. Execution goes through the real router (see Dispatcher), so authentication, RBAC guards, KB sharing and audit behave exactly as they do for the web UI; the catalog only narrows what is reachable.

Index

Constants

View Source
const (
	RiskRead        = policy.RiskRead
	RiskProbe       = policy.RiskProbe
	RiskWrite       = policy.RiskWrite
	RiskDestructive = policy.RiskDestructive
)

A probe operation runs without approval within a per-run budget, and uses POST because the API does.

View Source
const MaxApprovalItems = 20

MaxApprovalItems bounds a batch whose items the approval resolves, so the user sees every item they approve.

Variables

View Source
var ErrDispatcherUnavailable = errors.New("operation dispatcher is not available")

ErrDispatcherUnavailable means the router has not been bound yet.

View Source
var ErrResponseTooLarge = errors.New("operation response is too large")

ErrResponseTooLarge means the handler wrote more than the capture limit.

Functions

func SelectParams

func SelectParams(op Operation, params map[string]json.RawMessage) map[string]json.RawMessage

SelectParams keeps the parameters op accepts.

Types

type Access

type Access struct {
	// Role is the caller's workspace role. It filters only when EnforceRole
	// is set, matching the router, which skips role checks otherwise.
	Role        types.TenantRole
	EnforceRole bool
	SystemAdmin bool
	// Level is the user's assistant access level.
	Level types.AssistantAccessLevel
}

Access is what one run may do with the catalog.

func (Access) NeedsApproval

func (a Access) NeedsApproval(op Operation) bool

NeedsApproval reports whether running op must wait for the user. An operation the level denies is withheld before it gets here.

func (Access) Rules

func (a Access) Rules() policy.Rules

Rules are the execution rules this access gives a run.

type Call

type Call struct {
	Method string
	// Path is escaped and ready to use as a request URI path.
	Path  string
	Query url.Values
	// Body is a JSON object, or nil when the operation has no body params.
	Body []byte
}

Call is a fully validated HTTP request for one operation.

func (Call) URI

func (c Call) URI() string

URI is Path plus the encoded query.

type Catalog

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

Catalog is an immutable, validated set of operations.

func Builtin

func Builtin() *Catalog

Builtin returns the catalog compiled from the Swagger document embedded in the binary: every operation annotated with x-agent. It panics on an invalid declaration, which tests catch before release.

func NewCatalog

func NewCatalog(ops ...Operation) (*Catalog, error)

NewCatalog validates ops and returns a catalog sorted by ID.

func (*Catalog) All

func (c *Catalog) All() []Operation

All returns every operation, sorted by ID.

func (*Catalog) Domains

func (c *Catalog) Domains() []string

Domains lists the distinct operation domains.

func (*Catalog) Find

func (c *Catalog) Find(query, domain string) []Operation

Find returns operations matching every whitespace-separated term of query (case-insensitive, against ID, summary and description), optionally limited to one domain. An empty query matches everything.

func (*Catalog) For

func (c *Catalog) For(a Access) *Catalog

For returns the operations a allows; see Withheld.

func (*Catalog) Get

func (c *Catalog) Get(id string) (Operation, bool)

Get returns the operation with id.

func (*Catalog) Withheld

func (c *Catalog) Withheld(a Access, op Operation) (Withholding, bool)

Withheld reports why a leaves op out of c, if it does. A mutation whose approval target is withheld is withheld for the same reason, so every offered mutation can still show the user what it acts on.

type Dispatcher

type Dispatcher interface {
	Dispatch(ctx context.Context, identity Identity, call Call) (*Response, error)
}

Dispatcher executes a built call as identity.

type Field

type Field struct {
	// From is a dotted path inside the source object.
	From string
	// MapKey selects one literal key within From, including keys containing dots.
	// Used for explicitly allow-listed keys of free-form maps.
	MapKey string
	// As is the output key; defaults to the last segment of From. Identifiers
	// should be renamed to the canonical handle keys so the model-context
	// policy turns them into handles.
	As string
	// MaxRunes overrides the projected string length for this field. Zero
	// keeps maxProjectedStringRunes.
	MaxRunes int
	// Items projects each element of a list of objects. Element fields are
	// relative to the element and cannot declare Items themselves.
	Items []Field
}

Field copies one value from the response into the model-visible result.

type HandlerDispatcher

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

HandlerDispatcher sends calls through an http.Handler, normally the gin engine. The engine is built after the services that hold this dispatcher, so it is bound late.

func NewHandlerDispatcher

func NewHandlerDispatcher() *HandlerDispatcher

NewHandlerDispatcher returns a dispatcher that fails until Bind is called.

func (*HandlerDispatcher) Bind

func (d *HandlerDispatcher) Bind(h http.Handler)

Bind sets the handler calls are dispatched to.

func (*HandlerDispatcher) Dispatch

func (d *HandlerDispatcher) Dispatch(ctx context.Context, identity Identity, call Call) (*Response, error)

Dispatch serves call through the bound handler as identity, detached from ctx's values but cancelled with it.

type Identity

type Identity struct {
	UserID   string
	TenantID uint64
	Language string
	Agent    types.AuditAgentAction
}

Identity is who an operation runs as. Only a signed-in web user can be dispatched: API-key, embed and IM principals carry narrower grants than the user record behind them, and replaying a call as that user would widen them.

type ItemTarget

type ItemTarget struct {
	// Param is the mutation's list parameter; at most MaxApprovalItems long.
	Param     string
	Operation string
	// As is the target parameter that receives each item.
	As    string
	Label string
}

ItemTarget runs a read once per item of a list parameter, so the approval names each item rather than showing IDs.

type Location

type Location string

Location is where a parameter goes in the HTTP request.

const (
	InPath  Location = "path"
	InQuery Location = "query"
	InBody  Location = "body"
)

Parameter locations.

type Operation

type Operation struct {
	// ID is the stable model-facing name, "<domain>.<verb>".
	ID          string
	Summary     string
	Description string
	Risk        Risk
	Method      string
	// Route is the full path as registered on the router, with :param and
	// *param segments.
	Route  string
	Params []Param
	Result Result
	// Target, for mutating operations, is a read operation that resolves
	// what the call acts on. It runs first, through the same authorization,
	// and its result labels the approval prompt. Its parameters must be a
	// subset of this operation's.
	Target *Target
	// LabelParam, for a creation with nothing existing to act on, names the
	// required string parameter (the new name) that labels the approval in
	// place of a Target.
	LabelParam string
	// Role is the lowest workspace role the route's guards let through;
	// empty takes the default for Risk. It only decides what a caller is
	// offered: the router still authorizes every call, and a router test
	// keeps the two in step.
	Role types.TenantRole
	// SystemAdmin requires the independent platform administrator permission.
	SystemAdmin bool
	// AlwaysConfirm makes a write ask every time, whatever the access level
	// and session grants: installing a skill runs fetched code as root in
	// the image every later session boots, so it is never pre-approved.
	AlwaysConfirm bool
}

Operation is one catalog entry.

func FromSpec

func FromSpec(document []byte) ([]Operation, error)

FromSpec compiles the operations a Swagger 2.0 document marks with x-agent. The result still has to pass NewCatalog, which owns the safety rules (allowed API areas, risk versus method, approval targets).

func (Operation) Build

func (op Operation) Build(params map[string]json.RawMessage) (Call, error)

Build validates params against the operation and assembles the request. Unknown parameters are rejected rather than ignored, so a model that guessed a name learns about it instead of silently getting other behavior.

func (Operation) Domain

func (op Operation) Domain() string

Domain is the part of the ID before the dot.

func (Operation) Param

func (op Operation) Param(name string) (Param, bool)

Param returns the parameter declared under name.

func (Operation) Project

func (op Operation) Project(body []byte) (Projected, error)

Project extracts the declared fields from a JSON response body.

type Param

type Param struct {
	Name string
	In   Location
	// Key is the wire name: the route segment, query key or body field.
	// Defaults to Name.
	Key      string
	Type     ParamType
	Required bool
	// AllowEmpty separates an agent-required field from an API nonempty constraint.
	AllowEmpty  bool
	Description string
	Enum        []string
	// Minimum and Maximum bound integers when Maximum > 0.
	Minimum int
	Maximum int
	// MaxItems bounds lists; defaults to defaultMaxListItems.
	MaxItems int
	// MaxBytes overrides maxStringParamBytes for this string. Zero keeps the
	// default. It cannot exceed maxAgentStringBytes.
	MaxBytes int
}

Param is one model-facing parameter.

Names are chosen for the model, not copied from the route: identifiers use the canonical keys (knowledge_base_id, knowledge_id, issue_id, ...) that the model-context handle policy recognizes, so handles the model saw elsewhere (b1, d3, i2) decode to real IDs before the request is built.

type ParamError

type ParamError struct {
	Param   string
	Message string
}

ParamError is a validation failure the model can correct.

func (*ParamError) Error

func (e *ParamError) Error() string

type ParamType

type ParamType string

ParamType is the JSON type the model must supply.

const (
	TypeString      ParamType = "string"
	TypeInteger     ParamType = "integer"
	TypeNumber      ParamType = "number"
	TypeBoolean     ParamType = "boolean"
	TypeStringList  ParamType = "string_list"
	TypeIntegerList ParamType = "integer_list"
)

Parameter types.

type Projected

type Projected struct {
	// Data is an object, or a list of objects for list results.
	Data any `json:"data"`
	// Meta holds Result.Meta fields, when declared.
	Meta map[string]any `json:"meta,omitempty"`
	// Truncated reports any loss of string content or list items in the projection.
	Truncated bool `json:"truncated,omitempty"`
}

Projected is the model-visible slice of a response.

func (Projected) Label

func (p Projected) Label(key string) string

Label returns the projected string field key, if present.

type Response

type Response struct {
	Status int
	Body   []byte
}

Response is a captured HTTP response.

type Result

type Result struct {
	// Root is a dotted path to the object or array to project, relative to
	// the response body. Empty means the body itself.
	Root string
	// List projects each element of the array at Root with Fields.
	List bool
	// Fields are relative to the object at Root, or to each element.
	Fields []Field
	// Meta fields are relative to the response body (e.g. a total count).
	Meta []Field
	// MaxItems caps List results; defaults to defaultMaxResultItems.
	MaxItems int
}

Result is the projection of a response body. Anything not listed is dropped, so new fields added to a handler never reach the model unless they are added here.

type Risk

type Risk = policy.Risk

Risk classifies an operation by its effect on user data.

type Target

type Target struct {
	Operation string
	// Label is the result field shown to the user (e.g. "title").
	Label string
	// Items, for a batch mutation, also resolves every item it acts on.
	Items *ItemTarget
	// RequireComplete blocks a full replacement when the target read loses data.
	RequireComplete bool
}

Target names the read operation that describes a mutation's subject.

type Withholding

type Withholding struct {
	// ReadOnly: the user set the assistant to read-only.
	ReadOnly    bool
	SystemAdmin bool
	// Role is the workspace role the operation needs when the caller's falls
	// short.
	Role types.TenantRole
}

Withholding says why an access leaves an operation out.

Jump to

Keyboard shortcuts

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