agent

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 31 Imported by: ? modules, 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 agent is the agent loop: an own ReAct loop on eino ToolCallingChatModel that streams AG-UI events and checkpoints messages.

Index

Constants

View Source
const (
	MsgModelError = "The AI model could not answer. Please try again in a moment."
	MsgInternal   = "An internal error occurred."
)

Messages sent to clients (RUN_ERROR, run.error): never raw provider errors or hostnames.

View Source
const (

	// SummaryHeading introduces the compaction summary in the system prompt.
	SummaryHeading = prompts.SummaryHeading
	// TriggerAuto / TriggerManual are work.compaction triggers.
	TriggerAuto   = "auto"
	TriggerManual = "manual"
	// FilesHeading introduces the list of files written so far at the end of a summary. Summaries already stored
	// carry it, so it must not change.
	FilesHeading = "Files written or edited so far (still in /workspace unless deleted later):"
	// OneQuestionResult answers a second ask_user call of the same step.
	OneQuestionResult = "Error: ask only one question at a time; wait for the answer to the first one."
)
View Source
const (

	// StreamRetriedResult is the TOOL_CALL_RESULT of a call announced by an attempt that is retried.
	StreamRetriedResult = "(stream interrupted, retrying)"
	// StreamFailedResult is the TOOL_CALL_RESULT of a call announced by the last, failed attempt.
	StreamFailedResult = "(stream interrupted)"

	// Messages of the v3 RUN_ERROR codes (user-facing, never provider details).
	MsgModelTimeout  = "The AI model did not respond in time. Please try again."
	MsgRateLimited   = "The AI model is overloaded right now (rate limited). Please try again in a few minutes."
	MsgContentFilter = "The AI provider's content filter stopped the answer. Rephrase the request and try again."
	MsgEmptyAnswer   = "The AI model returned an empty answer. Please try again or rephrase the request."
)

Harness v3 §1: model call budgets, retries and the texts of their outcomes.

View Source
const (
	// OutputLimitResult answers every tool call of a message cut by the output limit (finish_reason=length).
	OutputLimitResult = "" /* 150-byte string literal not displayed */
	// ContinueAfterLengthNote follows a text answer cut by the output limit (at most maxContinuations per run).
	ContinueAfterLengthNote = "" /* 130-byte string literal not displayed */
	// ContentFilterResult answers the tool calls announced by an answer the content filter stopped.
	ContentFilterResult = "(stopped by the content filter)"
)

Harness v3 §1: finish_reason handling.

View Source
const AlternationGuardResult = "" /* 167-byte string literal not displayed */

AlternationGuardResult replaces the 6th call of an A-B-A-B-A-B alternation (%s, %s: the tools).

View Source
const ConsecutiveErrorsNote = "" /* 206-byte string literal not displayed */

ConsecutiveErrorsNote is appended after failedCallsNote failed tool calls in a row.

View Source
const CustomVerification = "work.verification"

CustomVerification is the CUSTOM event of a checker result (and of an answer's verification summary).

View Source
const EmptyAnswerNudge = "You stopped without answering. Continue the task, or give the user a short summary of what you did and found."

EmptyAnswerNudge is given (once per run) when the model stops without text or tool calls.

View Source
const ImageAttachmentKey = "work.attachment"

ImageAttachmentKey tags an attachment's image part (Extra) with the attachment's artifact id, so its stub names the right file.

View Source
const LoopGuardResult = "" /* 213-byte string literal not displayed */

LoopGuardResult replaces the 3rd consecutive identical tool call (%s: the tool name).

View Source
const MaxRequestImages = 6

MaxRequestImages is the most images one model request carries (attachments included: artifacts.Images attaches at most this many).

View Source
const MsgStepLimitNoDeliverable = "The agent reached its step limit before producing a deliverable; its last answer is partial."

MsgStepLimitNoDeliverable is the RUN_ERROR max_steps of a run that used all its steps without producing the file it was meant to write (its last answer is kept).

View Source
const OutputsDir = "/workspace/outputs/"

OutputsDir holds the deliverables.

View Source
const PartialDeliverableReminder = "" /* 368-byte string literal not displayed */

PartialDeliverableReminder is given once, lateSteps() steps before the step limit, to a run with a sandbox that has not written any deliverable yet (%d: the steps left). Round 3 (A2).

View Source
const PlanModePrompt = `` /* 544-byte string literal not displayed */

PlanModePrompt is the system-prompt section of a plan run.

View Source
const RehydrationTag = "context_after_compaction"

RehydrationTag wraps the context restored after a compaction.

View Source
const RenderFailedPrefix = "render failed: "

RenderFailedPrefix starts the unverified reason of a deliverable whose view_file failed after its last change (round 3, A5): the StopGuard accepts the stop, the answer must say the file could not be viewed.

View Source
const RepeatedErrorNote = "" /* 182-byte string literal not displayed */

RepeatedErrorNote is appended to a tool result whose error already occurred twice in this task.

View Source
const RepeatedResultNote = "" /* 248-byte string literal not displayed */

RepeatedResultNote is appended to a call that returned the same result for the repeatedResultNote-th time in this task (%d: the count): a re-reading cycle the consecutive guards do not see (round 3, A2).

View Source
const SteerPrefix = "[The user added while you were working]: "

SteerPrefix prefixes steer messages in the model history.

View Source
const StepLimitNudge = "You have reached the step limit; answer with what you have."

StepLimitNudge is appended on the last allowed step.

View Source
const TooManyErrorsNote = "" /* 137-byte string literal not displayed */

TooManyErrorsNote ends a run stuck on failing calls: the next answer is forced without tools.

View Source
const ViewFailedNote = "" /* 175-byte string literal not displayed */

ViewFailedNote follows a failed view_file of a deliverable.

Variables

This section is empty.

Functions

func AuthorTag

func AuthorTag(login, kind, onBehalfOf string) string

AuthorTag is the "[alice] " prefix that tells the model who wrote a user message ("" when the author is unknown).

func BuildHistory

func BuildHistory(msgs []*store.Message) []*ai.Message

BuildHistory turns persisted messages into a provider-valid model history: reasoning rows are skipped, steers are prefixed, every tool call is followed by its result (found by tool call id, wherever it was stored: an ask_user answer arrives after the steers of its run) or a synthetic "interrupted" result, orphan results are dropped, and tool outputs older than the last two assistant turns are cut to their head and tail. Each message carries its store position.

func BuildHistoryWith

func BuildHistoryWith(msgs []*store.Message, opts HistoryOptions) []*ai.Message

BuildHistoryWith is BuildHistory with options.

func CapOutput

func CapOutput(s string, max int) string

CapOutput keeps the head and tail of s within max characters with a marker.

func FenceData

func FenceData(tag, text string) string

FenceData wraps untrusted text in <tag>…</tag>, escaping every opening or closing form of the tag inside it (any case, whitespace around "/") so the text cannot close the block nor open a nested one.

func MaskFromSetting

func MaskFromSetting(f float64) float64

MaskFromSetting maps COMPACTION_MASK_FROM_FRACTION to Harness.MaskFromFraction (0: mask from the first step, as in v3).

func MaskSetting

func MaskSetting(n int) int

MaskSetting maps COMPACTION_KEEP_RECENT_TOOL_RESULTS to Harness.KeepRecentToolResults (0: no masking).

func MaskStub

func MaskStub(tool, content string) string

MaskStub is the model's view of a masked tool result: "[<tool> result, <size>, exit <code> — hidden to save context; full output in <outputPath>]" (exit and path only when the result reports them). It never suggests running the call again: commands are not always idempotent.

func ReportUntrusted

func ReportUntrusted(ctx context.Context)

ReportUntrusted is called by a prompt section that put untrusted text (an attached user or global skill) into the system prompt: the run's context is then untrusted from its start, so memory writes are only proposed (A-11).

func StepRetriesSetting

func StepRetriesSetting(n int) int

StepRetriesSetting maps LLM_STEP_RETRIES to Agent.StepRetries (0 retries: -1).

func UsageOf

func UsageOf(model string, msg *ai.Message) agui.Usage

UsageOf is the usage a model call reported (zero when none), for counting auxiliary calls (title, goal judge) in the run's usage.

Types

type Agent

type Agent struct {
	Models             llm.Factory
	Tools              tools.Provider
	Store              MessageStore
	Steers             SteerSource
	MaxSteps           int
	MaxToolOutputChars int
	// RetryBackoff is the first model retry delay (doubles each retry, ±50 % jitter).
	RetryBackoff time.Duration
	// ModelTimeout bounds the wait for the first chunk of a model call (LLM_TIMEOUT_SECONDS; 0: 300 s).
	ModelTimeout time.Duration
	// StreamIdleTimeout bounds the gap between two chunks (LLM_STREAM_IDLE_SECONDS; 0: 90 s).
	StreamIdleTimeout time.Duration
	// CallCeiling bounds one model call whatever its stream sends
	// (LLM_CALL_MAX_SECONDS; 0: 20 min; ×2 at high, ×3 at xhigh effort). Round 3, N3.
	CallCeiling time.Duration
	// StepRetries is how often a failed model call is re-issued as a whole step
	// (LLM_STEP_RETRIES; 0: 3; < 0: never).
	StepRetries int
	// Sleep waits between retries (nil: a timer; tests record the delays).
	Sleep func(ctx context.Context, d time.Duration) error
	// SpillChars: a tool output longer than this is written in full to
	// /workspace/.work/tool-output/<toolCallId>.txt and the model gets its head
	// and tail (AGENT_TOOL_OUTPUT_SPILL_CHARS; 0: 20000).
	SpillChars int
	Now        func() time.Time
	// Harness holds the harness v2 options (prompt sections, tool hooks, images,
	// compaction, reasoning).
	Harness Harness
}

Agent runs the loop.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, in Input, w eventlog.Writer) (Result, error)

Run executes the loop. It returns ctx.Err() when cancelled, *Error for run failures.

type AnswerChecker

type AnswerChecker interface {
	CheckAnswer(ctx context.Context, run *store.Run, answer string, emit func(agui.Event) error) string
}

AnswerChecker reviews the final answer of a run (not cancelled, not failed, not waiting for the user) that still has steps left. A non-empty note is given to the model as a user-side message for one corrective step (at most once per run; the note is not persisted). emit writes events of existing types.

type ApprovalSource

type ApprovalSource interface {
	ResumedApproval(ctx context.Context, runID string) (*store.Approval, error)
}

ApprovalSource returns the approval a run was created to decide (or that its message cancelled); nil when none.

type BeforeToolHook

type BeforeToolHook interface {
	// ctx is the run's: Stop cancels a decision that needs the sandbox (round 3, N5).
	NeedsApproval(ctx context.Context, run *store.Run, toolName, arguments string) bool
	Pause(ctx context.Context, run *store.Run, tc ai.ToolCall) (*tools.Interrupt, error)
}

BeforeToolHook runs before a tool call executes (interactive approvals). NeedsApproval must not have side effects (it also decides which later calls of a step wait for an earlier decision); Pause records the pending approval and returns the interrupt that ends the run before the call runs.

type CheckCommander

type CheckCommander interface {
	CheckCommand(path string) string
}

CheckCommander is optionally implemented by a Checker: the shell command that checks a file (named in reminders, so the model can run it itself).

type CheckCompleter

type CheckCompleter interface {
	Complete(ctx context.Context, run *store.Run, path string, base CheckResult) CheckResult
}

CheckCompleter is optionally implemented by a Checker whose own check does more than the file's checker command (CheckCommand): Complete returns the runtime's result for p given base, the result of that command run by the model on p's final content (final review of round 3, F1: a deck's baseline and a document's page citations are still checked). A Checker without it takes base as its result.

type CheckResult

type CheckResult struct {
	Path    string `json:"path"`
	Checker string `json:"checker"`
	OK      bool   `json:"ok"`
	// Failed: the checker could not run (exit 1, timeout, skill missing): the
	// file is unverified, not known bad.
	Failed   bool   `json:"failed,omitempty"`
	Summary  string `json:"summary"`
	NextStep string `json:"nextStep,omitempty"`
}

CheckResult is one checker result.

func ParseCheckerOutput

func ParseCheckerOutput(checker, stdout string, exitCode int) (r CheckResult, found bool)

ParseCheckerOutput reads a checker run: the last checker-contract JSON object on stdout ({ok, file, checks, next_step?}) and the exit code (0 ok, 2 not ok, 1 or other: the checker could not run). found is false when stdout holds no contract object.

type Checker

type Checker interface {
	// CheckerFor names the checker of a file ("" when its type has none).
	CheckerFor(path string) string
	// Check runs it in the run's sandbox.
	Check(ctx context.Context, run *store.Run, path string) CheckResult
}

Checker runs the checker of a deliverable (verify.Verifier).

type CompactionStore

type CompactionStore interface {
	RecordCompaction(ctx context.Context, c store.Compaction) error
}

CompactionStore records completed compactions.

type Deliverable

type Deliverable struct {
	Path string
	// Checker names the checker that ran last ("" when none ran).
	Checker string
	// OK is the checker's verdict after the file's last change (nil: not checked since).
	OK      *bool
	Summary string
}

Deliverable is a file the run produced with its last checker result (harness v3 §4, provided by the verification hooks).

func DeliverablesSince

func DeliverablesSince(msgs []*store.Message, since time.Time) []Deliverable

DeliverablesSince are the deliverables changed in the turns that started at or after since (a goal's turns: since its creation), like TurnDeliverables; the current turn when no turn started since then.

func TurnDeliverables

func TurnDeliverables(msgs []*store.Message) []Deliverable

TurnDeliverables are the deliverables changed in the current turn of a thread's messages (the verification state a run rebuilds), sorted by path, with their last checker result after their last change.

type DeliverableSource

type DeliverableSource interface {
	Deliverables(ctx context.Context, run *store.Run) []Deliverable
}

DeliverableSource lists a run's deliverables (the verification hooks implement it).

type Error

type Error struct {
	Code    string
	Message string
	// Detail is logged, never sent to clients.
	Detail string
	// contains filtered or unexported fields
}

Error is a run failure with an AG-UI RUN_ERROR code.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying model error, if any.

type Harness

type Harness struct {
	// Sections extend the system prompt (skills, file references, memory, goal,
	// plan instructions…), in order.
	Sections []PromptSection
	// Context sections are dynamic (goal, recalled memories): rendered in the
	// prompt's final <context> block, after the static sections.
	Context []PromptSection
	// Tail sections change from run to run of a thread (the goal's turn
	// counter): rendered once per run into a reminder at the end of every
	// request, after the history, so the system prompt and the history before
	// it stay a cacheable prefix across runs (review round 1).
	Tail []PromptSection
	// StepNotes add mid-run notes before a step's model call (see StepNote): news the prompt, rendered at
	// the start of the run, could not carry.
	StepNotes []StepNote
	// PromptVariant is the prompt variant of a model (LLM_PROMPT_VARIANTS;
	// nil: prompts.Default).
	PromptVariant func(model string) string
	// ToolHooks observe tool results (artifact snapshots).
	ToolHooks []ToolHook
	// RunStart hooks run before the first step of every run but compactions
	// (the workspace checkpoint "Before AI turn").
	RunStart []RunStartHook
	// Images adds attached images as image parts for vision models.
	Images ImageAttacher
	// Checker runs the checker of a deliverable changed by a tool call (harness
	// v3 §4: post-write validation, verification StopGuard, metadata.verification).
	Checker Checker
	// Vision reports models that accept images (LLM_VISION_MODELS): the images
	// tools attach (tools.AttachImage: read_file, view_file) only reach those.
	Vision func(model string) bool
	// Summaries enables persisted compaction summaries.
	Summaries SummaryStore
	// Compactions records completed compactions (the UI's divider after a reload).
	Compactions CompactionStore
	// ContextWindow is a model's window in tokens (default 128000).
	ContextWindow func(model string) int
	// CompactionThreshold is the share of the window that triggers compaction
	// (0: window − OutputReserve, harness v3 §5).
	CompactionThreshold float64
	// Plans and Deliverables feed the context restored after a compaction
	// (harness v3 §5; nil: the plan is read from the history, no deliverables).
	Plans        PlanSource
	Deliverables DeliverableSource
	// Spill writes tool outputs longer than Agent.SpillChars to a workspace file (nil: they are cut).
	Spill tools.OutputSpiller
	// KeepRecentToolResults: tool results older than the newest K are masked in
	// the model input (COMPACTION_KEEP_RECENT_TOOL_RESULTS; 0: 6; < 0: no masking).
	KeepRecentToolResults int
	// MaskFromFraction: masking starts only once the prompt passes this share of
	// the window (COMPACTION_MASK_FROM_FRACTION; 0: 0.5; < 0: from the first
	// step, the v3 batches of min(4, keep)). Round 3 (A1).
	MaskFromFraction float64
	// OutputReserve is the part of a model's window kept free below the
	// compaction trigger: max output tokens + 20k (nil: 36000).
	OutputReserve func(model string) int
	// CompactionModel summarizes old context (default: the run's model).
	CompactionModel string
	// SupportsReasoning reports models that accept reasoningEffort.
	SupportsReasoning func(model string) bool
	// ReasoningEffort maps a run's effort to the one sent to its model (the
	// nearest the model accepts, "" for none; nil: sent as is). A-29.
	ReasoningEffort func(model, effort string) string
	// PromptCacheKey reports models whose calls send prompt_cache_key (the thread
	// id) so the provider routes a thread's calls to the same prompt cache.
	PromptCacheKey func(model string) bool
	// ReasoningPassback reports models whose assistant messages carry their
	// reasoning_content back, within and across runs (LLM_REASONING_PASSBACK_MODELS).
	ReasoningPassback func(model string) bool
	// Answers reviews the final answer of a run that still has steps left
	// (dangling file links); a note gets one corrective step.
	Answers AnswerChecker
	// BeforeTool gates tool calls before they run (interactive approvals);
	// Approvals gives a resumed run its decided approval.
	BeforeTool []BeforeToolHook
	Approvals  ApprovalSource
}

Harness holds the harness v2 options of the agent (all optional).

type HistoryOptions

type HistoryOptions struct {
	// Reasoning gives every assistant message the reasoning stored before it in
	// its run (reasoning passback, harness v3 §5) instead of dropping it.
	Reasoning bool
}

HistoryOptions tune BuildHistoryWith.

type ImageAttacher

type ImageAttacher interface {
	AttachImages(ctx context.Context, run *store.Run, history []*ai.Message) []*ai.Message
}

ImageAttacher adds attached images as image parts for vision models.

type Input

type Input struct {
	Run       *store.Run
	FirstName string
	// Sandbox is set by the agent before the prompt sections run: the run has sandbox tools.
	Sandbox bool
	// Variant is the run's prompt variant (prompts.Default, prompts.Legacy…),
	// set by the agent before the prompt sections run.
	Variant string
}

Input is one run to execute.

type MessageStore

type MessageStore interface {
	ListMessages(ctx context.Context, threadID string) ([]*store.Message, error)
	AppendMessages(ctx context.Context, msgs ...*store.Message) error
}

MessageStore is the subset of store.Store used by the agent.

type PlanSource

type PlanSource interface {
	GetThread(ctx context.Context, login, id string) (*store.Thread, error)
}

PlanSource reads a thread's plan (store.Store implements it).

type PromptSection

type PromptSection func(ctx context.Context, in Input) string

PromptSection adds a section to a run's system prompt ("" adds nothing). Sections are appended in order after the base prompt; in.Variant tells which prompt variant they render for (see prompts).

func Part

Part keeps a section only in the variants that include the optional part p.

type Result

type Result struct {
	Usage []agui.Usage
	// Interrupt is set when the run ended waiting for the user (ask_user).
	Interrupt *tools.Interrupt
}

Result is a successful run outcome.

type RiskJudge

type RiskJudge interface {
	Risky(ctx context.Context, run *store.Run, toolName, arguments string) bool
}

RiskJudge is implemented by BeforeToolHooks that can tell whether a call would need approval in interactive mode, whatever the run's current mode is. Once a step has a pending approval, later calls it judges risky wait behind that approval, so a switch to automatic mid-step never lets them run before the paused call. Like NeedsApproval it must not have side effects.

type RunStartHook

type RunStartHook interface {
	BeforeRun(ctx context.Context, run *store.Run)
}

RunStartHook runs at the start of every run except compactions, before its first model call; it must not fail the run (errors are its own to log).

type SteerSource

type SteerSource interface {
	DrainSteers(ctx context.Context, runID string) ([]queue.Steer, error)
	FinalizeSteers(ctx context.Context, runID string) ([]queue.Steer, error)
	ReopenSteers(ctx context.Context, runID string) error
}

SteerSource drains steer messages of a run. FinalizeSteers atomically stops accepting steers (PushSteer then fails) and drains; ReopenSteers accepts again.

type StepNote

type StepNote func(ctx context.Context, in Input) string

StepNote adds a note to the model's next request when it has news for the model mid-run (a sandbox started by the run holds project skills the prompt could not list): "" adds nothing. The notes of a step are appended to the in-run history as one <system-reminder> user message, before the step's model call (not persisted: the next run's prompt sections see the same facts). A hook returns each note once.

type SummaryStore

type SummaryStore interface {
	GetThreadSummary(ctx context.Context, threadID string) (store.ThreadSummary, error)
	SetThreadSummary(ctx context.Context, threadID string, s store.ThreadSummary) error
}

SummaryStore persists the thread's compaction summary.

type ToolDenier

type ToolDenier interface {
	Denial(ctx context.Context, run *store.Run, toolName, arguments string) string
}

ToolDenier is implemented by BeforeToolHooks that can refuse a call outright (a permission policy): a non-empty text is the call's error result and the call is not run, whatever the interaction mode. Like NeedsApproval it must not have side effects.

type ToolHook

type ToolHook interface {
	AfterTool(ctx context.Context, run *store.Run, toolCallID, toolName string) map[string]any
}

ToolHook observes every tool result (not cancelled calls, not the ask_user interrupt). It runs after the call's TOOL_CALL_RESULT; its events go through tools.AfterResult(ctx, …) — the queue the tools themselves use — so they are written right after the result and before STEP_FINISHED. The metadata it returns is stored on the tool message (e.g. metadata.artifacts).

type VerificationStore

type VerificationStore interface {
	AppendToolVerification(ctx context.Context, threadID, toolCallID string, items []any) error
}

VerificationStore persists the checks run after their tool call (store.HarnessStore.AppendToolVerification), optionally implemented by Agent.Store.

Jump to

Keyboard shortcuts

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