agent

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultHookOutputCapBytes = 256 * 1024
)

Variables

View Source
var ErrBudgetExceeded = errors.New("session budget exhausted")
View Source
var ErrSessionBusy = errors.New("session is currently processing another request")

Functions

func FormatPlanUpdateForDisplay added in v0.1.15

func FormatPlanUpdateForDisplay(update PlanUpdateInfo) string

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

func NewAgent

func NewAgent(provider llm.Provider, store store.MessageStore, tools []core.Tool) *Agent

func NewAgentWithRegistry

func NewAgentWithRegistry(provider llm.Provider, store store.MessageStore, tools *core.ToolRegistry, opts ...AgentOption) *Agent

func (*Agent) CompactSession

func (a *Agent) CompactSession(ctx context.Context, sessionID string) (CompactInfo, error)

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, sessionID, input string) (core.Message, error)

func (*Agent) RunSideQuestion added in v0.1.17

func (a *Agent) RunSideQuestion(ctx context.Context, sessionID, question string) (<-chan SideQuestionEvent, error)

func (*Agent) RunStream

func (a *Agent) RunStream(ctx context.Context, sessionID, input string) (<-chan AgentEvent, error)

func (*Agent) RunStreamWithInjectedInput added in v0.1.4

func (a *Agent) RunStreamWithInjectedInput(ctx context.Context, sessionID, visibleInput, hiddenInput string) (<-chan AgentEvent, error)

func (*Agent) RunStreamWithInjectedInputOptions added in v0.1.17

func (a *Agent) RunStreamWithInjectedInputOptions(ctx context.Context, sessionID, visibleInput, hiddenInput string, opts RunOptions) (<-chan AgentEvent, error)

func (*Agent) RunStreamWithOptions

func (a *Agent) RunStreamWithOptions(ctx context.Context, sessionID, input string, hiddenInput bool) (<-chan AgentEvent, error)

func (*Agent) RunStreamWithTurnOptions added in v0.1.17

func (a *Agent) RunStreamWithTurnOptions(ctx context.Context, sessionID, input string, opts RunOptions) (<-chan AgentEvent, error)

type AgentEvent

type AgentEvent struct {
	Type           AgentEventType
	Content        string
	ReasoningDelta string
	ToolArgs       *ToolArgsProgress
	ToolArgsRepair *ToolArgsRepair
	ToolBlocked    *ToolCallBlocked
	Approval       *ToolApprovalRequired
	ApprovalGrant  *ToolApprovalGranted
	Scavenged      *ToolCallScavenged
	Policy         *ToolPolicyDecision
	Recovery       *ToolRecoveryInfo
	ProviderRetry  *llmretry.Info
	Compact        *CompactInfo
	PrefixDrift    *PrefixDriftInfo
	CacheMetrics   *PrefixCacheMetricsInfo
	Budget         *BudgetWarningInfo
	Hook           *HookEventInfo
	Task           *TaskActivityInfo
	PlanUpdate     *PlanUpdateInfo
	ToolCall       *core.ToolCall
	UserInputReq   *core.UserInputRequest
	UserInputResp  *core.UserInputResponse
	Result         *core.ToolResult
	Message        *core.Message
	Err            error
}

type AgentEventType

type AgentEventType string
const (
	AgentEventTypeAssistantDelta         AgentEventType = "assistant_delta"
	AgentEventTypeReasoningDelta         AgentEventType = "reasoning_delta"
	AgentEventTypeToolArgsDelta          AgentEventType = "tool_args_delta"
	AgentEventTypeToolArgsRepaired       AgentEventType = "tool_args_repaired"
	AgentEventTypeToolCallBlocked        AgentEventType = "tool_call_blocked"
	AgentEventTypeToolModeBlocked        AgentEventType = "tool_mode_blocked"
	AgentEventTypeToolApprovalRequired   AgentEventType = "tool_approval_required"
	AgentEventTypeToolApprovalGranted    AgentEventType = "tool_approval_granted"
	AgentEventTypeToolCallScavenged      AgentEventType = "tool_call_scavenged"
	AgentEventTypeToolPolicyDecision     AgentEventType = "tool_policy_decision"
	AgentEventTypeToolCall               AgentEventType = "tool_call"
	AgentEventTypeToolResult             AgentEventType = "tool_result"
	AgentEventTypeUserInputRequired      AgentEventType = "user_input_required"
	AgentEventTypeUserInputSubmitted     AgentEventType = "user_input_submitted"
	AgentEventTypeUserInputCancelled     AgentEventType = "user_input_cancelled"
	AgentEventTypePlanDelta              AgentEventType = "plan_delta"
	AgentEventTypePlanCompleted          AgentEventType = "plan_completed"
	AgentEventTypePlanUpdate             AgentEventType = "plan_update"
	AgentEventTypePlanStepBlocked        AgentEventType = "plan_step_blocked"
	AgentEventTypeProviderRetryScheduled AgentEventType = "provider_retry_scheduled"
	AgentEventTypeToolRecoveryScheduled  AgentEventType = "tool_recovery_scheduled"
	AgentEventTypeToolRecoveryAttempt    AgentEventType = "tool_recovery_attempt"
	AgentEventTypeToolRecoveryExhausted  AgentEventType = "tool_recovery_exhausted"
	AgentEventTypeReplanRequiredSet      AgentEventType = "replan_required_set"
	AgentEventTypeContextCompacted       AgentEventType = "context_compacted"
	AgentEventTypePrefixDrift            AgentEventType = "prefix_drift"
	AgentEventTypePrefixCacheMetrics     AgentEventType = "prefix_cache_metrics"
	AgentEventTypeBudgetWarning          AgentEventType = "budget_warning"
	AgentEventTypeTurnCancelled          AgentEventType = "turn_cancelled"
	AgentEventTypeForcedSummaryStarted   AgentEventType = "forced_summary_started"
	AgentEventTypeForcedSummaryDone      AgentEventType = "forced_summary_done"
	AgentEventTypeForcedSummaryFailed    AgentEventType = "forced_summary_failed"
	AgentEventTypeHookStarted            AgentEventType = "hook_started"
	AgentEventTypeHookBlocked            AgentEventType = "hook_blocked"
	AgentEventTypeHookWarned             AgentEventType = "hook_warned"
	AgentEventTypeHookFailed             AgentEventType = "hook_failed"
	AgentEventTypeHookCompleted          AgentEventType = "hook_completed"
	AgentEventTypeParallelReasonStarted  AgentEventType = "parallel_reason_started"
	AgentEventTypeParallelReasonDone     AgentEventType = "parallel_reason_completed"
	AgentEventTypeSubagentStarted        AgentEventType = "subagent_started"
	AgentEventTypeTaskProgress           AgentEventType = "task_progress"
	AgentEventTypeSubagentDone           AgentEventType = "subagent_completed"
	AgentEventTypeDone                   AgentEventType = "done"
	AgentEventTypeError                  AgentEventType = "error"
)

type AgentOption

type AgentOption func(*Agent)

func WithApprovalFunc

func WithApprovalFunc(fn policy.ApprovalFunc) AgentOption

func WithAutoCompact

func WithAutoCompact(enabled bool, threshold float64, contextWindow int) AgentOption

func WithBudgetWarningUSD

func WithBudgetWarningUSD(capUSD float64) AgentOption

func WithDisabledSkills added in v0.1.11

func WithDisabledSkills(names []string) AgentOption

func WithExtraSkills added in v0.1.15

func WithExtraSkills(extra []*skills.Skill) AgentOption

func WithExtraSystemBlocks added in v0.1.5

func WithExtraSystemBlocks(blocks ...string) AgentOption

func WithHookHandlers added in v0.1.15

func WithHookHandlers(handlers ...HookHandler) AgentOption

func WithHookRunner added in v0.1.15

func WithHookRunner(runner *HookRunner) AgentOption

func WithHooks

func WithHooks(hooks []ResolvedHook, workspaceRoot string) AgentOption

func WithMaxToolIters added in v0.1.5

func WithMaxToolIters(maxIters int) AgentOption

func WithProjectMemory

func WithProjectMemory(enabled bool, maxChars int, fileOrder []string, workspaceRoot string) AgentOption

func WithRecoveryPolicy

func WithRecoveryPolicy(r RecoveryPolicy) AgentOption

func WithSessionMode

func WithSessionMode(mode session.Mode) AgentOption

func WithSessionsDir

func WithSessionsDir(sessionsDir string) AgentOption

func WithToolPolicy

func WithToolPolicy(policy policy.ToolPolicy) AgentOption

func WithUsageLogPath

func WithUsageLogPath(path string) AgentOption

func WithUserInputFunc

func WithUserInputFunc(fn UserInputFunc) AgentOption

type BudgetWarningInfo

type BudgetWarningInfo struct {
	CapUSD      float64
	SpentUSD    float64
	Percent     int
	TurnCostUSD float64
}

type CompactInfo

type CompactInfo struct {
	Compacted      bool
	Auto           bool
	MessagesBefore int
	MessagesAfter  int
	BeforeEstimate int
	AfterEstimate  int
}

type FailureClass

type FailureClass string
const (
	FailureClassTimeout          FailureClass = "timeout"
	FailureClassExecFailed       FailureClass = "exec_failed"
	FailureClassParseFailed      FailureClass = "parse_failed"
	FailureClassEmptyOutput      FailureClass = "empty_output"
	FailureClassPolicyDenied     FailureClass = "policy_denied"
	FailureClassApprovalDenied   FailureClass = "approval_denied"
	FailureClassPlanRequired     FailureClass = "plan_required"
	FailureClassPermissionDenied FailureClass = "permission_denied"
	FailureClassMCPToolError     FailureClass = "mcp_tool_error"
	FailureClassToolUnavailable  FailureClass = "tool_unavailable"
	FailureClassUnknown          FailureClass = "unknown"
)

type HookConfig

type HookConfig struct {
	Match       string `json:"match,omitempty" toml:"match,omitempty"`
	Command     string `json:"command" toml:"command,omitempty"`
	Description string `json:"description,omitempty" toml:"description,omitempty"`
	TimeoutMS   int    `json:"timeout,omitempty" toml:"timeout,omitempty"`
	CWD         string `json:"cwd,omitempty" toml:"cwd,omitempty"`
}

type HookDecision

type HookDecision string
const (
	HookDecisionPass    HookDecision = "pass"
	HookDecisionBlock   HookDecision = "block"
	HookDecisionHalt    HookDecision = "halt"
	HookDecisionWarn    HookDecision = "warn"
	HookDecisionTimeout HookDecision = "timeout"
	HookDecisionError   HookDecision = "error"
)

type HookEvent

type HookEvent string
const (
	HookEventPreToolUse       HookEvent = "PreToolUse"
	HookEventPostToolUse      HookEvent = "PostToolUse"
	HookEventUserPromptSubmit HookEvent = "UserPromptSubmit"
	HookEventStop             HookEvent = "Stop"
)

type HookEventInfo

type HookEventInfo struct {
	Name       string
	Event      HookEvent
	Decision   HookDecision
	ExitCode   int
	Message    string
	DurationMS int64
	Truncated  bool
}

type HookHandler added in v0.1.15

type HookHandler struct {
	Event       HookEvent
	Match       string
	Name        string
	Source      string
	Description string
	TimeoutMS   int
	Run         func(context.Context, HookPayload) HookResult
}

type HookOutcome

type HookOutcome struct {
	Hook       ResolvedHook
	Name       string
	Source     string
	Decision   HookDecision
	ExitCode   int
	Stdout     string
	Stderr     string
	Message    string
	DurationMS int64
	Truncated  bool

	AdditionalContext string
	UpdatedInput      string
	Metadata          map[string]any
}

type HookPayload

type HookPayload struct {
	Event             HookEvent      `json:"event"`
	CWD               string         `json:"cwd"`
	SessionID         string         `json:"session_id,omitempty"`
	ToolName          string         `json:"tool_name,omitempty"`
	ToolArgs          any            `json:"tool_args,omitempty"`
	ToolResult        string         `json:"tool_result,omitempty"`
	Prompt            string         `json:"prompt,omitempty"`
	LastAssistantText string         `json:"last_assistant_text,omitempty"`
	Turn              int            `json:"turn,omitempty"`
	ToolCall          *core.ToolCall `json:"tool_call,omitempty"`
}

func NewPostToolUsePayload

func NewPostToolUsePayload(sessionID string, call core.ToolCall, toolArgs any, toolResult string) HookPayload

func NewPreToolUsePayload

func NewPreToolUsePayload(sessionID string, call core.ToolCall, toolArgs any) HookPayload

func NewStopPayload

func NewStopPayload(sessionID, cwd, lastAssistantText string, turn int) HookPayload

func NewUserPromptSubmitPayload

func NewUserPromptSubmitPayload(sessionID, cwd, prompt string) HookPayload

type HookReport

type HookReport struct {
	Event             HookEvent
	Outcomes          []HookOutcome
	Blocked           bool
	Halted            bool
	AdditionalContext string
	UpdatedInput      string
	Metadata          map[string]any
}

type HookResult added in v0.1.15

type HookResult struct {
	Decision HookDecision
	Message  string
	Stdout   string
	Stderr   string

	AdditionalContext string
	UpdatedInput      string
	Metadata          map[string]any
}

type HookRunner

type HookRunner struct {
	// contains filtered or unexported fields
}

func NewHookRunner

func NewHookRunner(hooks []ResolvedHook, workspace string) *HookRunner

func (*HookRunner) AddHandlers added in v0.1.15

func (r *HookRunner) AddHandlers(handlers ...HookHandler)

func (*HookRunner) Empty

func (r *HookRunner) Empty() bool

func (*HookRunner) Run

func (r *HookRunner) Run(ctx context.Context, payload HookPayload) HookReport

type HookSettings

type HookSettings struct {
	Hooks map[HookEvent][]HookConfig `json:"hooks"`
}

type HookSpawnInput

type HookSpawnInput struct {
	Command   string
	CWD       string
	Stdin     string
	TimeoutMS int
}

type HookSpawnResult

type HookSpawnResult struct {
	ExitCode  int
	Stdout    string
	Stderr    string
	TimedOut  bool
	SpawnErr  error
	Truncated bool
}

type HookSpawner

type HookSpawner func(ctx context.Context, in HookSpawnInput) HookSpawnResult

type PlanUpdateInfo added in v0.1.15

type PlanUpdateInfo struct {
	Explanation string           `json:"explanation,omitempty"`
	Plan        []PlanUpdateStep `json:"plan"`
}

type PlanUpdateStep added in v0.1.15

type PlanUpdateStep struct {
	Step   string `json:"step"`
	Status string `json:"status"`
}

type PrefixCacheMetricsInfo

type PrefixCacheMetricsInfo struct {
	Model             string
	PrefixFingerprint string
	PromptTokens      int
	CachedTokens      int
	CacheHitRatio     float64
}

type PrefixDriftInfo

type PrefixDriftInfo struct {
	Expected string
	Actual   string
}

type RecoveryAction

type RecoveryAction string
const (
	RecoveryActionRetrySame        RecoveryAction = "retry_same"
	RecoveryActionRetryWithBackoff RecoveryAction = "retry_with_backoff"
	RecoveryActionFallbackReadOnly RecoveryAction = "fallback_readonly"
	RecoveryActionRequestReplan    RecoveryAction = "request_replan"
	RecoveryActionHardBlock        RecoveryAction = "hard_block"
	RecoveryActionPassThrough      RecoveryAction = "pass_through"
)

type RecoveryPolicy

type RecoveryPolicy struct {
	Enabled bool
	Rules   map[FailureClass]RecoveryRule
}

func DefaultRecoveryPolicy

func DefaultRecoveryPolicy() RecoveryPolicy

type RecoveryRule

type RecoveryRule struct {
	Action      RecoveryAction
	MaxAttempts int
	BackoffMS   int
}

type ResolvedHook

type ResolvedHook struct {
	HookConfig
	Event  HookEvent
	Source string
}

func LoadHooks

func LoadHooks(workspaceRoot, dataDir string) ([]ResolvedHook, []string, error)

func LoadProjectHooks

func LoadProjectHooks(workspaceRoot string) ([]ResolvedHook, error)

func ResolveHooks added in v0.1.9

func ResolveHooks(st HookSettings, source string) []ResolvedHook

type RunOptions added in v0.1.17

type RunOptions struct {
	HiddenInput        bool
	ReadOnly           bool
	ShellAllowPrefixes []string
}

type SideQuestionEvent added in v0.1.17

type SideQuestionEvent struct {
	Type    SideQuestionEventType
	Content string
	Err     error
}

type SideQuestionEventType added in v0.1.17

type SideQuestionEventType string
const (
	SideQuestionEventDelta SideQuestionEventType = "delta"
	SideQuestionEventDone  SideQuestionEventType = "done"
	SideQuestionEventError SideQuestionEventType = "error"
)

type TaskActivityInfo added in v0.1.5

type TaskActivityInfo struct {
	ToolCallID string
	ToolName   string
	Role       string
	Model      string
	Count      int
	Summary    string
	Status     string
	DurationMS int64
	Metadata   map[string]any
}

type ToolApprovalGranted added in v0.1.15

type ToolApprovalGranted struct {
	SessionID  string
	ToolCallID string
	ToolName   string
	Key        string
	Keys       []string
}

type ToolApprovalRequired

type ToolApprovalRequired struct {
	ToolCallID string
	ToolName   string
	Reason     string
	Code       string
	Key        string
	Keys       []string
	Summary    string
	Scope      string
	Metadata   map[string]any
}

type ToolArgsProgress

type ToolArgsProgress struct {
	ToolCallIndex int
	ToolName      string
	ArgsChars     int
	ReadyCount    int
}

type ToolArgsRepair

type ToolArgsRepair struct {
	ToolCallIndex int
	ToolName      string
}

type ToolCallBlocked

type ToolCallBlocked struct {
	ToolCallID string
	ToolName   string
	ReasonCode string
}

type ToolCallScavenged

type ToolCallScavenged struct {
	Count int
}

type ToolPolicyDecision

type ToolPolicyDecision struct {
	ToolCallID    string
	ToolName      string
	Allow         bool
	NeedsApproval bool
	Reason        string
	Code          string
	Phase         string
	MatchedRule   string
}

type ToolRecoveryInfo

type ToolRecoveryInfo struct {
	ToolCallID     string
	ToolName       string
	FailureClass   string
	Action         string
	Attempt        int
	MaxAttempts    int
	Reason         string
	Executed       bool
	ReplanInjected bool
}

type UserInputFunc

type UserInputFunc func(req UserInputRequest) (core.UserInputResponse, bool)

type UserInputRequest

type UserInputRequest struct {
	SessionID string
	ToolCall  core.ToolCall
	Questions []core.UserInputQuestion
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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