agent

package
v0.16.7 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultMaxTurns         = 400
	DefaultMaxParallelTools = 8
	DefaultToolTimeout      = 10 * time.Minute

	DefaultContextWindow = 400_000

	DefaultReserveTokens = 32_000
)

Variables

View Source
var ErrEmptyInput = errors.New("agent input is empty")

ErrEmptyInput means Send was called without any content.

View Source
var ErrMaxTurnsExceeded = errors.New("agent: internal turn-loop safety bound exceeded — likely a runaway tool-call cycle")
View Source
var ErrTurnInProgress = errors.New("agent turn already in progress")

ErrTurnInProgress means Send was called while another turn was active.

Functions

func ContextWindowFor added in v0.9.3

func ContextWindowFor(id string) int

func DefaultEffort added in v0.10.5

func DefaultEffort() string

DefaultEffort returns the reasoning effort requested via WINGMAN_EFFORT. Empty (or "auto") leaves the role-based default in place. Unrecognized values are ignored so a typo cannot silently pin an unexpected effort.

func DefaultModel added in v0.9.4

func DefaultModel() string

DefaultModel returns the model requested via environment; WINGMAN_MODEL takes priority over the OpenAI-standard OPENAI_DEFAULT_MODEL.

func DefaultPlanEffort added in v0.11.2

func DefaultPlanEffort() string

DefaultPlanEffort returns the reasoning effort for plan mode requested via WINGMAN_EFFORT_PLAN; empty uses the role-based default.

func DefaultPlanModel added in v0.11.2

func DefaultPlanModel() string

DefaultPlanModel returns the model for plan mode; empty selects the largest available model automatically.

func DefaultUtilityModel added in v0.11.2

func DefaultUtilityModel() string

DefaultUtilityModel returns the model for internal utility calls (recaps, compaction summaries); empty selects the smallest available automatically.

func EmitStreamEvent added in v0.12.9

func EmitStreamEvent(ctx context.Context, event StreamEvent) bool

EmitStreamEvent synchronously publishes a lifecycle event to the sink in ctx. It reports whether the consumer implements that exact event; agents must not retry after visible partial output unless Reset is implemented.

func InputIDFromContext added in v0.16.4

func InputIDFromContext(ctx context.Context) string

func OutputSchemaFromContext added in v0.12.18

func OutputSchemaFromContext(ctx context.Context) (map[string]any, bool)

OutputSchemaFromContext returns the turn's requested structured output.

func SandboxDisabled added in v0.10.6

func SandboxDisabled() bool

func WithInputID added in v0.16.4

func WithInputID(ctx context.Context, id string) context.Context

WithInputID correlates accepted user input with its retained conversation message. This is local metadata, never part of a model provider's payload.

func WithOutputSchema added in v0.12.18

func WithOutputSchema(ctx context.Context, schema map[string]any) context.Context

WithOutputSchema requests structured output for a turn. An empty schema uses the provider's native JSON-object mode; a non-empty schema uses strict JSON Schema output. A nil schema is treated as no structured-output request.

func WithStreamEventHandlers added in v0.12.9

func WithStreamEventHandlers(ctx context.Context, handlers StreamEventHandlers) context.Context

WithStreamEventHandlers installs synchronous lifecycle operations for an Agent.Send consumer. Handlers must return quickly.

Types

type Agent

type Agent struct {
	*Config

	// Events is the canonical append-only runtime ledger. Messages is its
	// materialized conversation projection and remains exported for source
	// compatibility; provider context is maintained separately.
	Events   []RuntimeEvent
	Messages []Message
	Usage    Usage
	Revision uint64

	// Recorder is instance-scoped on purpose: derived subagent configs must not
	// accidentally append child events to their parent's journal.
	Recorder EventRecorder

	ContextRevision uint64
	// contains filtered or unexported fields
}

func (*Agent) ContextStats added in v0.11.2

func (a *Agent) ContextStats() ContextStats

func (*Agent) MessagesSnapshot added in v0.10.3

func (a *Agent) MessagesSnapshot() []Message

func (*Agent) QueueInput added in v0.10.9

func (a *Agent) QueueInput(input []Content) bool

QueueInput adds guidance to the active run. The agent consumes queued input at the next safe model boundary. It returns false when no run is active so callers can preserve the input as a normal follow-up instead.

func (*Agent) QueueInputWithID added in v0.16.4

func (a *Agent) QueueInputWithID(input []Content, id string) bool

func (*Agent) Recap added in v0.11.2

func (a *Agent) Recap(ctx context.Context) (string, error)

Recap produces a short user-facing briefing of the conversation so far, for returning to a resumed session.

func (*Agent) ReconcileInterrupted added in v0.15.8

func (a *Agent) ReconcileInterrupted(reason string) error

ReconcileInterrupted closes lifecycle entities that were open when the previous process stopped. It never retries work. An open non-read-only tool is explicitly recorded as uncertain because its side effect may have happened before the crash.

func (*Agent) Restore added in v0.15.8

func (a *Agent) Restore(state State) error

Restore replaces all runtime state from a snapshot. When Events is present, every projection is rebuilt from it and duplicated snapshot fields are ignored. Event-less state is treated as an in-memory legacy snapshot.

func (*Agent) Running added in v0.11.2

func (a *Agent) Running() bool

Running reports whether a turn is currently active.

func (*Agent) Send

func (a *Agent) Send(ctx context.Context, input []Content) (iter.Seq2[Message, error], error)

Send starts exactly one turn. It never queues implicitly: callers that want to guide the active turn must use QueueInput, while FIFO follow-ups belong in a caller-owned session orchestrator. Setup errors are returned immediately; failures after the turn starts are yielded by the returned stream.

func (*Agent) StateSnapshot added in v0.10.3

func (a *Agent) StateSnapshot() State

func (*Agent) StateVersion added in v0.12.9

func (a *Agent) StateVersion() (messageCount int, revision uint64)

StateVersion returns retained-history metadata without cloning messages.

func (*Agent) UsageSnapshot added in v0.10.3

func (a *Agent) UsageSnapshot() Usage

type Config

type Config struct {

	// Telemetry instruments agent, model, and tool operations. DefaultConfig
	// initializes it when standard OTEL exporter variables are present. Library
	// callers may inject a separately configured pipeline instead.
	Telemetry *telemetry.Telemetry

	Model        func() string
	Effort       func() string
	Tools        func() []tool.Tool
	Instructions func() string

	// RoleModel resolves "main", "plan", and "utility" role models. An empty
	// role names the currently inherited model and is used for effort clamping.
	// ok=false or an empty ID keeps the inherited model. Nil disables role
	// overrides.
	RoleModel func(role string) (ModelOption, bool)

	// CacheKey routes provider-side prompt caching; keep it stable per
	// conversation (e.g. the session ID) to maximize prefix-cache hits.
	CacheKey string

	Hooks hook.Hooks

	// MaxTurns caps successful model invocations in one Send run. Stream
	// retries and tool calls do not consume turns. Zero uses the default;
	// negative disables the safety bound.
	MaxTurns int

	// MaxParallelTools bounds concurrently executing read-only tool calls.
	// Zero uses the default; negative allows the whole emitted batch.
	MaxParallelTools int

	// ToolTimeout is a hard ceiling on every tool call. When zero, tools may
	// extend the default via tool.Tool.Timeout; negative disables deadlines.
	ToolTimeout time.Duration

	ContextWindow int

	ReserveTokens int
	// contains filtered or unexported fields
}

func DefaultConfig

func DefaultConfig() (*Config, error)

func (*Config) Derive added in v0.6.2

func (c *Config) Derive() *Config

func (*Config) Generate added in v0.14.9

func (c *Config) Generate(ctx context.Context, opts GenerateOptions) (GenerateResult, error)

Generate runs one stateless Responses API request. A non-nil OutputSchema requests strict JSON schema output; callers remain responsible for decoding and semantically validating that JSON.

func (*Config) Models added in v0.6.9

func (c *Config) Models(ctx context.Context) ([]ModelInfo, error)

func (*Config) Utility added in v0.11.4

func (c *Config) Utility(ctx context.Context, instructions, input string) (string, error)

Utility runs a one-shot completion on the utility model (falling back to the main model) and credits its token usage to the session through the context's usage sink. It backs internal helpers such as fetch page extraction.

type Content

type Content struct {
	Text string `json:"text,omitempty"`
	// TextID is source-local identity used to reconcile streamed and retained
	// UI content. It is metadata, not a provider payload to replay in requests.
	TextID string `json:"text_id,omitempty"`

	Refusal string `json:"refusal,omitempty"`

	// Hidden marks injected context (e.g. background-task notifications) that
	// the model must see but UIs must not render as user input. A user message
	// whose content is entirely hidden becomes a hidden message.
	Hidden bool `json:"hidden,omitempty"`

	File *File `json:"file,omitempty"`

	Reasoning *Reasoning `json:"reasoning,omitempty"`

	ToolCall   *ToolCall   `json:"tool_call,omitempty"`
	ToolResult *ToolResult `json:"tool_result,omitempty"`
}

func CloneContent added in v0.10.9

func CloneContent(in []Content) []Content

CloneContent returns an independent copy suitable for retaining after an API call. Content only contains value fields and one level of pointer fields.

type ContextStats added in v0.11.2

type ContextStats struct {
	Model  string
	Window int

	InstructionsTokens int
	ToolsTokens        int
	ToolStats          []ToolStat
	MessagesTokens     int
	MessageCount       int

	LastInputTokens int64
}

ContextStats estimates what occupies the model's context window, by category. Token counts are byte-based approximations (~4 bytes/token); LastInputTokens is the provider-reported figure for the latest request.

func (ContextStats) EstimatedTotal added in v0.11.2

func (s ContextStats) EstimatedTotal() int

type EventRecorder added in v0.15.8

type EventRecorder interface {
	AppendEvents(events []RuntimeEvent) error
}

EventRecorder is the durability boundary. Implementations must append the whole batch in order or return an error without reporting success. Agent applies events to its in-memory projections only after this call succeeds.

type EventRecorderFunc added in v0.15.8

type EventRecorderFunc func(events []RuntimeEvent) error

func (EventRecorderFunc) AppendEvents added in v0.15.8

func (f EventRecorderFunc) AppendEvents(events []RuntimeEvent) error

type File

type File struct {
	Name string `json:"name,omitempty"`
	Data string `json:"data,omitempty"`
}

type GenerateOptions added in v0.14.9

type GenerateOptions struct {
	Model           string
	Effort          string
	Instructions    string
	Input           string
	OutputSchema    map[string]any
	MaxOutputTokens int64
}

GenerateOptions describes a stateless, tool-free model request. It is used by latency-sensitive helpers that must not inherit a chat session, tools, or conversation history.

type GenerateResult added in v0.14.9

type GenerateResult struct {
	Text  string
	Usage Usage
}

GenerateResult is the visible response plus provider-reported usage for independent budgeting and accounting.

type Message

type Message struct {
	InputID string      `json:"input_id,omitempty"`
	Role    MessageRole `json:"role"`

	Content []Content `json:"content"`
	Hidden  bool      `json:"hidden,omitempty"`
}

func CloneMessages added in v0.12.0

func CloneMessages(messages []Message) []Message

CloneMessages returns a deep-enough copy for handing message snapshots to callers while another goroutine may continue streaming into retained state.

type MessageRole

type MessageRole string
const (
	RoleUser      MessageRole = "user"
	RoleAssistant MessageRole = "assistant"
	RoleSystem    MessageRole = "system"
)

type ModelInfo added in v0.6.2

type ModelInfo struct {
	ID string
}

type ModelOption added in v0.11.4

type ModelOption struct {
	ID      string
	Efforts []string
}

ModelOption is a resolved model role. Efforts lists the supported reasoning efforts in ascending order; empty means unrestricted.

type Reasoning added in v0.6.2

type Reasoning struct {
	ID string `json:"id,omitempty"`

	Summary string `json:"summary,omitempty"`

	// Part indexes the summary part a streamed delta belongs to; renderers
	// separate parts however suits their medium.
	Part int `json:"part,omitempty"`

	// Content is the provider's opaque (encrypted) reasoning payload, only
	// replayable to the model that produced it. Model tags the producer so the
	// agent loop can purge stale payloads when the session model changes.
	Content string `json:"content,omitempty"`
	Model   string `json:"model,omitempty"`
}

type RuntimeEvent added in v0.15.8

type RuntimeEvent struct {
	Sequence uint64           `json:"sequence"`
	ID       string           `json:"id"`
	Type     RuntimeEventType `json:"type"`
	At       time.Time        `json:"at"`

	TurnID      string `json:"turn_id,omitempty"`
	RunID       string `json:"run_id,omitempty"`
	OperationID string `json:"operation_id,omitempty"`
	Model       string `json:"model,omitempty"`

	Message       *Message         `json:"message,omitempty"`
	Context       []Message        `json:"context,omitempty"`
	ContextReason string           `json:"context_reason,omitempty"`
	Usage         *Usage           `json:"usage,omitempty"`
	Terminal      *RuntimeTerminal `json:"terminal,omitempty"`
	Tool          *RuntimeTool     `json:"tool,omitempty"`
}

RuntimeEvent is deliberately a small tagged union. Sequence is assigned by Agent immediately before durable append; ID identifies this individual fact, while TurnID/RunID/OperationID identify lifecycle entities.

type RuntimeEventType added in v0.15.8

type RuntimeEventType string

RuntimeEventType identifies an immutable fact in an agent's runtime ledger. Messages form canonical conversation history; context checkpoints only replace the provider-facing projection and never remove canonical events.

const (
	EventMessage           RuntimeEventType = "message"
	EventContextCheckpoint RuntimeEventType = "context_checkpoint"
	EventUsage             RuntimeEventType = "usage"
	EventTurnStarted       RuntimeEventType = "turn_started"
	EventTurnTerminal      RuntimeEventType = "turn_terminal"
	EventRunStarted        RuntimeEventType = "run_started"
	EventRunTerminal       RuntimeEventType = "run_terminal"
	EventToolStarted       RuntimeEventType = "tool_started"
	EventToolTerminal      RuntimeEventType = "tool_terminal"
)

type RuntimeStatus added in v0.15.8

type RuntimeStatus string
const (
	RuntimeCompleted   RuntimeStatus = "completed"
	RuntimeFailed      RuntimeStatus = "failed"
	RuntimeInterrupted RuntimeStatus = "interrupted"
)

type RuntimeTerminal added in v0.15.8

type RuntimeTerminal struct {
	Status           RuntimeStatus `json:"status"`
	Error            string        `json:"error,omitempty"`
	OutcomeUncertain bool          `json:"outcome_uncertain,omitempty"`
}

RuntimeTerminal is the durable outcome of a turn, provider run, or tool operation. OutcomeUncertain is set when a process stopped after a possibly mutating tool began but before its terminal fact reached the ledger.

type RuntimeTool added in v0.15.8

type RuntimeTool struct {
	CallID  string `json:"call_id,omitempty"`
	Name    string `json:"name"`
	Args    string `json:"args,omitempty"`
	Effect  string `json:"effect,omitempty"`
	IsError bool   `json:"is_error,omitempty"`
}

type State added in v0.6.2

type State struct {
	Events          []RuntimeEvent `json:"events,omitempty"`
	Usage           Usage          `json:"usage"`
	Messages        []Message      `json:"messages,omitempty"`
	Context         []Message      `json:"context,omitempty"`
	ContextSet      bool           `json:"context_set,omitempty"`
	Revision        uint64         `json:"-"`
	ContextRevision uint64         `json:"context_revision,omitempty"`
}

func (*State) Load added in v0.6.2

func (s *State) Load(path string) error

func (*State) Save added in v0.6.2

func (s *State) Save(path string) error

type StreamEvent added in v0.12.9

type StreamEvent uint8

StreamEvent describes a lifecycle boundary in an Agent.Send stream. These events are separate from Message because they are transport concerns, not conversational content that can be retained or sent back to a model.

const (
	// StreamEventReset asks a consumer to discard visible deltas from the
	// current failed attempt before the agent retries the request.
	StreamEventReset StreamEvent = iota + 1
	// StreamEventCommit marks the current streamed attempt as accepted into
	// retained history. A later retry reset must not discard its output.
	StreamEventCommit
)

type StreamEventHandlers added in v0.12.9

type StreamEventHandlers struct {
	Reset  func()
	Commit func()
}

StreamEventHandlers declares the lifecycle operations a stream consumer can actually perform. In particular, a non-nil Reset is a capability promise: the consumer can discard every delta from the failed attempt before Send retries it.

type ToolCall

type ToolCall struct {
	ID string `json:"id"`

	Name         string            `json:"name"`
	Kind         string            `json:"kind,omitempty"`
	Args         string            `json:"args,omitempty"`
	Locations    []ToolLocation    `json:"locations,omitempty"`
	Presentation *ToolPresentation `json:"presentation,omitempty"`

	Partial bool `json:"partial,omitempty"`
}

type ToolLocation added in v0.15.1

type ToolLocation struct {
	Path string `json:"path"`
	Line int    `json:"line,omitempty"`
}

type ToolPresentation added in v0.15.2

type ToolPresentation struct {
	Title     string         `json:"title"`
	Kind      string         `json:"kind,omitempty"`
	Args      string         `json:"args,omitempty"`
	Hint      string         `json:"hint,omitempty"`
	Locations []ToolLocation `json:"locations,omitempty"`
}

func NewToolPresentation added in v0.15.2

func NewToolPresentation(name, kind, args string, locations []ToolLocation) *ToolPresentation

NewToolPresentation creates display metadata without changing the execution name or arguments stored on a tool call.

type ToolResult

type ToolResult struct {
	ID string `json:"id,omitempty"`

	Name         string            `json:"name"`
	Kind         string            `json:"kind,omitempty"`
	Args         string            `json:"args,omitempty"`
	Locations    []ToolLocation    `json:"locations,omitempty"`
	Presentation *ToolPresentation `json:"presentation,omitempty"`

	Content  string         `json:"content,omitempty"`
	IsError  bool           `json:"is_error,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

type ToolStat added in v0.11.2

type ToolStat struct {
	Name   string
	Tokens int
}

type Usage

type Usage struct {
	// InputTokens and OutputTokens are inclusive totals. Cache reads and cache
	// creation are subsets of InputTokens; reasoning is a subset of
	// OutputTokens. The JSON names retain session compatibility with earlier
	// versions of wingman-agent.
	InputTokens  int64 `json:"input_tokens"`
	OutputTokens int64 `json:"output_tokens"`

	ReasoningTokens int64 `json:"reasoning_tokens,omitempty"`

	CacheReadInputTokens     int64 `json:"cached_tokens"`
	CacheCreationInputTokens int64 `json:"cache_write_tokens,omitempty"`

	// LastInputTokens is the input size of the most recent request — the
	// current context occupancy, unlike the cumulative counters above.
	LastInputTokens int64 `json:"last_input_tokens,omitempty"`
	// ContextWindow is the provider-reported maximum context size when the
	// transport supplies it directly.
	ContextWindow int64 `json:"context_window,omitempty"`
}

func (Usage) TotalTokens added in v0.16.0

func (u Usage) TotalTokens() int64

TotalTokens returns the provider-neutral total without double-counting cache or reasoning subsets.

Directories

Path Synopsis
fs
lsp
mcp

Jump to

Keyboard shortcuts

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