Policies & Approvals
Gojent policies (agent.Policy) govern model and tool calls at runtime with fail-closed semantics: once a policy is installed, any unrecognized decision or unapproved agent.Ask verdict resolves to agent.Deny. Use policies together with agent.Approver to require human confirmation for destructive operations, enforce security boundaries, or abort a run immediately.
How fail-closed enforcement works
Without a policy configured on agent.Config or agent.RunOptions, tool calls execute directly. As soon as a policy is attached, the runner enforces every verdict defensively:
agent.DecisionUnknown(the zero value) and any out-of-rangeDecisionvalue are treated asagent.Deny.agent.Askdelegates to the configuredagent.Approver. If no approver is configured orApprover.Approvereturns(false, nil), the call is denied and the model can recover. IfApprover.Approvereturns a non-nil error, the error propagates out of the tool gate and aborts the run without recordingllm.ToolStatusDeniedor emittingagent.ErrToolDenied.- Denied tool calls never invoke the tool handler; the runtime records a denied tool result (
llm.ToolStatusDenied) and emitsagent.ErrToolDeniedonToolEnd.Errso the model can recover without leaving unanswered tool calls in the session transcript. agent.Terminateaborts the run immediately withagent.ErrTerminatedand prevents dangling assistant tool-call messages from being persisted.
Tool decisions
BeforeTool inspects the step index, requested tool.Call, and tool metadata (tool.Spec, including tool.Annotations) and returns one of four explicit decisions:
| Decision | Effect |
|---|---|
agent.Allow |
Execute the tool handler. |
agent.Deny |
Skip execution and report the denial to the model. |
agent.Ask |
Require Approver.Approve to return true; deny if no approver is attached. |
agent.Terminate |
Abort the run immediately with agent.ErrTerminated. |
Gate destructive tools with Hooks and Approver
agent.Hooks implements agent.Policy using optional function fields, making it concise for single-purpose gates such as requiring approval whenever a tool declares Annotations.Destructive:
package main
import (
"context"
"fmt"
"log"
"github.com/ijaidev/gojent/core/agent"
"github.com/ijaidev/gojent/core/llm"
"github.com/ijaidev/gojent/core/tool"
"github.com/ijaidev/gojent/providers/mockllm"
)
func main() {
ctx := context.Background()
cleanup := tool.MustNew(tool.Config[struct{}, string]{
ID: "clean_build",
Description: "Remove build artifacts.",
Annotations: tool.Annotations{Destructive: true},
Execute: func(_ context.Context, _ struct{}) (string, error) {
return "cleaned", nil
},
})
turn := 0
model := mockllm.New().ApplyOptions(
mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) {
turn++
if turn == 1 {
return llm.NewSliceStream(ctx, []llm.StreamEvent{
llm.MessageStart{Model: "mock-llm"},
llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{
CallID: "c1",
Name: "clean_build",
Input: []byte(`{}`),
})},
llm.PartEnd{Index: 0},
llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool},
}), nil
}
return llm.NewSliceStream(ctx, []llm.StreamEvent{
llm.MessageStart{Model: "mock-llm"},
llm.PartStart{Index: 0, Part: llm.NewTextPart("")},
llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Build directory cleaned."},
llm.PartEnd{Index: 0},
llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop},
}), nil
}),
)
assistant, err := agent.New(agent.Config{
Name: "maintainer",
Model: model,
Tools: []tool.Tool{cleanup},
})
if err != nil {
log.Fatal(err)
}
opts := agent.RunOptions{
Policy: agent.Hooks{
OnBeforeTool: func(_ context.Context, req *agent.ToolRequest) (agent.Decision, error) {
if req.Spec.Annotations.Destructive {
return agent.Ask, nil
}
return agent.Allow, nil
},
},
Approver: agent.ApproverFunc(func(_ context.Context, req agent.ToolRequest) (bool, error) {
// Present req.Call and req.Spec to a human operator and return their choice.
return req.Call.Name == "clean_build", nil
}),
}
response, err := assistant.GenerateWith(ctx, "Clean up the build directory.", opts)
if err != nil {
log.Fatal(err)
}
fmt.Println(response.Text)
}
Because approval is evaluated inside the runtime loop rather than exposed as a tool, a model cannot bypass or spoof the approval check.
Compose policies with PolicyChain
Use agent.PolicyChain to layer multiple independent policies (for example, an organization-wide deny list followed by a workspace approval hook):
package main
import (
"context"
"fmt"
"github.com/ijaidev/gojent/core/agent"
)
func main() {
denyOpenWorld := agent.Hooks{
OnBeforeTool: func(_ context.Context, req *agent.ToolRequest) (agent.Decision, error) {
if req.Spec.Annotations.OpenWorld {
return agent.Deny, nil
}
return agent.Allow, nil
},
}
approveDestructive := agent.Hooks{
OnBeforeTool: func(_ context.Context, req *agent.ToolRequest) (agent.Decision, error) {
if req.Spec.Annotations.Destructive {
return agent.Ask, nil
}
return agent.Allow, nil
},
}
chain := agent.PolicyChain{
denyOpenWorld,
approveDestructive,
}
fmt.Println(len(chain))
}
PolicyChain applies strict composition rules:
BeforeModelandBeforeToolexecute in slice order.AfterModelandAfterToolexecute in reverse order, matching standard middleware unwinding.- For
BeforeTool, the most restrictive decision wins in precedence order:agent.Terminate>agent.Ask>agent.Deny(includingDecisionUnknown) >agent.Allow. - If any policy returns an error from
BeforeTool,PolicyChainimmediately returnsagent.Denyalongside the error.
Inspect model requests and responses
A full agent.Policy implementation also intercepts model turns via BeforeModel and AfterModel:
type Policy interface {
BeforeModel(ctx context.Context, req *ModelRequest) error
AfterModel(ctx context.Context, result *ModelResult) error
BeforeTool(ctx context.Context, req *ToolRequest) (Decision, error)
AfterTool(ctx context.Context, result *ToolResult) error
}
BeforeModel and AfterModel may inspect or rewrite req.Request and result.Response, or return an error to abort the run. Keep observation-only telemetry in agent.Sink rather than in a policy: sinks observe events without altering execution, whereas policies decide.
Agent defaults and run overrides
Behavior that should apply to every run belongs on agent.Config. A run overrides it with RunOptions; unset values inherit the agent configuration:
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/ijaidev/gojent/core/agent"
"github.com/ijaidev/gojent/core/session"
"github.com/ijaidev/gojent/providers/mockllm"
)
func main() {
ctx := context.Background()
temperature := 0.2
assistant, err := agent.New(agent.Config{
Name: "reviewer",
Model: mockllm.New("Repository analysis complete."),
Store: session.NewMemory(),
Budget: agent.Budget{MaxSteps: 16, MaxDuration: 10 * time.Minute},
Retry: agent.RetryPolicy{MaxAttempts: 3},
ToolTimeout: 30 * time.Second,
Temperature: &temperature,
})
if err != nil {
log.Fatal(err)
}
// This run raises only the step limit. The duration cap, store, retry
// policy, temperature, and tool timeout still apply.
response, err := assistant.Generate(ctx, "Analyze this repository.",
agent.WithMaxSteps(32),
agent.WithSession("review-1", "user-1"),
)
if err != nil {
log.Fatal(err)
}
fmt.Println(response.Text)
}
Precedence is package defaults < agent.Config < RunOptions. Budget and RetryPolicy merge field by field, so overriding one field keeps the others. Session is always per-run—an agent Store still requires a session on each call. Sink and Media also stay per-run because they belong to a specific execution.
Package defaults:
agent.DefaultMaxStepsis8whenBudget.MaxStepsis zero.agent.DefaultToolTimeoutis2 * time.MinutewhenToolTimeoutis zero (negative values disable the timeout).RetryPolicy.MaxAttemptscounts total attempts, including the first; zero or one disables retries.
(*Agent).ApplyAgentOptions applies this exact layering to a RunOptions value. The runtime calls it for every run, so custom wrappers or engines can reuse it instead of duplicating merge rules. See pkg.go.dev for full symbol reference.