gates

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 20 Imported by: 1 module, 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 gates is the rules that gate an agent's turn (spec_041_gates): checks written in plain English in .agents/rules/<name>.md, with front matter when: before_agent or after_agent, judged in order by a model before the agent runs (on the prompt) or after (on its answer and the files it changed), each blocking, warning or asking for a revision. A rule without when: is an instruction rule (spec_012_memory MEM-07), listed here so Studio can edit it, and loaded by the memory package.

Index

Constants

View Source
const (
	CheckJudge      = "judge"       // the judge reads its text against the content (the default)
	CheckRegex      = "regex"       // patterns: a match is a catch
	CheckKeywords   = "keywords"    // words: one found is a catch
	CheckMaxLength  = "max_length"  // longer than max_length characters is a catch
	CheckJSONSchema = "json_schema" // content that isn't JSON valid against schema is a catch
	CheckPII        = "pii"         // personal data (emails, phone and card numbers…) is a catch
)

The checks a custom guardrail makes (spec_041 GT-41): the judge, and the deterministic ones, which need no model and run first.

View Source
const (
	// BeforeAgent gates judge the prompt, before the agent runs.
	BeforeAgent = "before_agent"
	// AfterAgent gates judge the answer and the changed files, before the
	// turn ends.
	AfterAgent = "after_agent"
)

When a gate runs.

View Source
const (
	// Block stops the turn (before) or marks the answer as failing the
	// rule (after).
	Block = "block"
	// Warn says so in the conversation.
	Warn = "warn"
	// Revise gives the agent the reason: with the prompt (before), or as
	// a request for one more pass (after).
	Revise = "revise"
)

What a failed gate does.

View Source
const (
	// StageInput checks the prompt, before the turn.
	StageInput = "input"
	// StageToolResult checks what a tool brought back, before the model
	// reads it.
	StageToolResult = "tool_result"
	// StageOutput checks the model's answers.
	StageOutput = "output"
	// StageAction checks a tool call before it runs.
	StageAction = "action"
)

The stages a guardrail checks.

View Source
const (
	// BuiltinInjection watches tool results for instructions aimed at the
	// agent (prompt injection): patterns, and the judge when asked.
	BuiltinInjection = "prompt_injection"
	// BuiltinSecrets masks credentials (and, when asked, personal data)
	// in answers.
	BuiltinSecrets = "secrets"
	// BuiltinLimits holds a turn to limits: spending, model calls, files
	// changed, the domains it may reach and the commands it may not run.
	BuiltinLimits = "limits"
)

The built-in guardrails.

View Source
const (
	DefaultMaxTurns   = 200
	DefaultMaxCostUSD = 10
)

The limits guardrail's ceilings without a file (or a file that doesn't set them): high enough for real work, low enough to stop a runaway loop. A file's 0 means no ceiling.

View Source
const DefaultsEntry = "defaults"

DefaultsEntry, in a limits file's commands, stands for DefaultCommands as this version of Blitz has them, so a file that adds its own commands keeps getting the defaults' updates instead of a copy.

View Source
const InjectionNote = "[removed by the prompt_injection guardrail: instructions aimed at the agent]"

InjectionNote stands in for a phrase RedactInjection took out.

View Source
const Redact = "redact"

Redact is a guardrail action: what it finds is masked, the rest kept.

Variables

View Source
var Builtins = []Builtin{
	{ID: BuiltinInjection, Stage: StageToolResult, Action: Redact, Actions: []string{Redact, Warn, Block}},
	{ID: BuiltinSecrets, Stage: StageOutput, Action: Redact, Actions: []string{Redact, Warn, Block}},
	{ID: BuiltinLimits, Stage: StageAction, Action: Block, Actions: []string{Block}},
}

Builtins are the built-in guardrails, in the order Studio lists them.

Checks are every check, as a guardrail's check: may name them.

View Source
var DefaultCommands = []string{
	"git push* --force", "git push* --force *", "git push* -f", "git push* -f *", "git push* +*",
	"rm -rf /", "rm -rf ~", "rm -rf ~/", "rm -r /", "rm -r ~", "rm -r ~/",
	"mkfs*", "dd *of=/dev/sd*", "dd *of=/dev/disk*", "dd *of=/dev/nvme*",
}

DefaultCommands are the commands the limits guardrail refuses without a file: a force push (--force, -f or a +refspec; --force-with-lease, which won't overwrite commits it hasn't seen, is allowed), deleting the whole disk or the home folder (rm's flags in any order, each path on its own, $HOME as ~, a folder's /* as the folder: CommandDenied), formatting a disk, and writing over one.

View Source
var ErrNoJudge = errors.New("it can't be judged here")

ErrNoJudge is a guardrail that needs the judge where there's none.

View Source
var ErrUnknown = errors.New("no such rule")

ErrUnknown means there's no rule of that name.

Functions

func Check

func Check(spec Spec) []string

Check is what keeps spec from being saved.

func CheckGuardrail

func CheckGuardrail(spec GuardrailSpec) []string

CheckGuardrail is what keeps spec from being saved.

func CommandDenied

func CommandDenied(command string, denied []string) string

CommandDenied is the first of denied (globs: * is anything, slashes too; ? one character) that a shell line matches, "" when none does. A glob is matched against the whole line, its spaces made single, and against each command it runs: split at ;, &&, ||, | and new lines, with those in $(…), `…` and sh -c "…" too, and sudo, env, nice, nohup, time and VAR=value before it dropped with their options. A git command is matched without git's own options (git -C dir push as git push), a push's bundled short flags one each (-uf as -u -f). An rm is matched as "rm -rf <path>" (or -r, -f) once per path, whatever order or spelling its flags have (-fr, -R -f, --recursive --force), $HOME and ${HOME} read as ~ and a trailing /* as the folder itself; so "rm -rf ~/" refuses "sudo rm -fr $HOME/*" too.

func Delete

func Delete(dir, name string) error

Delete removes rule name from dir.

func DeleteGuardrail

func DeleteGuardrail(dir, name string) error

DeleteGuardrail removes guardrail name from dir (a built-in's file: it runs with its defaults again).

func Describe added in v0.8.6

func Describe(g Guardrail) string

Describe is a built-in guardrail as it runs, in words: where it runs, what it checks (its patterns or limits, with this file's changes), its action and what that does, and the actions it could take instead. It's what the dashboard's judge reads of a built-in (a file holds only what it changes), so it says everything the defaults leave out. A custom guardrail's file says it all: "" for one.

func DomainAllowed

func DomainAllowed(raw string, domains []string) bool

DomainAllowed reports whether the URL raw is on one of domains (a domain allows its subdomains); with none listed, every domain is.

func ExpandCommands added in v0.8.6

func ExpandCommands(commands []string) []string

ExpandCommands is commands with DefaultsEntry replaced by the defaults.

func Injection

func Injection(text string) string

Injection reports the first phrase in text that looks like instructions aimed at the agent ("" when none does).

func RedactInjection added in v0.8.6

func RedactInjection(text string) (string, bool)

RedactInjection is text with each phrase that looks like instructions aimed at the agent replaced by a note saying so, and whether there was one: the rest of the content stays for the agent to use.

func Reorder

func Reorder(dir string, names []string) error

Reorder gives the gates named, in dir, orders 10, 20, 30… in the order given: Studio's dragged lists.

func Save

func Save(dir string, spec Spec, previous string) (string, []string, error)

Save writes dir/<name>.md from spec and returns its path, or the problems that keep it from being saved (nothing written). previous is the rule edited ("" for a new one); another name renames its file. The front matter's other fields are kept.

func SaveGuardrail

func SaveGuardrail(dir string, spec GuardrailSpec, previous string) (string, []string, error)

SaveGuardrail writes dir/<name>.md from spec (a built-in's file is named by its id, and edited in place when it's there) and returns its path, or the problems that keep it from being saved. previous is the custom guardrail edited ("" for a new one).

func ValidName

func ValidName(name string) bool

ValidName reports whether name may name a rule file (without .md). Studio's validRuleName (apps/desktop/web ruleForm.ts) is a copy.

Types

type Asker

type Asker func(ctx context.Context, instruction, prompt string) (string, error)

Asker asks a model: an instruction and a prompt, its reply's text.

type Builtin

type Builtin struct {
	ID      string
	Stage   string
	Action  string
	Actions []string
}

Builtin is one of the built-in guardrails: where it runs, its default action, and the actions it takes.

func BuiltinOf

func BuiltinOf(id string) (Builtin, bool)

BuiltinOf is the built-in guardrail id names.

type Guardrail

type Guardrail struct {
	// Name is its file's name without .md (a built-in's is its id).
	Name    string
	Path    string
	Builtin string
	Stage   string
	// Action is Block, Warn or Redact (a built-in's allowed ones).
	Action string
	// Agents are the agents it guards (none: every one).
	Agents []string
	// Tools are the tools a tool-result or action guardrail checks (none:
	// those that bring in outside content, for tool results; every tool,
	// for actions).
	Tools       []string
	Description string
	// PII makes the secrets guardrail mask personal data too; Judge makes
	// the injection guardrail confirm with the judge before acting.
	PII    bool
	Judge  bool
	Limits Limits
	// Text is a custom guardrail's check, in plain English, for the judge.
	Text string
	// Check is a custom guardrail's checks (GT-41): judge (the default),
	// regex, keywords, max_length, json_schema, pii; the deterministic
	// ones run first, and the judge only when they catch nothing.
	Check []string
	// Patterns (regex) and Words (keywords, CaseSensitive or not) are what
	// they look for; MinMatches how many make a catch (1).
	Patterns      []string
	Words         []string
	CaseSensitive bool
	MinMatches    int
	// MaxLength is max_length's most characters; Schema json_schema's
	// schema, as JSON.
	MaxLength int
	Schema    string
	// Threshold is the judge's score (0 to 1, how surely the guardrail is
	// broken) at which it acts; 0: the judge's own pass or fail.
	Threshold float64

	// Off is a guardrail switched off (enabled: false): it checks nothing.
	Off     bool
	Problem string
	// contains filtered or unexported fields
}

Guardrail is one guardrail file.

func Active

func Active(all []Guardrail, stage, agent string) []Guardrail

Active are the guardrails that hold (no problem, not switched off) at stage for agent. A built-in whose file has a problem runs with its defaults, as without a file: a mistake in limits.md mustn't take away its ceilings and refused commands.

func BuiltinDefault

func BuiltinDefault(b Builtin) Guardrail

BuiltinDefault is a built-in guardrail as it runs without a file: on, with its default action; the injection one confirming a match with the judge, limits refusing the default commands within its default ceilings.

func LoadGuardrails

func LoadGuardrails(dirs ...string) []Guardrail

LoadGuardrails reads every guardrail file (*.md) in dirs, a name in an earlier folder winning, and adds each built-in one without a file, with its defaults: the built-in ones first, in catalog order, then custom ones by stage and name.

func ParseGuardrail

func ParseGuardrail(name, path string, data []byte) Guardrail

ParseGuardrail reads a guardrail file; what doesn't hold is its Problem (it's skipped; a built-in's runs with its defaults).

func (Guardrail) Checks

func (g Guardrail) Checks(tool string, external bool) bool

Checks reports whether g checks the named tool: one of its tools, or with none listed, every tool for an action guardrail and those that bring in outside content (external) for a tool-result one.

func (Guardrail) For added in v0.9.1

func (g Guardrail) For() string

For is the built-in g stands for: its builtin, or, for a file with a problem, the built-in it's named after ("" for neither).

func (Guardrail) GuardsAgent

func (g Guardrail) GuardsAgent(agent string) bool

GuardsAgent reports whether g guards the named agent (none listed: every agent; one that can't be told: guarded).

func (Guardrail) NeedsJudge added in v1.1.0

func (g Guardrail) NeedsJudge() bool

NeedsJudge reports whether g asks the judge (GT-41): a guardrail of deterministic checks alone runs without a model.

func (Guardrail) Streamable added in v1.1.0

func (g Guardrail) Streamable() bool

Streamable reports whether g can check an answer piece by piece as it streams (GT-45): only regex, keywords and pii, without the judge; a length or a schema needs the whole answer.

type GuardrailSpec

type GuardrailSpec struct {
	Name        string
	Builtin     string
	Stage       string
	Action      string
	Agents      []string
	Tools       []string
	Description string
	PII         bool
	Judge       bool
	Limits      Limits
	Text        string
	// Off switches the guardrail off (enabled: false), keeping its
	// settings.
	Off bool
}

GuardrailSpec is what Studio's guardrail form edits.

type Limits

type Limits struct {
	MaxCostUSD      float64  `yaml:"max_cost_usd,omitempty"`
	MaxTurns        int      `yaml:"max_turns,omitempty"`
	MaxFilesChanged int      `yaml:"max_files_changed,omitempty"`
	AllowedDomains  []string `yaml:"allowed_domains,omitempty"`
	// Commands are shell commands the agent may not run (globs, like
	// "git push --force*", matched against the whole command).
	Commands []string `yaml:"commands,omitempty"`
}

Limits are what the limits guardrail holds a turn to; zero or empty means no limit of that kind.

type Rule

type Rule struct {
	// Name is its file's path in the rule folder, without .md.
	Name string
	Path string
	// When is BeforeAgent or AfterAgent for a gate, "" for an instruction
	// rule.
	When string
	// Order sorts gates (then their names): lower first.
	Order int
	// Agents are the agents it gates (none: every one).
	Agents []string
	// Action is Block, Warn or Revise (a gate; Warn when unset).
	Action      string
	Description string
	// Paths scope an instruction rule to files (MEM-07).
	Paths []string
	// Text is the rule, in plain English.
	Text string
	// Problem says why its front matter doesn't hold (it's skipped).
	Problem string
	// Off is a rule switched off (enabled: false, spec_040_studio
	// STU-16): it gates nothing and isn't an instruction.
	Off bool
}

Rule is one rule file: a gate (When set) or an instruction rule.

func Gates

func Gates(rules []Rule, when, agent string) []Rule

Gates are the rules that run when for the agent, in order, without those whose front matter doesn't hold or that are switched off.

func Load

func Load(dirs ...string) []Rule

Load reads every rule file (*.md, recursively) in dirs; a name in an earlier folder wins. Gates come first, by when (before, then after), order and name; then instruction rules by name.

func Parse

func Parse(name, path string, data []byte) Rule

Parse reads a rule file. A front matter that doesn't hold (an unknown when or action) is its Problem.

func (Rule) IsGate

func (r Rule) IsGate() bool

IsGate reports whether the rule gates turns.

func (Rule) OfferedTo

func (r Rule) OfferedTo(agent string) bool

OfferedTo reports whether the rule gates the named agent's turns (agents:; none means every agent, and an agent that can't be told is gated by all).

type Spec

type Spec struct {
	Name        string
	When        string
	Action      string
	Order       int
	Agents      []string
	Description string
	Paths       []string
	Text        string
	// Off switches the rule off (enabled: false), keeping the rest.
	Off bool
}

Spec is what Studio's rule form edits.

type Verdict

type Verdict struct {
	Pass   bool
	Reason string
	// Score is how surely it's broken, 0 to 1 (a guardrail's judge, or 1
	// for a deterministic catch); Check which check decided (GT-44).
	Score float64
	Check string
}

Verdict is the judge's answer: whether the subject passes the rule, and why (for a failure, what to fix).

func ConfirmInjection

func ConfirmInjection(ctx context.Context, ask Asker, content string) (Verdict, error)

ConfirmInjection has ask judge whether content is prompt injection.

func Deterministic added in v1.1.0

func Deterministic(g Guardrail, subject string) (v Verdict, caught bool)

Deterministic runs g's deterministic checks on subject (GT-42): the first that catches it is a failed verdict, which check and why, with score 1; caught is false when none did (or it has none).

func Evaluate added in v1.1.0

func Evaluate(ctx context.Context, ask Asker, g Guardrail, subject string) (Verdict, error)

Evaluate checks subject against custom guardrail g (GT-42): its deterministic checks first, and a catch there is the verdict without a model; then, when it asks the judge, the judge's verdict, its score against g's threshold. A guardrail of deterministic checks alone that catches nothing passes.

func Judge

func Judge(ctx context.Context, ask Asker, r Rule, subject string) (Verdict, error)

Judge has ask judge whether subject (the prompt, for a before-agent gate; the answer and changed files, after) passes the rule.

func JudgeGuardrail

func JudgeGuardrail(ctx context.Context, ask Asker, g Guardrail, subject string) (Verdict, error)

JudgeGuardrail has ask judge subject against a custom guardrail.

Jump to

Keyboard shortcuts

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