Documentation
¶
Overview ¶
Package agent is the provider-neutral core of dialogram: the block IR a conversation is persisted in, the Provider contract every model backend implements, the Agent wrapper that layers the honesty guard and metrics on top of a provider, and the supporting pieces the tool loop relies on (profiles, interceptors, skills, pause detection).
Nothing in this package speaks a provider wire format. The Anthropic and OpenAI translators live in provider/anthropic and provider/openai; the shared loop machinery they both use lives in internal/loop.
Index ¶
- Constants
- Variables
- func CollectGroundedNumbers(turns []Turn, minDigits int) map[string]bool
- func CountAssistantTurns(turns []Turn) int
- func DeniedResultJSON(reason string) string
- func DismissedResultJSON(kind, reason string) string
- func EstOutputTokens(reply string) int
- func FindPendingHITL(turns []Turn) (toolUseID, prompt string, ok bool)
- func FindPendingPause(turns []Turn, isPause func(name string) bool) (toolUseID, toolName string, rawInput json.RawMessage, ok bool)
- func IsImageMediaType(mt string) bool
- func NewToolUseID() string
- func NotRunResultJSON(toolName string) string
- func PromptFingerprint(prompt string) string
- func RegisterLoadSkill(reg *tool.Registry, lib *SkillLibrary)
- func ResultIsSuccess(raw string) bool
- func RunInterruptedResultJSON(toolName string) string
- func SkillsSummary(lib *SkillLibrary) string
- func ValidateSkills(fsys fs.FS, root string) error
- type Accumulator
- type Agent
- type ApprovalListInterceptor
- type Block
- type BlockType
- type ChatInput
- type ChatMessage
- type ChatOutput
- type Checkpoint
- type Checkpointer
- type ChoiceOption
- type Config
- type EmitFn
- type FormQuestion
- type Guard
- type InterceptAction
- type InterceptDecision
- type Interceptor
- type MemCheckpointer
- type Metrics
- type Options
- type Pause
- type Policy
- type PolicyInterceptor
- type Profile
- type Provider
- type Redaction
- type Signature
- type Skill
- type SkillLibrary
- type StreamEvent
- type TokenBreakdown
- type ToolTrace
- type Turn
Constants ¶
const ( EventMeta = "meta" EventText = "text" EventToolCall = "tool_call" EventToolResult = "tool_result" EventGenUI = "gen_ui" EventUsage = "usage" EventTurn = "turn" EventWaitingForUser = "waiting_for_user" EventDone = "done" EventError = "error" )
Stream event types emitted by providers and the streaming layer.
const ( PauseKindHITL = "hitl" PauseKindHITLChoice = "hitl_choice" PauseKindHITLForm = "hitl_form" PauseKindApproval = "approval" // PauseKindCustom marks a pause raised by an application-defined pause // tool (Config.PauseTools). The event carries the tool's Name and Input // so the application can render it and resolve it on resume. PauseKindCustom = "custom" // PauseKindToolInput marks a pause raised by a tool that needs the // user's input to finish a call (tool.NeedInput; an MCP server's // elicitation). The event carries the tool's Name and Input, and the // tool.InputRequest as Request; resume with tool.ExecuteWithInput and // agent.AnswerPause. PauseKindToolInput = "tool_input" )
Kinds of waiting_for_user pauses.
const ( RoleUser = "user" RoleAssistant = "assistant" RoleTool = "tool" )
Roles a Turn may carry.
const DefaultFinalSynthesisNudge = "You've reached the tool-call budget for this turn, so no further tools are available. " +
"Do not ask to run more tools. Using only the results you've already gathered, give the user your best, " +
"complete answer now. Briefly note any gaps where you'd have looked further, but lead with the substantive findings."
DefaultFinalSynthesisNudge is appended as a one-off user message when the step cap is reached, so the model wraps up from the data it already has instead of dead-ending.
const DefaultMaxToolSteps = 12
DefaultMaxToolSteps caps how many tool_use rounds a single turn may run before the loop makes one tool-free synthesis call and returns.
const DefaultPlaceholder = "〔I don't have a verified figure for this — I'd need to look it up before quoting one〕"
DefaultPlaceholder is the honest, first-person text that replaces an un-grounded figure. It offers the real path forward, so a redaction reads as the assistant declining to guess rather than as a censored blank.
const InstrumentationName = telemetry.Scope
InstrumentationName is the OpenTelemetry instrumentation scope every dialogram tracer uses: the module path. Filter or route dialogram's spans by it.
const LoadSkillToolName = "load_skill"
LoadSkillToolName is the reserved tool through which the model loads a skill's instructions and reads the files bundled with it.
const ToolUseIDPrefix = "dg_"
ToolUseIDPrefix is the prefix of every neutral tool_use id this runtime mints.
Variables ¶
var ErrNotPending = errors.New("agent: the tool call is not pending")
ErrNotPending is returned by AnswerPause for a tool call that is not in the conversation, or already has a result.
Functions ¶
func CollectGroundedNumbers ¶
CollectGroundedNumbers harvests every numeric token of >= minDigits digits from the tool results and tool inputs in turns — the numbers engineering vouched for, which the model may restate on a later no-tool turn. The inputs of the built-in human-in-the-loop tools are skipped: the model wrote them for the user, and nothing vouched for them.
func CountAssistantTurns ¶
CountAssistantTurns returns the number of assistant turns in a slice — the count of upstream completions in one chat turn.
func DeniedResultJSON ¶
DeniedResultJSON is the tool_result body the loop feeds back to the model when an interceptor (or the user, on an approval pause) denies a tool. The shape mirrors the soft-failure convention so the model's handling of error_code applies to denials without extra teaching.
func DismissedResultJSON ¶
DismissedResultJSON is the tool_result body for a pause the user left without an answer: they dismissed it, or sent a new message instead. kind is the pause's kind (a PauseKind* constant). An approval reads as declined (DeniedResultJSON), so the model never takes the call for done; any other pause is a USER_CANCELLED soft failure. An empty reason gets a default.
func EstOutputTokens ¶
EstOutputTokens approximates a reply's length in tokens (~4 chars per token). Rough by design; the eval budgets and the metrics share this one definition so they agree.
func FindPendingHITL ¶
FindPendingHITL returns the details of a request_user_input tool_use block at the tail of turns that has no paired tool_result. ok=false when the conversation is not paused on a free-text question.
Pairing is scoped to the most recent assistant turn: any tool_use in an earlier assistant turn is, by construction, already paired by the loop's own tool turn that follows it.
func FindPendingPause ¶
func FindPendingPause(turns []Turn, isPause func(name string) bool) (toolUseID, toolName string, rawInput json.RawMessage, ok bool)
FindPendingPause detects an application-defined pause tool (see Config.PauseTools) at the tail of turns with no paired tool_result. isPause decides which tool names count; the built-in HITL tools are handled by the three Find* functions above and are not matched here.
func IsImageMediaType ¶
IsImageMediaType reports whether mt is one of the image media types both providers accept for an inline image.
func NewToolUseID ¶
func NewToolUseID() string
NewToolUseID returns a provider-neutral tool_use identifier: the prefix followed by 24 random hex chars (96 bits of entropy).
Why mint our own instead of passing the provider's native id through ("toolu_…" from Anthropic, "call_…" from OpenAI):
- Within a single provider request, the id is just an opaque string used to match tool_use blocks to their tool_result replies. Providers do not recognise ids across requests, so any internally consistent id works.
- Across requests, minting our own id means the persisted state carries no provider fingerprint. A conversation started on OpenAI can be resumed on Anthropic (and vice versa) without an id-format mismatch masquerading as a protocol error.
- If a provider changes its id format, stored history does not have to be rewritten.
func NotRunResultJSON ¶
NotRunResultJSON is the tool_result body AnswerPause gives a call of the paused turn that never ran. It is a soft failure the model can act on by calling the tool again.
func PromptFingerprint ¶
PromptFingerprint returns a stable content hash (hex SHA-256) of a system prompt. Pin it in a golden test: an intentional prompt edit then fails the test until the golden is re-baselined — a conscious act that flags the nightly scenario scores for a fresh look.
func RegisterLoadSkill ¶
func RegisterLoadSkill(reg *tool.Registry, lib *SkillLibrary)
RegisterLoadSkill wires the load_skill tool into reg, backed by lib. It is a no-op when lib is nil or empty, so no load_skill appears on the wire when there is nothing to load. The name parameter is an enum of the library's skill names, so the model cannot ask for a skill that does not exist.
Tool contract:
input: {"name": "<skill>", "offset"?: n} → instructions
{"name": "<skill>", "path": "<file>", "offset"?: n} → one bundled file
output: {"name", "compatibility"?, "instructions", "offset"?, "next_offset"?, "resources"?, "resources_omitted"?, "note"?}
{"name", "path", "content", "bytes", "offset"?, "next_offset"?, "note"?}
misses: soft failures UNKNOWN_SKILL, UNKNOWN_RESOURCE, BINARY_RESOURCE,
INVALID_INPUT, NOT_FOUND
Text longer than one page (32 KiB) is returned a page at a time, cut at a line break where one is near: next_offset is where the following page starts, and the note tells the model to call again with it.
Bundled files are served from the skill's own listing only, so a path cannot leave the skill directory. Scripts are returned as text and never run: executing them needs a tool of the application's own, with its own isolation.
func ResultIsSuccess ¶
ResultIsSuccess reports whether a serialised tool result vouches for anything: a JSON object carrying a top-level error_code or soft_failure (directly or inside an envelope's model_observation) does not. Empty or non-JSON output is treated as success — the caller only knows the tool ran, which is the pre-outcome-aware behaviour.
func RunInterruptedResultJSON ¶
RunInterruptedResultJSON is the tool_result body CloseDangling pairs with a tool_use whose run died before the result was recorded. Retryable is set: the tool never completed, so calling it again is the right move.
func SkillsSummary ¶
func SkillsSummary(lib *SkillLibrary) string
SkillsSummary renders the skill catalog appended to a stable system prompt: a short instruction and an <available_skills> block with one name and description per skill, the format the specification's reference library generates. Empty when the library is nil or empty, so no catalog appears when there is nothing to load.
func ValidateSkills ¶
ValidateSkills applies the specification's strict rules, the checks the reference validator (`skills-ref validate`) performs, to every skill under root. It returns one joined error listing every problem, or nil when all skills are spec-clean. Finding no skills is an error, since it usually means the wrong root. Run it in a test so the skills you ship stay portable to other clients:
func TestSkillsAreSpecClean(t *testing.T) {
if err := agent.ValidateSkills(os.DirFS("."), "skills"); err != nil {
t.Fatal(err)
}
}
Types ¶
type Accumulator ¶
type Accumulator struct {
// Text is the concatenated text deltas — a diagnostic signal ("did we
// emit anything before the stream broke?"), not the reply of record.
Text strings.Builder
// Turns are the assistant and tool turns in order.
Turns []Turn
// Paused is set by a waiting_for_user event; the Pause* fields carry
// what the event said.
Paused bool
PausedKind string
PausedToolUseID string
PausedToolName string
PausedToolInput json.RawMessage
PausedPrompt string
// PausedRequest is the tool.InputRequest of a tool_input pause.
PausedRequest json.RawMessage
// Usage counters track the LAST seen usage event. Providers emit usage
// cumulatively per turn, so the last value is the per-turn total.
InputTokens int
OutputTokens int
CacheReadTokens int
CacheCreationTokens int
}
Accumulator folds a stream of events into the state a server needs once the stream ends: the neutral Turn sequence to persist, whether the loop paused (and on what), and the final usage counters. Emission order is single-threaded (providers call emit serially), so no locking is needed.
func (*Accumulator) Observe ¶
func (a *Accumulator) Observe(ev StreamEvent)
Observe folds one event into the accumulator.
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent wraps a Provider with the cross-cutting layers that belong above the wire protocol: the honesty Guard, turn metrics and the run's root trace span. HTTP layers should talk to an Agent, not to a Provider directly.
func (*Agent) Chat ¶
Chat runs one non-streaming turn under the run span, then applies the guard (if any) and records metrics.
func (*Agent) ChatStream ¶
ChatStream runs one streaming turn under the run span. When a Guard is installed, text deltas are held and re-emitted at each assistant turn boundary so an un-grounded figure is redacted from both the live stream and the persisted turn snapshot before either reaches the client.
func (*Agent) Underlying ¶
Underlying returns the wrapped Provider.
type ApprovalListInterceptor ¶
type ApprovalListInterceptor struct {
// contains filtered or unexported fields
}
ApprovalListInterceptor pauses on any tool_use whose name is in names — the minimal "ask before running" policy. The intercepted tool's input is carried on the waiting_for_user event so the application can dispatch it verbatim on approve.
func NewApprovalListInterceptor ¶
func NewApprovalListInterceptor(names []string) *ApprovalListInterceptor
NewApprovalListInterceptor returns an interceptor pausing on any of names. Empty input returns an always-Allow interceptor so callers can wire it unconditionally.
func (*ApprovalListInterceptor) InspectToolUse ¶
func (a *ApprovalListInterceptor) InspectToolUse(_ context.Context, b Block) InterceptDecision
InspectToolUse returns InterceptPause when b's tool name is in the configured set, InterceptAllow otherwise.
type Block ¶
type Block struct {
Type BlockType `json:"type"`
Text string `json:"text,omitempty"`
ToolUseID string `json:"tool_use_id,omitempty"`
ToolName string `json:"tool_name,omitempty"`
ToolInput json.RawMessage `json:"tool_input,omitempty"`
// ToolResult holds the raw JSON returned by tool.Registry.Call — already
// serialised by the tool. OpenAI's tool-role content takes this string
// verbatim; Anthropic's tool_result.content accepts the same string.
ToolResult json.RawMessage `json:"tool_result,omitempty"`
// MediaType, Data and URL describe a BlockImage: MediaType is one of
// the image/* types IsImageMediaType accepts, and exactly one of Data
// (base64, without a data: prefix) or URL is set. Images are only
// valid in user turns; each translator maps the block to its own
// image part and rejects it anywhere else.
MediaType string `json:"media_type,omitempty"`
Data string `json:"data,omitempty"`
URL string `json:"url,omitempty"`
}
Block is the provider-neutral content unit of a conversation turn. A turn is a sequence of blocks; a conversation is a sequence of turns. This is the internal representation the agent loop manipulates — each provider has a translator that maps Blocks to its own wire format.
The IR exists so mid-turn state (tool_use / tool_result pairs) can be persisted in a provider-agnostic shape, enabling two things a flat message list cannot:
- Human-in-the-loop: a paused tool_use can be resumed by appending a tool_result block later, without re-running the whole turn.
- Cross-provider failover: a conversation started on OpenAI can be resumed on Anthropic (and vice versa) because neither wire format is baked into the persisted state.
ToolUseID is always a neutral id minted by NewToolUseID. The provider-native id is only meaningful within a single in-flight request and is never stored.
func DanglingToolUses ¶
DanglingToolUses returns, in order, every tool_use block in turns that has no tool_result with the same ToolUseID anywhere in turns. In a well-formed conversation these can only sit in the last assistant turn; they are what a Checkpoint reports as Pending.
func ImageBlock ¶
ImageBlock builds an inline image block from base64 data (no data: URI prefix) and its media type: image/png, image/jpeg, image/gif or image/webp. Validation happens at translation time, so an unsupported type surfaces as a provider error on the next call, not here.
func ImageURLBlock ¶
ImageURLBlock builds an image block the provider fetches itself from a public URL.
func SplitPauseTurn ¶
SplitPauseTurn partitions the tool_use blocks of an assistant turn into pause tools (as decided by isPause) and regular tools. A turn is "mixed" when both slices are non-empty: the model co-requested a pause alongside real tool calls. The loop runs the regular tools, attaches their results, and feeds a deterministic correction back for each pause block instead of silently discarding the real work. Non-tool_use blocks are ignored.
type ChatInput ¶
type ChatInput struct {
// Messages is the flat text history — each entry becomes a single text
// block in a Turn. Callers that need to round-trip tool_use /
// tool_result state across turns should populate Turns instead.
Messages []ChatMessage `json:"messages,omitempty"`
// Turns is the block-IR form of the conversation history. When set, it
// takes precedence over Messages. Use this when replaying a conversation
// whose blocks include tool_use / tool_result pairs (cross-provider
// resume, human-in-the-loop resume).
Turns []Turn `json:"turns,omitempty"`
// Profile names the Profile (system prompt, tool allow-list, step cap)
// this turn runs under. Empty selects Config.DefaultProfile.
Profile string `json:"profile,omitempty"`
// MemoryContext is the VOLATILE system block: a rendered text block the
// caller assembles per turn (user memory, workspace state, retrieved
// context). Providers append it after the stable system prompt and keep
// it OUT of the prompt-cache breakpoint, so the large stable prefix stays
// cache-eligible while this part drifts. Empty means no volatile block.
MemoryContext string `json:"memory_context,omitempty"`
// Tools, when non-nil, narrows the per-turn tool envelope further than
// the Profile allow-list does — e.g. an intent router that only ships
// the two tools relevant to the latest user message. Nil means the full
// profile set.
Tools []string `json:"tools,omitempty"`
// MessageID identifies this run — the id the sse handler hands its
// Producer — so step checkpoints (see Checkpointer) are keyed to it.
// It may stay empty when no Checkpointer is configured; with one,
// every run must set it or concurrent runs overwrite each other's
// checkpoints.
MessageID string `json:"message_id,omitempty"`
}
ChatInput is one request to the agent: the conversation so far plus the per-turn knobs.
func (ChatInput) InputTurns ¶
InputTurns returns the Turn sequence to feed the provider loop. If Turns is set it is used (empty turns dropped, roles normalised); otherwise the flat Messages are lifted. Never returns nil — an empty slice means no history.
type ChatMessage ¶
ChatMessage is the legacy flat history shape: one text message per turn.
type ChatOutput ¶
type ChatOutput struct {
Reply string `json:"reply"`
ToolCalls []ToolTrace `json:"tool_calls"`
// Turns is the assistant + tool Turn sequence produced by this call, in
// order (excluding the user turn that was input). Persist it as block
// IR; it carries the tool_use_id pairings a resume needs.
Turns []Turn `json:"turns,omitempty"`
Provider string `json:"provider"`
Model string `json:"model"`
TokenBreakdown *TokenBreakdown `json:"token_breakdown,omitempty"`
// CacheReadTokens / CacheCreationTokens are the provider-reported
// prompt-cache counters summed across this call's tool-loop steps.
// Unlike TokenBreakdown (a char-count estimate) these are authoritative.
// OpenAI reports only cache reads, so CacheCreationTokens stays 0 there.
CacheReadTokens int `json:"cache_read_tokens,omitempty"`
CacheCreationTokens int `json:"cache_creation_tokens,omitempty"`
}
ChatOutput is the non-streaming result of one chat turn.
func (*ChatOutput) CacheReadRatio ¶
func (o *ChatOutput) CacheReadRatio() float64
CacheReadRatio is cache_read / (cache_read + cache_creation) for this turn, 0 when no cache activity was reported.
func (*ChatOutput) ToolSteps ¶
func (o *ChatOutput) ToolSteps() int
ToolSteps counts the upstream completions in this turn: one per assistant Turn. Interleaved tool turns are local execution, not model round-trips.
type Checkpoint ¶
type Checkpoint struct {
// MessageID is ChatInput.MessageID — the run this checkpoint belongs to.
MessageID string `json:"message_id"`
// Step is the 1-based step within this run (one step = one upstream
// completion plus its tool turn). Both boundaries of a step carry the
// same number; the step-cap synthesis turn is MaxSteps+1.
Step int `json:"step"`
// Turns are the assistant and tool turns this run has produced so far,
// in order. The input history is not repeated — the application has it.
Turns []Turn `json:"turns"`
// Pending are the tool_use blocks whose results are not yet in Turns:
// the just-finalised assistant turn's calls, or nothing at a tool-turn
// boundary. A pause tool stays pending until the user answers.
Pending []Block `json:"pending,omitempty"`
// At is when the checkpoint was taken.
At time.Time `json:"at"`
}
Checkpoint is the block IR of one run at a step boundary. The loop hands one to the Checkpointer after every assistant turn is finalised (Pending = that turn's tool_use blocks, if any) and again after the matching tool turn is appended (Pending empty). An application that loses the process mid-turn can then pick the conversation up from the last boundary: the stream buffer has the events the client saw, the checkpoint has the state the model needs.
type Checkpointer ¶
type Checkpointer interface {
Save(ctx context.Context, cp Checkpoint) error
}
Checkpointer persists a Checkpoint. Save runs synchronously on the producer goroutine at every step boundary, so it should be one quick write keyed by MessageID, the latest checkpoint replacing the previous. The loop logs a Save error and carries on — checkpointing is a durability aid, never a correctness gate for the run.
This is also the seam for durable-execution engines (Temporal, DBOS and the like): a Checkpointer that records each boundary as a workflow step hands those engines exactly the state they replay from.
type ChoiceOption ¶
ChoiceOption is one selectable item in a request_user_choice prompt.
func FindPendingChoice ¶
func FindPendingChoice(turns []Turn) (toolUseID string, rawInput json.RawMessage, prompt string, options []ChoiceOption, multiple bool, ok bool)
FindPendingChoice is FindPendingHITL for the structured-choice variant. rawInput is the full tool_input JSON so callers can store it without re-scanning the turn.
type Config ¶
type Config struct {
// Profiles by name.
Profiles map[string]Profile
// DefaultProfile is used when ChatInput.Profile is empty or unknown.
// When empty, the zero Profile is used.
DefaultProfile string
// PauseTools are application-defined tools that, like the built-in
// human-in-the-loop tools, end the assistant turn and wait for the user
// (e.g. "propose this change, let the user accept or skip"). The loop
// never dispatches them; it emits a waiting_for_user event of
// PauseKindCustom carrying the tool name and input.
PauseTools []string
}
Config holds the profiles and the pause-tool policy shared by every turn. A nil *Config is valid and behaves like an empty one: a single unnamed profile with no system prompt and every tool visible.
func (*Config) CloseDangling ¶
CloseDangling is CloseDangling with the config's pause tools (built-in and Config.PauseTools) exempt. Nil-safe.
func (*Config) IsPauseTool ¶
IsPauseTool reports whether name ends the assistant turn by pausing for the user: one of the built-in HITL tools or a Config.PauseTools entry. Nil-safe.
type EmitFn ¶
type EmitFn func(StreamEvent)
EmitFn receives stream events in order. Providers call it serially.
type FormQuestion ¶
type FormQuestion struct {
ID string `json:"id"`
Type string `json:"type"`
Prompt string `json:"prompt"`
Required bool `json:"required,omitempty"`
Options []ChoiceOption `json:"options,omitempty"`
AllowOther bool `json:"allow_other,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
}
FormQuestion is one question in a request_user_form prompt. Type constrains the input shape: "text" → free-form string; "single_choice" → exactly one option value (or other_text when the user picks "Other"); "multi_choice" → a list of option values (with optional other_text).
func FindPendingForm ¶
func FindPendingForm(turns []Turn) (toolUseID string, rawInput json.RawMessage, title, reason string, questions []FormQuestion, ok bool)
FindPendingForm is FindPendingHITL for the multi-question form variant.
type Guard ¶
type Guard struct {
// GroundingTools are the tools whose SUCCESSFUL result legitimately
// backs a figure. A figure cited on a turn that called any of these
// (successfully) is grounded and is NOT redacted. The safe failure
// direction is over-redaction (visible), never a leak (silent), so an
// unknown tool does not count.
GroundingTools map[string]bool
// KindGrounding optionally narrows grounding per signature kind: when a
// kind has an entry here, only THOSE tools vouch for figures of that
// kind (e.g. an "entity_fact" kind grounded only by a profile lookup,
// not by any numeric tool). Kinds without an entry use GroundingTools.
KindGrounding map[string]map[string]bool
// Signatures are the regulated-figure detectors. Each should be
// high-precision so the guard fires on a genuine fabricated figure and
// stays quiet on ordinary prose. DefaultSignatures covers currency
// amounts and percentages.
Signatures []Signature
// Placeholder replaces a redacted span when the matching Signature has
// none of its own. Defaults to DefaultPlaceholder.
Placeholder string
// PauseTools names the application pause tools (Config.PauseTools)
// whose input is shown to the user. The built-in human-in-the-loop
// tools always count.
PauseTools map[string]bool
// MinRestatementDigits is the minimum digit count for a number harvested
// from tool results / inputs to count as "a figure a tool produced" for
// the restatement exemption. Defaults to 2. Lower it to 1 to exempt every
// number a tool ever emitted (at the cost of single-digit percentages
// surviving on a no-tool turn); raise it to 3 to exempt only amounts.
MinRestatementDigits int
// Logger receives one Warn per redacted turn. nil uses slog.Default().
Logger *slog.Logger
}
Guard is the turn-level honesty guard.
Prompt instruction alone does not stop a model from reciting a regulated figure from memory under pressure — it displaces the fabrication to whatever phrasing the prompt did not enumerate. Engineering has to own the trust line: on a turn that produced NO successful grounding tool call, an answer that nonetheless states a figure matching one of the Signatures is treated as fabricated and the span is replaced with an honest placeholder.
Two rules are built in:
- Grounding means a SUCCESSFUL result, not a call. A tool whose output carries error_code / soft_failure vouches for nothing; the model stating a figure after a soft-failed lookup is a common leak, and a name-only check cannot see it (ResultIsSuccess).
- Restating a number a tool actually produced is honest. Every numeric token of at least MinRestatementDigits digits found in a tool result or tool input earlier in the conversation is exempt from redaction.
A pause tool's input is text the model wrote for the user to read: the question of request_user_choice, a proposal the application shows on a card. The guard checks it like the reply on the same turn and redacts it in the persisted tool_use block and in the waiting_for_user event alike. Its numbers are never counted as grounded, so a figure cannot be laundered through a pause and then restated as if a tool had produced it.
The guard is pure and unit-testable; the policy of *where* it runs is Agent's (Agent.Chat redacts the reply and the persisted turns; ChatStream holds text deltas and re-emits them redacted at each assistant turn boundary). Install it through Options.Guard; a nil Guard means no guarding.
func (*Guard) Flag ¶
Flag is the guard's decision: given the assistant text for a turn and the tool calls made this turn (with their outputs when known), it reports whether the text states a regulated figure with no successful grounding call behind it, and which signature kind fired first.
func (*Guard) GuardReply ¶
func (g *Guard) GuardReply(history []Turn, out *ChatOutput) []Redaction
GuardReply applies the guard to a non-streaming ChatOutput: numbers a tool produced earlier in history (the block-IR conversation fed as ChatInput.Turns) are seeded as grounded, then any un-grounded figure in out.Reply and out.Turns is redacted in place. Returns the redactions.
Exported so an eval harness can compare a raw provider reply with the guarded reply from ONE upstream call — a paired before/after measurement.
func (*Guard) Redact ¶
Redact replaces every signature span in text with its placeholder, except spans that only restate a grounded number. It returns the rewritten text and the redactions made. Callers invoke it only on a turn Flag already flagged, so any non-restatement span is a number the model invented.
func (*Guard) WrapEmit ¶
WrapEmit wraps an EmitFn with the guard. It swallows raw text deltas and re-emits each assistant segment's text at that segment's turn boundary — where the full text and the tools used are both known — redacting any un-grounded figure first. The redaction is applied to BOTH the live text event and the persisted turn snapshot, keeping the streamed and re-hydrated views identical. Token-level streaming is traded for the guarantee; install a Guard only on surfaces where that trade is right.
type InterceptAction ¶
type InterceptAction string
InterceptAction is the outcome an Interceptor returns for one tool_use.
const ( // InterceptAllow lets the tool dispatch proceed normally. Returned by // default when no interceptor cares about the tool. InterceptAllow InterceptAction = "allow" // InterceptDeny blocks the dispatch and feeds a synthetic tool_result // carrying Reason back to the model. The model sees the rejection the // same way it sees any soft tool failure and can recover or surface it. InterceptDeny InterceptAction = "deny" // InterceptPause suspends the turn with a waiting_for_user event of // PauseKindApproval. The application resumes it with the user's // decision — on approve it dispatches the stashed tool, on deny it // appends a DENIED tool_result. InterceptPause InterceptAction = "pause" )
type InterceptDecision ¶
type InterceptDecision struct {
Action InterceptAction
Reason string
}
InterceptDecision is the outcome of evaluating one tool_use against the interceptor chain. Reason is the human-readable explanation used by Deny (stuffed into the tool_result error body) and Pause (shown to the user as the pause prompt).
func RunInterceptors ¶
func RunInterceptors(ctx context.Context, chain []Interceptor, b Block) InterceptDecision
RunInterceptors evaluates chain on one tool_use, short-circuiting at the first non-Allow decision.
type Interceptor ¶
type Interceptor interface {
InspectToolUse(ctx context.Context, b Block) InterceptDecision
}
Interceptor inspects a tool_use block before dispatch. Implementations should be side-effect-free except for logging — the decision they return is the only thing that shapes the loop's behaviour.
Interceptors run in registration order; the first non-Allow decision wins and later interceptors do not run for that block. An empty chain always allows.
type MemCheckpointer ¶
type MemCheckpointer struct {
// contains filtered or unexported fields
}
MemCheckpointer keeps the latest checkpoint per message id in memory. Meant for tests and single-process examples; it does not survive a restart, which is the one failure checkpoints exist for — production wires a Checkpointer over its database.
func NewMemCheckpointer ¶
func NewMemCheckpointer() *MemCheckpointer
NewMemCheckpointer builds an empty MemCheckpointer.
func (*MemCheckpointer) Delete ¶
func (m *MemCheckpointer) Delete(messageID string)
Delete forgets messageID — call it once the run's turns are persisted through the normal path so a finished run leaves nothing behind.
func (*MemCheckpointer) Load ¶
func (m *MemCheckpointer) Load(messageID string) (Checkpoint, bool)
Load returns the latest checkpoint for messageID. The slices are copies; callers may append to them freely.
func (*MemCheckpointer) Save ¶
func (m *MemCheckpointer) Save(_ context.Context, cp Checkpoint) error
Save replaces the checkpoint stored for cp.MessageID.
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics are the per-turn budget signals an Agent records: completed turns, tool steps per turn, output tokens per turn, and the prompt-cache read ratio. They mirror the budgets the eval package asserts, so an eval threshold breach predicts a real SLO regression rather than just failing a test in isolation.
Metrics are opt-in: nothing is registered on any registry unless you construct a Metrics and hand it to agent.New. Labels are bounded (profile and provider are small fixed enums), so this is safe on a high-RPS path.
func NewMetrics ¶
func NewMetrics(reg prometheus.Registerer) (*Metrics, error)
NewMetrics builds the collectors and registers them on reg. A nil reg builds unregistered collectors (useful in tests). Registration errors (e.g. a second Metrics on the same registry) are returned.
func (*Metrics) ObserveTurn ¶
func (m *Metrics) ObserveTurn(profile, provider string, toolSteps, outputTokens, cacheRead, cacheCreation int)
ObserveTurn records one completed chat turn's budget signals. Best-effort and side-effect-only; nil-safe. A turn with cacheRead+cacheCreation == 0 reported no cache activity, so the ratio is left unobserved rather than recorded as a misleading 0.
type Options ¶
type Options struct {
// Guard, when non-nil, redacts un-grounded regulated figures from
// replies (see Guard). nil disables guarding entirely.
Guard *Guard
// Metrics, when non-nil, receives per-turn budget signals.
Metrics *Metrics
// TracerProvider is the source of each run's root span; the model-call
// and tool spans under it come from the same provider. nil uses
// otel.GetTracerProvider(), which records nothing until an SDK is
// installed. See docs/OBSERVABILITY.md for the span model.
TracerProvider trace.TracerProvider
}
Options are the optional layers New installs around a Provider. A zero Options is valid: no guard, no metrics, spans from the global TracerProvider (a no-op until an OpenTelemetry SDK is installed).
type Pause ¶
type Pause struct {
Kind string
ToolUseID string
ToolName string
Input json.RawMessage
Message string
Options []ChoiceOption
Multiple bool
}
Pause describes a detected pause in an assistant turn, in the shape the waiting_for_user stream event carries.
func DetectPause ¶
DetectPause inspects a PURE pause turn (no co-requested regular tools — callers split mixed turns first with SplitPauseTurn) and returns the pause it carries, if any. The built-in HITL kinds are checked first, then isPause for application-defined pause tools.
func (*Pause) Event ¶
func (p *Pause) Event() StreamEvent
Event renders the pause as its waiting_for_user stream event.
type Policy ¶
type Policy struct {
// PauseDestructive pauses for approval on any tool whose Annotations
// mark it Destructive.
PauseDestructive bool
// PauseOpenWorld pauses for approval on any tool whose Annotations
// mark it OpenWorld.
PauseOpenWorld bool
// DenyUnknown denies a tool_use that names a tool the registry does not
// hold. Without it the miss surfaces later as a HARD_FAILURE from
// Registry.Call; with it the rejection is an explicit DENIED decision
// taken before anything is dispatched.
DenyUnknown bool
// DenyDestructive denies any tool annotated Destructive outright. It is
// stronger than PauseDestructive and takes precedence over it: a
// denial cannot be approved away.
DenyDestructive bool
}
Policy is the annotation-driven rule set PolicyInterceptor enforces. Every field is opt-in: the zero Policy allows everything, so the interceptor can be wired unconditionally and tightened per deployment.
type PolicyInterceptor ¶
type PolicyInterceptor struct {
// contains filtered or unexported fields
}
PolicyInterceptor applies a Policy to every tool_use by looking the tool up in the registry and reading its tool.Annotations. Decisions, in order of precedence:
- unknown tool → Deny (Policy.DenyUnknown), else Allow
- Destructive → Deny (Policy.DenyDestructive)
- Destructive → Pause (Policy.PauseDestructive)
- OpenWorld → Pause (Policy.PauseOpenWorld)
- otherwise → Allow
Annotations are evaluated as declared; a tool that is ReadOnly and Destructive at once is a tool bug, and the policy errs on the side of treating it as destructive.
Combining with ApprovalListInterceptor: put the PolicyInterceptor FIRST. RunInterceptors stops at the first non-Allow decision, and an approval pause the user accepts is dispatched by the application without re-running the chain. If the list ran first, a tool the policy would deny could instead be paused by the list and then approved straight past the denial. With the policy first a denial is final, a policy pause still pauses, and anything the policy allows falls through to the list:
Interceptors: []agent.Interceptor{
agent.NewPolicyInterceptor(reg, agent.Policy{DenyUnknown: true, PauseDestructive: true}),
agent.NewApprovalListInterceptor([]string{"book_flight"}),
}
Pause tools (the built-in HITL tools and Config.PauseTools) are split out of the assistant turn before the interceptor chain runs, so the policy never sees them; in particular DenyUnknown does not deny an application's unregistered custom pause tool.
func NewPolicyInterceptor ¶
func NewPolicyInterceptor(reg *tool.Registry, p Policy) *PolicyInterceptor
NewPolicyInterceptor returns an interceptor enforcing p against the tools registered in reg. A nil reg makes every tool unknown.
func (*PolicyInterceptor) InspectToolUse ¶
func (p *PolicyInterceptor) InspectToolUse(_ context.Context, b Block) InterceptDecision
InspectToolUse evaluates b against the policy. See PolicyInterceptor for the precedence order.
type Profile ¶
type Profile struct {
// Name is the key the profile is selected by. Filled from the map key
// by Config.Resolve when empty.
Name string
// SystemPrompt is the cache-stable base prompt. Skills summaries are
// appended to it; the volatile ChatInput.MemoryContext is sent as a
// separate block.
SystemPrompt string
// Tools is the allow-list of tool names this profile may see. nil means
// every registered tool; an empty non-nil slice means none.
Tools []string
// MaxToolSteps caps upstream completions per turn; <= 0 means
// DefaultMaxToolSteps.
MaxToolSteps int
// FinalSynthesisNudge overrides DefaultFinalSynthesisNudge.
FinalSynthesisNudge string
}
Profile is one chat surface: a system prompt, the tools it may see and the budget it runs under. Applications define as many as they have surfaces (a consumer assistant, an operator copilot, a report writer) and select one per turn via ChatInput.Profile.
func (Profile) Fingerprint ¶
Fingerprint is the content hash of the stable system prompt — the unit of prompt copy whose change is a prompt regression. The eval harness pins it so a score move can be attributed to a prompt edit rather than a tool or data change.
type Provider ¶
type Provider interface {
Name() string
Model() string
Chat(ctx context.Context, in ChatInput) (*ChatOutput, error)
ChatStream(ctx context.Context, in ChatInput, emit EmitFn) error
}
Provider is a model backend capable of a tool-use conversation loop. Every provider sees the same tool.Registry and Profile; the only difference is the wire protocol framing.
type Signature ¶
type Signature struct {
// Kind labels the figure class ("money", "percent", …); reported on
// Flag and used to look up KindGrounding.
Kind string
// Pattern matches the span to redact. Keep it tight: the whole match is
// replaced by the placeholder.
Pattern *regexp.Regexp
// Placeholder overrides Guard.Placeholder for this signature.
Placeholder string
}
Signature is one regulated-figure detector.
func DefaultSignatures ¶
func DefaultSignatures() []Signature
DefaultSignatures returns the generic detector set: currency amounts and percentages. Applications add domain signatures (durations, rates, identifiers) on top.
type Skill ¶
type Skill struct {
// Name identifies the skill: the frontmatter `name`, or the directory
// name when the frontmatter omits it.
Name string
// Description says what the skill does and when to use it. It is the
// only text the model reads before deciding to load the skill.
Description string
// License, Compatibility and Metadata are the optional frontmatter
// fields of the same names. Compatibility is shown to the model with
// the instructions; License and Metadata are for the application.
License string
Compatibility string
Metadata map[string]string
// AllowedTools is the experimental `allowed-tools` field: tools the
// skill expects to run without asking. dialogram records it and does
// not act on it; approval policy stays with the interceptors.
AllowedTools []string
// Body is the markdown after the frontmatter: the instructions.
Body string
// Dir is the skill directory inside the file system the skill was
// loaded from. Empty for a skill built in code.
Dir string
// Resources lists the bundled files the model may read, relative to
// Dir and sorted. SKILL.md, hidden files and symlinks are excluded.
Resources []string
// Diagnostics lists the problems found while loading that did not stop
// the skill from loading: specification violations, and bundled files
// beyond the readable limit. Empty for a spec-clean skill.
Diagnostics []string
// contains filtered or unexported fields
}
Skill is one Agent Skills package (https://agentskills.io/specification): a directory holding a SKILL.md, which is YAML frontmatter followed by markdown instructions, plus any bundled files (scripts/, references/, assets/, …).
dialogram follows the specification's three tiers of progressive disclosure. The catalog in the stable system prompt carries Name and Description only. The model loads Body through the load_skill tool when a task matches, and reads bundled files one at a time through the same tool when the instructions point at them.
func LoadSkill ¶
LoadSkill loads the one skill in dir: its SKILL.md and the list of its bundled files. See LoadSkills for what is lenient and what is fatal.
func ParseSkillMarkdown ¶
ParseSkillMarkdown parses one SKILL.md source with no directory around it: the name cannot fall back to a directory name and is required, there is no directory to match, and the skill has no bundled files. The other rules are those of LoadSkills.
type SkillLibrary ¶
type SkillLibrary struct {
// contains filtered or unexported fields
}
SkillLibrary holds the registered skills keyed by name, in registration order for deterministic listing.
func LoadSkills ¶
func LoadSkills(fsys fs.FS, root string) (*SkillLibrary, error)
LoadSkills discovers and loads every skill under root in fsys. A directory that contains a SKILL.md is one skill; its subdirectories are bundled files, not further skills. Discovery walks in lexical order, skips hidden directories and node_modules, follows a symlinked skill directory one level, and looks at most four levels below root. root may itself be a skill directory. Point it at a shared location such as .agents/skills to use the skills other clients install.
Loading is lenient where the specification's client guide says it should be. A name that breaks the naming rules or does not match its directory, an over-long field or a field the specification does not define is recorded in Skill.Diagnostics, logged, and the skill still loads. Problems that leave a skill unusable fail the whole load, so a server cannot start with a skill silently missing: frontmatter that does not parse, a missing description, or two skills with the same name. To skip broken skills instead, call LoadSkill per directory and pass the ones that load to NewSkillLibrary. ValidateSkills applies the strict rules.
func NewSkillLibrary ¶
func NewSkillLibrary(skills ...*Skill) (*SkillLibrary, error)
NewSkillLibrary builds a library from skills built in code or loaded one at a time with LoadSkill. A skill without a name or a description, or two skills with the same name, are errors.
func (*SkillLibrary) Get ¶
func (l *SkillLibrary) Get(name string) (*Skill, bool)
Get returns the skill with the given name, if registered. Nil-safe.
func (*SkillLibrary) Len ¶
func (l *SkillLibrary) Len() int
Len reports the number of registered skills. Nil-safe.
func (*SkillLibrary) List ¶
func (l *SkillLibrary) List() []*Skill
List returns the registered skills in registration order. Nil-safe.
func (*SkillLibrary) Names ¶
func (l *SkillLibrary) Names() []string
Names returns the registered skill names in registration order. Nil-safe.
type StreamEvent ¶
type StreamEvent struct {
Type string `json:"type"`
Delta string `json:"delta,omitempty"`
Name string `json:"name,omitempty"`
Label string `json:"label,omitempty"`
ToolUseID string `json:"tool_use_id,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
Output string `json:"output,omitempty"`
Message string `json:"message,omitempty"`
MessageID string `json:"message_id,omitempty"`
InputTokens int `json:"input_tokens,omitempty"`
OutputTokens int `json:"output_tokens,omitempty"`
// CacheReadTokens / CacheCreationTokens carry the running prompt-cache
// counters on usage events, parallel to InputTokens / OutputTokens.
CacheReadTokens int `json:"cache_read_tokens,omitempty"`
CacheCreationTokens int `json:"cache_creation_tokens,omitempty"`
Model string `json:"model,omitempty"`
Provider string `json:"provider,omitempty"`
Breakdown *TokenBreakdown `json:"breakdown,omitempty"`
Turn *Turn `json:"turn,omitempty"`
// Kind qualifies waiting_for_user: PauseKindHITL, PauseKindHITLChoice,
// PauseKindHITLForm, PauseKindApproval or PauseKindCustom.
Kind string `json:"kind,omitempty"`
// Options and Multiple are populated for PauseKindHITLChoice so a client
// can render the option buttons without re-parsing Input.
Options []ChoiceOption `json:"options,omitempty"`
Multiple bool `json:"multiple,omitempty"`
// GenUI carries the structured UI payload for gen_ui events.
GenUI json.RawMessage `json:"gen_ui,omitempty"`
// Request is the tool.InputRequest of a PauseKindToolInput pause.
Request json.RawMessage `json:"request,omitempty"`
}
StreamEvent is the unified event type emitted during a streaming chat. Providers translate their upstream formats into these events.
meta — stream metadata (Provider, Model, MessageID)
text — incremental text delta (Delta)
tool_call — a tool is about to be invoked (Name, Input, ToolUseID)
tool_result — a tool finished (Name, Input, Output, ToolUseID)
gen_ui — an inline UI payload to render (GenUI); emitted by the
streaming layer, never by providers
usage — running token usage (InputTokens, OutputTokens,
CacheReadTokens, CacheCreationTokens, Breakdown)
turn — a completed Turn (assistant or tool) ready to persist
as block IR. Internal boundary event: the streaming
layer filters these off the wire.
waiting_for_user — the loop paused for human input. Terminal for this
producer; no "done" follows. Kind distinguishes a
free-text pause, a choice, a form, an interceptor
approval, or a custom pause tool.
done — the assistant finished its turn
error — a terminal error (Message)
type TokenBreakdown ¶
type TokenBreakdown struct {
System int `json:"system"`
Tools int `json:"tools"`
History int `json:"history"`
UserPrompt int `json:"user_prompt"`
ToolCalling int `json:"tool_calling"`
Total int `json:"total"`
}
TokenBreakdown estimates how the input-token budget of a request is split across its semantic segments. Providers only return a single prompt token count, so each assembled segment is char-counted and approximated. The absolute numbers are rough; the ratios are what is useful for debugging "why is this request expensive?".
type ToolTrace ¶
type ToolTrace struct {
Name string `json:"name"`
Input json.RawMessage `json:"input"`
Output string `json:"output"`
}
ToolTrace is one executed tool call: its name, raw input and serialised output.
type Turn ¶
Turn is one role-scoped sequence of blocks. Role is one of:
- "user" — user-sent content (BlockText and BlockImage)
- "assistant" — model output (may mix BlockText and BlockToolUse)
- "tool" — tool execution results (Blocks are all BlockToolResult, one per BlockToolUse in the immediately preceding assistant turn)
A "tool" turn may aggregate results from multiple tool_use blocks in the preceding assistant turn. Translators that need one message per result (OpenAI) expand; translators that pack them into one user message (Anthropic) wrap.
func AnswerPause ¶
AnswerPause resumes a conversation that paused on the tool call toolUseID. It returns turns with that call answered by result, and with every other call of the same assistant turn that has no result yet answered by NotRunResultJSON. Run the next turn on what it returns.
The other calls matter. The loop surfaces one pause at a time, and it runs nothing in a turn it pauses for approval, so a paused turn can hold calls besides the one the user is asked about: a second pause tool, or the other tools of a turn in which one needed approval. Both providers reject a history in which a tool call has no result, so answering only the paused call fails the next request. The model reads the not-run results and can make those calls again; they then pass the interceptors like any other call.
The results go into the tool turn right after the paused assistant turn, completing one already there, so turns appended since then stay valid. turns is not modified. ErrNotPending wraps the error for a call that is unknown or already answered.
func CloseDangling ¶
CloseDangling makes a checkpointed conversation resumable on either provider after a crash: every tool_use that never received a tool_result is paired with a synthetic RUN_INTERRUPTED soft failure, so the next request does not carry an unanswered call (both wire formats reject that). The synthetic results are appended to the tool turn that follows the owning assistant turn, or a new tool turn is inserted when there is none. The input is not mutated; when nothing is dangling it is returned as is.
The built-in human-in-the-loop tools are left pending: an unanswered request_user_input is a legitimate pause the application resolves with the user's answer, not a lost result. Use Config.CloseDangling to extend that exemption to Config.PauseTools.
func MessagesToTurns ¶
func MessagesToTurns(msgs []ChatMessage) []Turn
MessagesToTurns lifts the flat ChatInput.Messages shape into Turns: each message becomes one turn with a single text block. Empty content is preserved rather than filtered so translators produce the same wire bytes a caller would get from sending the message directly.
func UserTurnBlocks ¶
UserTurnBlocks builds a user turn from explicit blocks — text and image blocks in any order. The translators render a turn that carries an image as a content array; a text-only turn keeps the shape UserTurn produces.