approval

package
v3.1.0-dev.2 Latest Latest
Warning

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

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

Documentation

Overview

Package approval is the write gate: the seam where a mutating tool call stops and waits for an operator (docs/durable-write-gate-design.md).

It is deliberately two halves that meet here and nowhere else:

  • pkg/permissions decides POLICY — may this call proceed without asking, must it ask, or is it refused outright. That package is ADK-independent and stays that way.
  • ADK's tool-confirmation flow performs the PAUSE. It is durable: the request is a function call in the session event log, so the turn survives a process death and resumes from the log.

The seam itself is an ADK runner plugin's BeforeToolCallback, which is the only place that sees every tool call — builtin, MCP, or specialist-scoped — before it runs. Registration order matters and is settled: the internal/effects outbox plugin goes first, this one second, so a replayed call is answered from the outbox without asking an operator to approve a mutation that already happened.

Index

Constants

View Source
const CaptureStateKeyPrefix = "mast_effect_capture_"

CaptureStateKeyPrefix namespaces the durable prior-state record of one mutating call.

View Source
const ChangeSetField = "proposed_change"

ChangeSetField is the report property a change set travels in.

View Source
const ChangeSetStateKeyPrefix = "mast_change_set_"

ChangeSetStateKeyPrefix namespaces the durable record of the change set one specialist proposed, one key per specialist.

View Source
const DecisionSchema = "mast.decision/v1"

DecisionSchema names the record shape in an export's provenance header.

View Source
const DecisionStateKeyPrefix = "mast_decision_"

DecisionStateKeyPrefix namespaces the durable record of one adjudication in the session's state, one key per function call.

View Source
const DefaultGrantTTL = 10 * time.Minute

DefaultGrantTTL is how long a change-set grant lives when the bundle does not say.

View Source
const EditStateKeyPrefix = "mast_approval_edit_"

EditStateKeyPrefix namespaces the durable record of an applied edit in the session's state, one key per function call.

View Source
const FinishTaskToolName = "finish_task"

FinishTaskToolName is the completion tool ADK auto-installs on every Task-mode agent.

View Source
const GrantStateKeyPrefix = "mast_change_grant_"

GrantStateKeyPrefix namespaces the durable record of one minted change-set grant. One key per authorized call.

View Source
const MachineApproverPrefix = "mast:"

MachineApproverPrefix marks an identity that names a mechanism rather than a person.

View Source
const PluginName = "mast-write-gate"

PluginName is the registered name of the write gate's runner plugin.

View Source
const RedactedApproverPrefix = "sha256:"

RedactedApproverPrefix marks a digested identity in an export.

Variables

This section is empty.

Functions

func CallKey

func CallKey(name string, args map[string]any) string

CallKey renders a tool call as the one-line description an operator approves and the deny policy matches against.

func CaptureFromPolicies

func CaptureFromPolicies(policies []config.ToolPolicyConfig) func(string) (*Capture, error)

CaptureFromPolicies builds a CaptureRules.For lookup function from declarative config.ToolPolicyConfig entries (#1455).

func CaptureStateKey

func CaptureStateKey(functionCallID string) string

CaptureStateKey is the state key holding the capture for one call.

func ChangeSetStateKey

func ChangeSetStateKey(specialist string) string

ChangeSetStateKey is the state key holding a specialist's proposed change set.

func ConfirmationResponse

func ConfirmationResponse(v Verdict) map[string]any

ConfirmationResponse builds the FunctionResponse payload that answers a parked mutating call.

func DecisionStateKey

func DecisionStateKey(functionCallID string) string

DecisionStateKey is the state key holding the Decision record for one function call.

func DescribeCapture

func DescribeCapture(r CaptureRecord) string

DescribeCapture renders a capture record as the two lines an operator needs: what was overwritten, and the call that puts it back.

func DescribeChangeSet

func DescribeChangeSet(changes []ProposedChange) string

DescribeChangeSet renders a change set for a prompt or an operator message: one canonical signature per line, in list order.

func EditStateKey

func EditStateKey(functionCallID string) string

EditStateKey is the state key holding the AppliedEdit record for one function call.

func EncodeCapture

func EncodeCapture(r CaptureRecord) (string, error)

EncodeCapture renders a capture for durable state.

func EncodeChangeSet

func EncodeChangeSet(changes []ProposedChange) (string, error)

EncodeChangeSet renders a change set for durable state.

func EncodeDecision

func EncodeDecision(d Decision) (string, error)

EncodeDecision renders the record for storage.

func EncodeGrant

func EncodeGrant(g Grant) (string, error)

EncodeGrant renders a grant for durable state.

func GrantStateKey

func GrantStateKey(signature string) string

GrantStateKey is the state key holding the grant for one call signature.

func InputSchema

func InputSchema(t tool.Tool) (*jsonschema.Schema, error)

InputSchema reads a tool's declared parameters as a JSON Schema.

func Legible

func Legible(changes []ProposedChange) error

Legible reports whether a change set is one an operator can approve as a set.

func MutatingFromPolicies

func MutatingFromPolicies(policies []config.ToolPolicyConfig, gate *permissions.Gate) func(string) bool

MutatingFromPolicies returns a tool mutation classifier backed by policies and falling back to gate.ToolClass (or permissions.DefaultToolClass when gate is nil).

func New

func New(cfg Config, opts ...Option) (*plugin.Plugin, error)

New builds the write gate as an ADK runner plugin.

Register it AFTER the internal/effects outbox plugin at every runner construction site.

func NewPlugin

func NewPlugin(cfg Config, opts ...Option) (*plugin.Plugin, error)

NewPlugin is an alias for New.

func NormalizeArgs

func NormalizeArgs(toolName string, schema *jsonschema.Schema, args map[string]any) (map[string]any, error)

NormalizeArgs validates one call's arguments against the tool's declared input schema and returns them in the shape the tool will receive.

func ParkHintFieldsFromPolicies

func ParkHintFieldsFromPolicies(policies []config.ToolPolicyConfig) func(string) []string

ParkHintFieldsFromPolicies returns a lookup function for per-tool park_hint_fields configured in policies.

func PreconditionFromPolicies

func PreconditionFromPolicies(policies []config.ToolPolicyConfig) func(string) (*Precondition, error)

PreconditionFromPolicies builds a Freshness.Precondition lookup function from declarative config.ToolPolicyConfig entries (#1455).

func RedactApprover

func RedactApprover(approver string) string

RedactApprover replaces an approver identity with a stable digest of it.

func Signature

func Signature(toolName string, args map[string]any) (string, error)

Signature renders a change as a byte-stable identity for the exact call it proposes.

func VerdictSchema

func VerdictSchema() *jsonschema.Schema

VerdictSchema is the JSON schema a resume payload answering a parked mutating call must satisfy.

func WithTurnStop

func WithTurnStop(ctx context.Context, stop TurnStop) context.Context

WithTurnStop returns ctx carrying stop, for the write gate to find.

Types

type AppliedEdit

type AppliedEdit struct {
	Tool         string         `json:"tool"`
	Approver     string         `json:"approver"`
	ProposedKey  string         `json:"proposed_key"`
	ExecutedKey  string         `json:"executed_key"`
	ProposedArgs map[string]any `json:"proposed_args"`
	ExecutedArgs map[string]any `json:"executed_args"`
	Note         string         `json:"note,omitempty"`
}

AppliedEdit is the durable record of an operator's edit being applied: what the model asked for, what actually ran, and who authorized the substitution.

func DecodeAppliedEdit

func DecodeAppliedEdit(v any) (AppliedEdit, error)

DecodeAppliedEdit parses a record written under an EditStateKey.

func (AppliedEdit) String

func (e AppliedEdit) String() string

String renders the record for an operator-facing listing.

type Authority

type Authority string

Authority is where the authorization for this call came from.

const (
	// AuthorityVerdict is the ordinary case: a person was asked about
	// this exact call and answered it.
	AuthorityVerdict Authority = "operator_verdict"

	// AuthorityChangeSetGrant is a call that fired on an answer given
	// earlier about a different call in the same change set (W7).
	AuthorityChangeSetGrant Authority = "change_set_grant"
)

type Capture

type Capture struct {
	Read     string            `json:"read"`
	Args     map[string]any    `json:"args,omitempty"`
	ArgsFrom map[string]string `json:"args_from,omitempty"`
	Fields   []string          `json:"fields,omitempty"`
	Revert   *Revert           `json:"revert,omitempty"`
}

Capture is a workload's declaration of how to record what a mutating call is about to change.

type CaptureRecord

type CaptureRecord struct {
	Tool           string          `json:"tool"`
	Key            string          `json:"key"`
	Arguments      map[string]any  `json:"arguments"`
	CapturedAt     time.Time       `json:"captured_at"`
	Read           string          `json:"read"`
	ReadArgs       map[string]any  `json:"read_args,omitempty"`
	Prior          map[string]any  `json:"prior"`
	PriorFields    []string        `json:"prior_fields,omitempty"`
	Digest         string          `json:"digest"`
	Revert         *ProposedChange `json:"revert,omitempty"`
	Workload       string          `json:"workload,omitempty"`
	Specialist     string          `json:"specialist,omitempty"`
	Session        string          `json:"session,omitempty"`
	Invocation     string          `json:"invocation,omitempty"`
	FunctionCallID string          `json:"function_call_id,omitempty"`
}

CaptureRecord is the durable answer to "how do I undo this": one mutating call, the state it was about to overwrite, and the call that puts that state back.

func DecodeCapture

func DecodeCapture(v any) (CaptureRecord, error)

DecodeCapture parses a record written under a CaptureStateKey.

func (CaptureRecord) Undoable

func (r CaptureRecord) Undoable() bool

Undoable reports whether this record names a call that would restore the captured state.

type CaptureRules

type CaptureRules struct {
	For    func(toolName string) (*Capture, error)
	Read   func(ctx agent.Context, toolName string, args map[string]any) (map[string]any, error)
	Schema func(toolName string) (*jsonschema.Schema, error)
	Now    func() time.Time
}

CaptureRules is the runtime half of prior-state capture: what each tool declares, and the two things needed to honor a declaration.

type ChangeSetChecker

type ChangeSetChecker struct {
	Declares func(toolName string) bool
	Schema   func(toolName string) (*jsonschema.Schema, error)
}

ChangeSetChecker validates a proposed change set against the workload's catalog and the named tools' declared input schemas.

func (ChangeSetChecker) Check

func (c ChangeSetChecker) Check(changes []ProposedChange) ([]ProposedChange, error)

Check validates every entry and returns the change set with each entry's arguments normalized into the shape the tool will receive.

type ChangeSetContext

type ChangeSetContext struct {
	Specialist    string            `json:"specialist"`
	Changes       []ProposedChange  `json:"changes"`
	Grantable     bool              `json:"grantable"`
	Ungrantable   string            `json:"ungrantable,omitempty"`
	TTLSeconds    int               `json:"ttl_seconds,omitempty"`
	Preconditions map[string]string `json:"preconditions,omitempty"`
}

ChangeSetContext is what the parked question says about the set the call belongs to, so an operator answering one call can see the rest and authorize them together.

type Config

type Config struct {
	// Policy is the workload's hitl_policy.on_mutation. Required.
	Policy OnMutation

	// Mutating classifies a tool by name. Required.
	Mutating func(toolName string) bool

	// Gate adjudicates policy for a parked call and validates the
	// operator's verdict. Required when Policy is
	// OnMutationRequireApproval; unused otherwise.
	Gate *permissions.Gate

	// ChangeSet, when non-nil, enforces the change-set producer
	// contract (W7.0).
	ChangeSet *ChangeSetChecker

	// Grants, when non-nil, lets one operator answer authorize a whole
	// change set (W7).
	Grants *Freshness

	// Captures, when non-nil, records what a mutating call is about to
	// overwrite before it fires, and the call that puts it back (#296).
	Captures *CaptureRules

	// ParkHintFields, when non-nil, returns the subset of argument names
	// to include in the operator-facing park hint for toolName (#1455).
	ParkHintFields func(toolName string) []string

	// ForgetToolRun, when non-nil, is called with a session ID when the
	// gate turns away a call an operator already refused in this turn.
	ForgetToolRun func(sessionID string)

	// NotifyPark, when non-nil, is told out of band that a call has been
	// parked (#451).
	NotifyPark func(context.Context, ParkNotice)

	// DecisionSink, when non-nil, persists each Decision record before
	// BeforeToolCallback returns to execute the tool (mast #561).
	DecisionSink DecisionSink

	// DecisionLookup, when non-nil, checks whether a FunctionCallID has
	// already been durably adjudicated in the external DecisionStore
	// across process restarts (mast #561).
	DecisionLookup DecisionLookup

	// Workload names the workload whose bundle composed this gate, and
	// is stamped onto every Decision record. Optional.
	Workload string

	// Logger receives the audit trail. Defaults to slog.Default().
	Logger *slog.Logger
}

Config wires the write gate.

type Decision

type Decision struct {
	DecidedAt      time.Time      `json:"decided_at"`
	Session        string         `json:"session"`
	Workload       string         `json:"workload,omitempty"`
	Specialist     string         `json:"specialist,omitempty"`
	Invocation     string         `json:"invocation,omitempty"`
	FunctionCallID string         `json:"function_call_id,omitempty"`
	Tool           string         `json:"tool"`
	Outcome        Outcome        `json:"outcome,omitempty"`
	Scope          Scope          `json:"scope,omitempty"`
	Authority      Authority      `json:"authority"`
	Disposition    Disposition    `json:"disposition"`
	Refusal        string         `json:"refusal,omitempty"`
	ChangeSet      string         `json:"change_set,omitempty"`
	ProposedKey    string         `json:"proposed_key"`
	ProposedArgs   map[string]any `json:"proposed_args,omitempty"`
	ExecutedKey    string         `json:"executed_key,omitempty"`
	ExecutedArgs   map[string]any `json:"executed_args,omitempty"`
	Approver       string         `json:"approver,omitempty"`
	Note           string         `json:"note,omitempty"`
}

Decision is the durable record of one adjudication of one mutating call: what was proposed, what the operator answered, what actually ran, and who decided.

func DecodeDecision

func DecodeDecision(v any) (Decision, error)

DecodeDecision parses a record written under a DecisionStateKey.

func (Decision) Edited

func (d Decision) Edited() bool

Edited reports whether the operator substituted their own arguments.

func (Decision) Redacted

func (d Decision) Redacted() Decision

Redacted returns a copy of the record with the approver digested.

type DecisionLookup

type DecisionLookup func(ctx context.Context, sessionID, functionCallID string) (bool, error)

DecisionLookup reports whether a Decision record for functionCallID in sessionID has already been durably persisted in the external DecisionStore (e.g. before a mid-tool crash across process restart where session.State never received the post-tool StateDelta).

type DecisionSink

type DecisionSink func(ctx context.Context, d Decision) error

DecisionSink persists a Decision record durably before BeforeToolCallback returns nil to execute the tool (mast #561 fix). Even if the process crashes mid-tool before the FunctionResponse event and its StateDelta are appended, the approver attribution is durably recorded.

type Disposition

type Disposition string

Disposition is what the gate did with the call, as distinct from what the operator asked for.

const (
	// DispositionAuthorized means the gate let the call through.
	DispositionAuthorized Disposition = "authorized"

	// DispositionRefusedByOperator means a person said no.
	DispositionRefusedByOperator Disposition = "refused_by_operator"

	// DispositionRefusedByMast means the write gate refused a verdict a
	// person gave.
	DispositionRefusedByMast Disposition = "refused_by_mast"
)

type Freshness

type Freshness struct {
	TTL          time.Duration
	Now          func() time.Time
	Precondition func(toolName string) (*Precondition, error)
	Read         func(ctx agent.Context, toolName string, args map[string]any) (map[string]any, error)
}

Freshness bounds how long an approval speaks for.

type Grant

type Grant struct {
	Signature    string                `json:"signature"`
	Tool         string                `json:"tool"`
	Arguments    map[string]any        `json:"arguments"`
	Origin       string                `json:"origin"`
	Approver     string                `json:"approver,omitempty"`
	Note         string                `json:"note,omitempty"`
	MintedAt     time.Time             `json:"minted_at"`
	ExpiresAt    time.Time             `json:"expires_at"`
	Precondition *PreconditionSnapshot `json:"precondition,omitempty"`
	ConsumedBy   string                `json:"consumed_by,omitempty"`
	VoidedBy     string                `json:"voided_by,omitempty"`
}

Grant is the durable record of one authorized call.

func DecodeGrant

func DecodeGrant(v any) (Grant, error)

DecodeGrant reads a grant back out of durable state.

func (Grant) Spent

func (g Grant) Spent(functionCallID string) bool

Spent reports whether this grant can still authorize a call.

type OnMutation

type OnMutation string

OnMutation is a workload's policy for what happens when an agent calls a mutating tool (hitl_policy.on_mutation).

const (
	// OnMutationRequireApproval parks the call and waits for an
	// operator.
	OnMutationRequireApproval OnMutation = "require_approval"

	// OnMutationApply executes mutating calls without asking. Policy
	// still applies — a configured deny still denies — but no human is
	// consulted.
	OnMutationApply OnMutation = "apply"

	// OnMutationDryRun never executes a mutating call and reports the
	// call it would have made.
	OnMutationDryRun OnMutation = "dry_run"
)

func (OnMutation) Valid

func (p OnMutation) Valid() bool

Valid reports whether p is a policy this package implements.

type Option

type Option func(*Config)

Option configures a write-gate plugin at construction time.

func WithDecisionLookup

func WithDecisionLookup(lookup DecisionLookup) Option

WithDecisionLookup attaches a durable lookup for already-adjudicated FunctionCallIDs across process restarts (#1400, mast #561).

func WithDecisionSink

func WithDecisionSink(sink DecisionSink) Option

WithDecisionSink attaches a pre-execution durable sink for Decision records (#1400, mast #561).

func WithToolPolicies

func WithToolPolicies(policies []config.ToolPolicyConfig) Option

WithToolPolicies wires Mutating, ParkHintFields, Grants.Precondition, and Captures.For from a config.Tools.Policies slice (#1455).

type Outcome

type Outcome string

Outcome is the operator's answer to a parked mutating call.

const (
	// OutcomeApprove runs the call as the agent proposed it.
	OutcomeApprove Outcome = "approve"
	// OutcomeReject refuses the call.
	OutcomeReject Outcome = "reject"
	// OutcomeEdit runs the call with arguments the operator supplied in
	// place of the agent's.
	OutcomeEdit Outcome = "edit"
)

type ParkNotice

type ParkNotice struct {
	Session    string
	Invocation string
	Workload   string
	Agent      string
	Tool       string
	Key        string
	Hint       string
	ParkedAt   time.Time
}

ParkNotice is what the gate hands NotifyPark when it parks a call.

type Parked

type Parked struct {
	Hint    string
	CallID  string
	Tool    string
	Args    map[string]any
	Request map[string]any
}

Parked describes a mutating call waiting on an operator, read back out of the durable session log.

func DescribeConfirmation

func DescribeConfirmation(args map[string]any) Parked

DescribeConfirmation reads a parked mutating call out of the Args of an adk_request_confirmation function call.

func (Parked) Summary

func (p Parked) Summary() string

Summary is the operator-facing one-liner for a parked call.

type Precondition

type Precondition struct {
	Read     string            `json:"read"`
	Args     map[string]any    `json:"args,omitempty"`
	ArgsFrom map[string]string `json:"args_from,omitempty"`
	Fields   []string          `json:"fields,omitempty"`
}

Precondition is a workload's declaration of what a change assumed about the environment, expressed as a read this deployment can make.

type PreconditionSnapshot

type PreconditionSnapshot struct {
	Read   string            `json:"read"`
	Args   map[string]any    `json:"args,omitempty"`
	Digest string            `json:"digest"`
	Fields map[string]string `json:"fields,omitempty"`
}

PreconditionSnapshot is what the read returned at approval time.

type ProposedChange

type ProposedChange struct {
	Tool      string         `json:"tool"`
	Arguments map[string]any `json:"arguments"`
}

ProposedChange is one machine-executable remediation: a tool the workload declares, and the arguments to call it with.

func DecodeChangeSet

func DecodeChangeSet(v any) ([]ProposedChange, error)

DecodeChangeSet reads a change set back out of durable state.

func ParseChangeSet

func ParseChangeSet(report map[string]any) ([]ProposedChange, error)

ParseChangeSet reads the change set out of a specialist's structured report.

func (ProposedChange) Signature

func (c ProposedChange) Signature() (string, error)

Signature is the change's call signature. See Signature.

func (*ProposedChange) UnmarshalJSON

func (c *ProposedChange) UnmarshalJSON(raw []byte) error

UnmarshalJSON accepts `arguments` as either a JSON object or a JSON string holding one.

type RefusalLoopError

type RefusalLoopError struct {
	Tool  string
	Key   string
	Count int
}

RefusalLoopError is the reason a turn ended in which the model kept re-proposing a call an operator had already refused.

func (*RefusalLoopError) Error

func (e *RefusalLoopError) Error() string

func (*RefusalLoopError) TurnErrorKind

func (e *RefusalLoopError) TurnErrorKind() string

TurnErrorKind implements the attach package's turn-error classification contract without importing pkg/attach.

type Request

type Request struct {
	Tool      string            `json:"tool"`
	Args      map[string]any    `json:"args"`
	Key       string            `json:"key"`
	Policy    string            `json:"policy"`
	Agent     string            `json:"agent"`
	Verdict   map[string]any    `json:"verdict_format"`
	ChangeSet *ChangeSetContext `json:"change_set,omitempty"`
	Stale     string            `json:"stale,omitempty"`
}

Request is the payload of the parked confirmation.

func DecodeRequest

func DecodeRequest(v any) (Request, error)

DecodeRequest reads the parked confirmation's payload back into the typed Request.

type Revert

type Revert struct {
	Call            string            `json:"call"`
	Args            map[string]any    `json:"args,omitempty"`
	ArgsFromChange  map[string]string `json:"args_from_change,omitempty"`
	ArgsFromCapture map[string]string `json:"args_from_capture,omitempty"`
}

Revert declares the call that undoes a change, in terms of the change and the state captured before it.

type Scope

type Scope string

Scope is how far an approval reaches.

const (
	// ScopeOnce authorizes exactly this call.
	ScopeOnce Scope = "once"
	// ScopeSession asks to authorize this exact request for the session.
	ScopeSession Scope = "session"
	// ScopeSessionTool asks to authorize every call to this tool for the
	// session.
	ScopeSessionTool Scope = "session_tool"
	// ScopeAlways asks to persist a standing allowlist entry.
	ScopeAlways Scope = "always"
	// ScopeChangeSet authorizes this call and the other calls in the
	// change set it belongs to.
	ScopeChangeSet Scope = "change_set"
)

type TurnStop

type TurnStop interface {
	StopTurn(reason error)
}

TurnStop ends the turn the gate is running in.

func TurnStopFrom

func TurnStopFrom(ctx context.Context) TurnStop

TurnStopFrom returns the stop on ctx, or nil if this turn cannot be ended from inside.

type Verdict

type Verdict struct {
	Verdict  Outcome        `json:"verdict"`
	Scope    Scope          `json:"scope,omitempty"`
	Args     map[string]any `json:"args,omitempty"`
	Note     string         `json:"note,omitempty"`
	Approver string         `json:"approver,omitempty"`
}

Verdict is the operator's answer, carried in the Payload of the ADK tool confirmation that resumes a parked call.

func DecodeVerdict

func DecodeVerdict(c *toolconfirmation.ToolConfirmation) (Verdict, error)

DecodeVerdict reads the verdict record out of an ADK tool confirmation.

func (Verdict) Decision

func (v Verdict) Decision() (permissions.Decision, error)

Decision maps the verdict's scope onto the permissions decision the gate adjudicates.

Jump to

Keyboard shortcuts

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