agent

package
v0.107.6-beta.27 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FeatureWorkflows = "workflows"
)
View Source
const GoalFromContextDefaultWindow = 8

Variables

View Source
var ErrBusy = errors.New("agent is busy; wait for the current turn to finish")

Functions

func BuildGoalFromContextPrompt

func BuildGoalFromContextPrompt(tail []ai.Message) string

func EstimateTokens

func EstimateTokens(msgs []ai.Message) int

func GoalFromContextMessages

func GoalFromContextMessages(msgs []ai.Message, n int) ([]ai.Message, error)

func MemoryOffSnapshot added in v0.107.6

func MemoryOffSnapshot() ai.PromptSnapshot

MemoryOffSnapshot marks a user message created while memory is off. Every path that adds a user message to History while off must attach it.

func WithLifecycleStart added in v0.107.0

func WithLifecycleStart(ctx context.Context, callback func()) context.Context

func WithMemoryOffAuthored added in v0.107.6

func WithMemoryOffAuthored(ctx context.Context) context.Context

WithMemoryOffAuthored marks the turn's user message as written while memory was off, for input that waited (a queued message) until after memory was turned back on.

func WithRequestObserver added in v0.107.0

func WithRequestObserver(ctx context.Context, observer RequestObserver) context.Context

func WithTurnSnapshot added in v0.107.6

func WithTurnSnapshot(ctx context.Context, snapshot ai.PromptSnapshot) context.Context

WithTurnSnapshot attaches request-only text to the user message of the next turn. The model sees it after the user's words; history and transcripts keep only what the user typed. Desktop slash commands use it to send an expanded prompt template while the conversation still shows "/name args".

func WithUserMessageID added in v0.107.0

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

func WithUserMessageObserver added in v0.107.0

func WithUserMessageObserver(ctx context.Context, observe func(ai.Message) error) context.Context

WithUserMessageObserver observes the durable turn identity before model or tool execution.

Types

type Agent

type Agent struct {
	Client          ai.Client
	Model           string
	ModelName       string
	Provider        string
	MaxTokens       int
	Effort          string
	Vision          bool
	NativeWebSearch bool

	Temperature *float64
	TopP        *float64
	Tools       []tools.Tool
	// RequestToolFilter narrows schemas sent to the model; execution still uses AllTools.
	RequestToolFilter func([]tools.Tool) []tools.Tool
	RunTools          []tools.Tool
	RunToolsSet       bool
	Messages          []ai.Message

	ContextLimit int

	CompactClient   ai.Client
	CompactModel    string
	CompactProvider string

	CompactThreshold float64

	TaskDefault SubModel

	ResolveModel func(model, provider string) (SubModel, error)

	MaxTurns int

	WorkingDir string

	WorktreeSubagents bool

	Todos []Todo

	BrowserDisabled bool

	ComputerDisabled bool
	ComputerConfig   config.ComputerConfig
	SandboxPolicy    *sandbox.Policy

	OnOrphanedSteer func(text string)

	Hooks      *hooks.Runner
	PluginHook func(context.Context, hooks.Event) error
	// contains filtered or unexported fields
}

func New

func New(client ai.Client, model string, maxTokens int, systemPrompt string, opts ...Option) *Agent

func (*Agent) AddSubUsage

func (a *Agent) AddSubUsage(model string, u ai.Usage)

func (*Agent) AddUsage

func (a *Agent) AddUsage(u ai.Usage)

func (*Agent) AllTools

func (a *Agent) AllTools() []tools.Tool

func (*Agent) AppendUser

func (a *Agent) AppendUser(content string)

func (*Agent) AvailableTools added in v0.107.0

func (a *Agent) AvailableTools() []tools.Tool

func (*Agent) ContextTokens added in v0.107.0

func (a *Agent) ContextTokens() int

func (*Agent) ContinueUser added in v0.107.0

func (a *Agent) ContinueUser(ctx context.Context, messageID string, ev Events) (string, error)

ContinueUser runs the persisted tail user message without appending another user turn.

func (*Agent) Experimental

func (a *Agent) Experimental() []string

func (*Agent) FollowupTask

func (a *Agent) FollowupTask(ctx context.Context, id, text string, ev Events) (string, error)

func (*Agent) KnownTools added in v0.107.6

func (a *Agent) KnownTools() []tools.Tool

KnownTools are the tools a run may name in its options, including memory tools the switch currently hides, so a run's validation does not depend on the switch.

func (*Agent) LastStopReason added in v0.103.0

func (a *Agent) LastStopReason() ai.StopReason

func (*Agent) LaunchBackground

func (a *Agent) LaunchBackground(t *BackgroundTask, worktreePath string)

func (*Agent) LoadTodosJSON

func (a *Agent) LoadTodosJSON(s string)

func (*Agent) ManualCompact

func (a *Agent) ManualCompact(ctx context.Context, ev Events) error

func (*Agent) ManualCompactCommit added in v0.107.0

func (a *Agent) ManualCompactCommit(ctx context.Context, ev Events, commit func() error) (err error)

ManualCompactCommit keeps the turn lock until the caller commits the new context. A cancelled or failed commit restores the previous context and usage ledger.

func (*Agent) ManualNewContext added in v0.104.0

func (a *Agent) ManualNewContext(ctx context.Context, ev Events) error

func (*Agent) MemoryEnabled added in v0.107.6

func (a *Agent) MemoryEnabled() bool

func (*Agent) MessagesSnapshot

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

func (*Agent) ModelUsage added in v0.103.0

func (a *Agent) ModelUsage() map[string]ai.Usage

func (*Agent) PlanMode added in v0.103.0

func (a *Agent) PlanMode() bool

func (*Agent) RefreshMemory added in v0.103.0

func (a *Agent) RefreshMemory()

func (*Agent) RegisterBackground

func (a *Agent) RegisterBackground(description, prompt string, o SubModel) *BackgroundTask

func (*Agent) RegisterBackgroundContext added in v0.103.0

func (a *Agent) RegisterBackgroundContext(parent context.Context, description, prompt string, o SubModel) *BackgroundTask

func (*Agent) ResetUsage

func (a *Agent) ResetUsage()

func (*Agent) RestoreMessages added in v0.107.0

func (a *Agent) RestoreMessages(messages []ai.Message)

func (*Agent) RestoreTask

func (a *Agent) RestoreTask(t BackgroundTask)

func (*Agent) RestoreUsage added in v0.103.0

func (a *Agent) RestoreUsage(usage ai.UsageSummary)

func (*Agent) SessionIDValue

func (a *Agent) SessionIDValue() string

func (*Agent) SetCacheKey

func (a *Agent) SetCacheKey(key string)

func (*Agent) SetMCPTools

func (a *Agent) SetMCPTools(ts []tools.Tool)

func (*Agent) SetMemoryEnabled added in v0.107.6

func (a *Agent) SetMemoryEnabled(enabled bool)

SetMemoryEnabled toggles memory injection, hidden extraction and memory tools from the next turn on. Stored memories are untouched.

func (*Agent) SetMemoryRuntime added in v0.107.0

func (a *Agent) SetMemoryRuntime(runtime MemoryRuntime)

func (*Agent) SetMessageRewoundFrom added in v0.107.0

func (a *Agent) SetMessageRewoundFrom(index int, value string)

func (*Agent) SetModel added in v0.103.0

func (a *Agent) SetModel(model ModelConfig) error

func (*Agent) SetModelUsage added in v0.103.0

func (a *Agent) SetModelUsage(usage map[string]ai.Usage)

func (*Agent) SetOnTodos

func (a *Agent) SetOnTodos(fn func(items []Todo))

func (*Agent) SetPlanMode added in v0.103.0

func (a *Agent) SetPlanMode(enabled bool)

func (*Agent) SetPluginTools added in v0.103.0

func (a *Agent) SetPluginTools(ts []tools.Tool)

func (*Agent) SetSessionID

func (a *Agent) SetSessionID(id string)

func (*Agent) SetSubUsage

func (a *Agent) SetSubUsage(m map[string]ai.Usage)

func (*Agent) SetUsage

func (a *Agent) SetUsage(u ai.Usage)

func (*Agent) StartBackground

func (a *Agent) StartBackground(description, prompt string, o SubModel) *BackgroundTask

func (*Agent) StartSession added in v0.103.0

func (a *Agent) StartSession(ctx context.Context) error

func (*Agent) StartWait

func (a *Agent) StartWait(spec WaitTaskSpec) (*waitTask, error)

func (*Agent) StartWaitContext added in v0.103.0

func (a *Agent) StartWaitContext(ctx context.Context, spec WaitTaskSpec) (*waitTask, error)

func (*Agent) Steer

func (a *Agent) Steer(text string)

func (*Agent) SteerImages

func (a *Agent) SteerImages(text string, parts []ai.ContentPart)

func (*Agent) SteerTask

func (a *Agent) SteerTask(id, text string) error

func (*Agent) SubUsage

func (a *Agent) SubUsage() map[string]ai.Usage

func (*Agent) Tasks

func (a *Agent) Tasks() *taskRegistry

func (*Agent) TodosJSON

func (a *Agent) TodosJSON() string

func (*Agent) TotalUsage

func (a *Agent) TotalUsage() ai.Usage

func (*Agent) Turn

func (a *Agent) Turn(ctx context.Context, input string, ev Events) (string, error)

func (*Agent) TurnAuthored

func (a *Agent) TurnAuthored(ctx context.Context, input string, ev Events) (string, error)

func (*Agent) TurnParts

func (a *Agent) TurnParts(ctx context.Context, input string, parts []ai.ContentPart, ev Events) (string, error)

func (*Agent) TurnRunning

func (a *Agent) TurnRunning() bool

func (*Agent) TurnWithImages

func (a *Agent) TurnWithImages(ctx context.Context, input string, parts []ai.ContentPart, ev Events) (string, error)

func (*Agent) Usage

func (a *Agent) Usage() ai.Usage

func (*Agent) UsageSummary added in v0.103.0

func (a *Agent) UsageSummary() ai.UsageSummary

func (*Agent) WaitingOnSubagents

func (a *Agent) WaitingOnSubagents() bool

func (*Agent) Waits

func (a *Agent) Waits() *waitRegistry

func (*Agent) Workflows

func (a *Agent) Workflows() *workflow.Manager

type BackgroundTask

type BackgroundTask struct {
	ID          string
	Description string
	Prompt      string
	Status      TaskStatus
	Report      string
	StartedAt   time.Time
	EndedAt     time.Time

	Restored    bool
	FollowingUp bool

	Done chan struct{}

	SubMessages []ai.Message

	SubUsage      ai.Usage
	SubModelUsage map[string]ai.Usage
	SubSubUsage   map[string]ai.Usage

	SubModel string
	// contains filtered or unexported fields
}

type CompactInfo

type CompactInfo struct {
	Model    string
	Provider string
	Usage    ai.Usage
	Fresh    bool
}

type Events

type Events struct {
	OnPhase        func(stage string)
	OnLifecycle    func(event string)
	OnText         func(delta string)
	OnThink        func(delta string)
	OnHostedSearch func(ai.HostedSearch)
	OnToolStart    func(id, name, args string)
	OnToolEnd      func(id, name, result string)
	OnToolResult   func(id, name string, result tools.Result)

	OnToolCall func(id, name, args string)

	OnToolOutput func(id, outputSoFar string)
	OnSteer      func(text string)
	OnCompact    func(took, kept int)

	OnCompacted func(summary string, cutoff int, info CompactInfo)

	OnCompactStart    func(took, estTokens int)
	OnNewContextStart func(took, estTokens int)
	OnNewContext      func(cutoff int)
	OnUsage           func(u ai.Usage)
	OnRetry           func(ev ai.RetryEvent)

	OnDecay func(n int)
}

func FanIn

func FanIn(evs ...Events) Events

type JournaledEvent

type JournaledEvent struct {
	Kind  int
	S, S2 string
}

type MemoryRuntime added in v0.107.0

type MemoryRuntime interface {
	Inject(context.Context, string) (string, error)
	Completed(context.Context, MemoryTurn)
	// Abandoned is called for a turn that ended without completing (stopped,
	// failed, plan-mode exit) after its user message entered History. It must
	// not take the agent's locks.
	Abandoned(sessionID string, user ai.Message)
	Tools(func() string) []tools.Tool
	Close() error
}

MemoryRuntime owns backend memory injection and hidden extraction. Implementations must keep persistence behind the internal/memory Store seam.

type MemoryTurn added in v0.107.0

type MemoryTurn struct {
	SessionID string
	Workdir   string
	Model     string
	User      ai.Message
	History   []ai.Message
}

MemoryTurn is the durable input and history snapshot supplied after a real turn.

type ModelConfig added in v0.103.0

type ModelConfig struct {
	Client          ai.Client
	ID              string
	Name            string
	Provider        string
	MaxTokens       int
	ContextLimit    int
	Vision          bool
	NativeWebSearch bool
	Temperature     *float64
	TopP            *float64
}

type Option

type Option func(*Agent)

func WithComputerConfig added in v0.107.6

func WithComputerConfig(cfg config.ComputerConfig) Option

func WithExperimental

func WithExperimental(features []string) Option

func WithMemoryEnabled added in v0.107.6

func WithMemoryEnabled(enabled bool) Option

WithMemoryEnabled sets the memory master switch at construction.

func WithSystemPromptResolver added in v0.107.0

func WithSystemPromptResolver(resolve func() (string, error)) Option

WithSystemPromptResolver refreshes factory instructions before each turn.

func WithTurnTimeContext added in v0.107.6

func WithTurnTimeContext() Option

WithTurnTimeContext supplies current context alongside a clock-free system prompt.

type RequestObservation added in v0.107.0

type RequestObservation struct {
	ToolCallID   string
	TaskID       string
	ParentTaskID string
	Provider     string
	Endpoint     string
	Request      ai.Request
}

type RequestObserver added in v0.107.0

type RequestObserver interface {
	Start(context.Context, RequestObservation) (context.Context, error)
	End(context.Context, ai.Message, ai.Usage, error)
	Retry(context.Context, ai.RetryEvent)
}

type SubModel

type SubModel struct {
	Client       ai.Client
	Model        string
	Provider     string
	ContextLimit int
	MaxTokens    int
	Effort       string
	Vision       bool
}

type TaskStatus

type TaskStatus string
const (
	TaskRunning   TaskStatus = "running"
	TaskDone      TaskStatus = "done"
	TaskError     TaskStatus = "error"
	TaskCancelled TaskStatus = "cancelled"
)

type Todo

type Todo struct {
	ID      string `json:"id"`
	Content string `json:"content"`
	Status  string `json:"status"`
}

type WaitStatus

type WaitStatus string
const (
	WaitRunning WaitStatus = "running"
	WaitMet     WaitStatus = "condition met"
	WaitTimeout WaitStatus = "timed out"
	WaitFailed  WaitStatus = "command failing"
	WaitKilled  WaitStatus = "cancelled"
)

type WaitTaskSpec

type WaitTaskSpec struct {
	Command  string
	Shell    string
	Until    string
	Interval time.Duration
	Timeout  time.Duration
}

Jump to

Keyboard shortcuts

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