agent

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: May 13, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultRepeatedToolSequenceThreshold = 3

Variables

This section is empty.

Functions

func BuildStopSummary

func BuildStopSummary(in StopSummaryInput) string

func NormalizeToolArguments

func NormalizeToolArguments(raw string) string

func RecentUniqueToolNames

func RecentUniqueToolNames(names []string, limit int) []string

func SignatureToolCallNames

func SignatureToolCallNames(calls []llm.ToolCall) string

func SignatureToolCalls

func SignatureToolCalls(calls []llm.ToolCall) string

func UniqueToolCallNames

func UniqueToolCallNames(calls []llm.ToolCall) []string

func ValidateTurnEvent

func ValidateTurnEvent(event TurnEvent) error

Types

type AgentMention added in v0.1.8

type AgentMention struct {
	Name string
}

type Engine

type Engine interface {
	HandleTurn(ctx context.Context, req TurnRequest) (<-chan TurnEvent, error)
}

Engine executes one turn and emits turn-scoped events.

Contract:

  • Implementations should emit exactly one terminal event (TurnEventComplete or TurnEventError).
  • Implementations should close the channel after the terminal event.

func NewDefaultEngine

func NewDefaultEngine(runner *Runner) Engine

NewDefaultEngine wires the default engine implementation backed by Runner internals.

type Event

type Event struct {
	Type          EventType
	SessionID     corepkg.SessionID
	UserInput     string
	Content       string
	ToolName      string
	ToolCallID    string
	ToolArguments string
	ToolResult    string
	Error         string
	Plan          planpkg.State
	Usage         llm.Usage
	AgentID       string // non-empty when emitted by a subagent
	InvocationID  string // non-empty when emitted by a subagent, globally unique per invocation

	// EventThinkingProgress fields — reasoning progress without exposing content.
	ReasoningCharCount int
	ReasoningActive    bool
}

type EventType

type EventType string
const (
	EventRunStarted        EventType = "run_started"
	EventAssistantDelta    EventType = "assistant_delta"
	EventAssistantMessage  EventType = "assistant_message"
	EventToolCallStarted   EventType = "tool_call_started"
	EventToolCallCompleted EventType = "tool_call_completed"
	EventPlanUpdated       EventType = "plan_updated"
	EventUsageUpdated      EventType = "usage_updated"
	EventRunFinished       EventType = "run_finished"
	EventThinkingProgress  EventType = "thinking_progress"
	EventStatusUpdated     EventType = "status_updated"
)

type Observer

type Observer interface {
	HandleEvent(Event)
}

func SubAgentObserver added in v0.1.6

func SubAgentObserver(inner Observer, agentID, invocationID string) Observer

SubAgentObserver wraps an Observer to tag all events with the given agentID and invocationID so the TUI can distinguish subagent events from main agent events, and route them to the correct subagent entry even when multiple subagents of the same type run concurrently.

type ObserverFunc

type ObserverFunc func(Event)

func (ObserverFunc) HandleEvent

func (f ObserverFunc) HandleEvent(event Event)

type Options

type Options struct {
	Workspace       string
	Config          config.Config
	Client          llm.Client
	Store           SessionStore
	Registry        ToolRegistry
	Executor        ToolExecutor
	PolicyGateway   PolicyGateway
	Engine          Engine
	TaskManager     runtimepkg.TaskManager
	Runtime         RuntimeGateway
	Extensions      extensionspkg.Manager
	SkillManager    *skills.Manager
	SubAgentManager *subagentspkg.Manager
	AuditStore      storagepkg.AuditStore
	PromptStore     storagepkg.PromptHistoryWriter
	Observer        Observer
	Approval        tools.ApprovalHandler
	Stdin           io.Reader
	Stdout          io.Writer
}

type PolicyGateway

type PolicyGateway interface {
	DecideTool(context.Context, ToolDecisionInput) (ToolDecision, error)
}

func NewDefaultPolicyGateway

func NewDefaultPolicyGateway() PolicyGateway

type PromptActiveSkill

type PromptActiveSkill struct {
	Name         string
	Description  string
	WhenToUse    string
	Instructions string
	Args         map[string]string
	ToolPolicy   string
	Tools        []string
}

type PromptInput

type PromptInput struct {
	Workspace                    string
	ApprovalPolicy               string
	ApprovalMode                 string
	AwayPolicy                   string
	SandboxEnabled               bool
	SystemSandbox                string
	SystemSandboxBackend         string
	SystemSandboxRequiredCapable bool
	SystemSandboxCapabilityLevel string
	SystemSandboxShellNetwork    bool
	SystemSandboxWorkerNetwork   bool
	SystemSandboxFallback        bool
	SystemSandboxStatus          string
	Model                        string
	Mode                         string
	Platform                     string
	Now                          time.Time
	Skills                       []PromptSkill
	SubAgents                    []PromptSubAgent
	Tools                        []string
	SubAgentRuntime              *PromptSubAgentRuntime
	SubAgentDefinition           string
	Plan                         planpkg.State
	ActiveSkill                  *PromptActiveSkill
	Instruction                  string
}

type PromptSkill

type PromptSkill struct {
	Name        string
	Description string
	Enabled     bool
}

type PromptSubAgent

type PromptSubAgent struct {
	Name        string
	Description string
	WhenToUse   string
	Mode        string
}

type PromptSubAgentRuntime

type PromptSubAgentRuntime struct {
	Name         string
	Task         string
	ScopePaths   []string
	ScopeSymbols []string
	AllowedTools []string
	Isolation    string
	ResultPolicy string
}

type RunPromptInput

type RunPromptInput struct {
	UserMessage                     llm.Message
	Assets                          map[llm.AssetID]llm.ImageAsset
	DisplayText                     string
	PersistDisplayTextAsUserMessage bool
	SubAgent                        *SubAgentPromptInput
}

type Runner

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

func NewRunner

func NewRunner(opts Options) *Runner

func (*Runner) ActivateSkill

func (r *Runner) ActivateSkill(sess *session.Session, name string, args map[string]string) (skills.Skill, error)

func (*Runner) AuthorSkill

func (r *Runner) AuthorSkill(name, brief string) (skills.AuthorResult, error)

func (*Runner) ClearActiveSkill

func (r *Runner) ClearActiveSkill(sess *session.Session) error

func (*Runner) ClearSkill

func (r *Runner) ClearSkill(name string) (skills.ClearResult, error)

func (*Runner) Close

func (r *Runner) Close() error

func (*Runner) CompactSession

func (r *Runner) CompactSession(ctx context.Context, sess *session.Session) (string, bool, error)

func (*Runner) DispatchSubAgent

func (r *Runner) DispatchSubAgent(
	ctx context.Context,
	sess *session.Session,
	mode string,
	request tools.DelegateSubAgentRequest,
	streamObserver Observer,
) (tools.DelegateSubAgentResult, error)

func (*Runner) FindBuiltinSubAgent

func (r *Runner) FindBuiltinSubAgent(name string) (subagentspkg.Agent, bool)

func (*Runner) FindSubAgent

func (r *Runner) FindSubAgent(name string) (subagentspkg.Agent, bool)

func (*Runner) GetActiveSkill

func (r *Runner) GetActiveSkill(sess *session.Session) (skills.Skill, bool)

func (*Runner) GetClient

func (r *Runner) GetClient() llm.Client

func (*Runner) GetConfig

func (r *Runner) GetConfig() config.Config

func (*Runner) ListModels added in v0.1.8

func (r *Runner) ListModels(ctx context.Context) ([]provider.ModelInfo, []provider.Warning, error)

func (*Runner) ListSkills

func (r *Runner) ListSkills() ([]skills.Skill, []skills.Diagnostic)

func (*Runner) ListSubAgents

func (r *Runner) ListSubAgents() ([]subagentspkg.Agent, []subagentspkg.Diagnostic)

func (*Runner) RunPrompt

func (r *Runner) RunPrompt(ctx context.Context, sess *session.Session, userInput, mode string, out io.Writer) (string, error)

func (*Runner) RunPromptWithInput

func (r *Runner) RunPromptWithInput(ctx context.Context, sess *session.Session, input RunPromptInput, mode string, out io.Writer) (string, error)

func (*Runner) SetApprovalHandler

func (r *Runner) SetApprovalHandler(handler tools.ApprovalHandler)

func (*Runner) SetObserver

func (r *Runner) SetObserver(observer Observer)

func (*Runner) SubAgentManager added in v0.1.8

func (r *Runner) SubAgentManager() *subagentspkg.Manager

func (*Runner) UpdateApprovalMode

func (r *Runner) UpdateApprovalMode(mode string)

func (*Runner) UpdateProvider

func (r *Runner) UpdateProvider(providerCfg config.ProviderConfig, client llm.Client)

func (*Runner) UpdateProviderRuntime added in v0.1.8

func (r *Runner) UpdateProviderRuntime(runtimeCfg config.ProviderRuntimeConfig, providerCfg config.ProviderConfig, client llm.Client)

type RuntimeGateway

type RuntimeGateway interface {
	RunSync(ctx context.Context, request RuntimeTaskRequest) (RuntimeTaskExecution, error)
	RunAsync(ctx context.Context, request RuntimeTaskRequest) (RuntimeTaskLaunch, error)
}

type RuntimeTaskExecution

type RuntimeTaskExecution struct {
	TaskID         corepkg.TaskID
	Result         runtimepkg.TaskResult
	ExecutionError error
}

type RuntimeTaskLaunch

type RuntimeTaskLaunch struct {
	TaskID corepkg.TaskID
}

type RuntimeTaskRequest

type RuntimeTaskRequest struct {
	SessionID          corepkg.SessionID
	TraceID            corepkg.TraceID
	Name               string
	Kind               string
	ParentTaskID       corepkg.TaskID
	Background         bool
	Timeout            time.Duration
	Metadata           map[string]string
	Execute            func(context.Context) ([]byte, error)
	OnTaskStateChanged func(runtimepkg.Task)
}

type SessionStore

type SessionStore interface {
	Save(session *session.Session) error
	Load(id string) (*session.Session, error)
}

SessionStore defines the persistence contract consumed by Runner.

type StopSummaryInput

type StopSummaryInput struct {
	SessionID         corepkg.SessionID
	Reason            string
	ExecutedTools     []string
	TaskReport        *TaskReport
	IncludeTaskReport bool
	RecentToolLimit   int
}

type SubAgentCompletionNotification added in v0.1.6

type SubAgentCompletionNotification struct {
	ParentSession  *session.Session
	TaskID         string
	Agent          string
	InvocationID   string
	Status         string // "completed" or "failed"
	Summary        string
	ErrorCode      string
	ErrorMessage   string
	WorktreePath   string
	WorktreeBranch string
	WorktreeState  string
}

SubAgentCompletionNotification carries the result of a completed async subagent task.

type SubAgentConfigOverrides added in v0.1.8

type SubAgentConfigOverrides struct {
	Workspace     string
	WritableRoots []string
}

SubAgentConfigOverrides allows the delegate layer to override config fields inherited from the parent runner when creating a child runner. Zero/nil fields mean "inherit from parent".

type SubAgentExecutionInput added in v0.1.6

type SubAgentExecutionInput struct {
	Request      tools.DelegateSubAgentRequest
	Preflight    subagentspkg.PreflightResult
	InvocationID string
	Agent        string
	RunMode      planpkg.AgentMode
	ExecCtx      *tools.ExecutionContext
	Observer     Observer                 // optional: receives streaming events from the child runner
	Store        SessionStore             // optional: used to persist child session transcript
	Overrides    *SubAgentConfigOverrides // optional: overrides for child runner config
}

SubAgentExecutionInput carries all resolved parameters needed to execute a subagent task.

type SubAgentExecutor added in v0.1.6

type SubAgentExecutor interface {
	Execute(ctx context.Context, input SubAgentExecutionInput) (tools.DelegateSubAgentResult, error)
}

SubAgentExecutor runs a subagent task to completion and returns a structured result. It encapsulates: child runner creation, child session creation, prompt building, engine loop execution, and result extraction.

func NewSubAgentExecutor added in v0.1.6

func NewSubAgentExecutor(runner *Runner) SubAgentExecutor

NewSubAgentExecutor creates a SubAgentExecutor backed by the given Runner.

type SubAgentNotifier added in v0.1.6

type SubAgentNotifier interface {
	NotifyCompletion(notification SubAgentCompletionNotification)
	DrainPending() []SubAgentCompletionNotification
}

SubAgentNotifier delivers async subagent completion results to a parent session. When an async task completes, the notifier queues a structured notification that the parent's turn loop can drain before each step.

type SubAgentPromptInput

type SubAgentPromptInput struct {
	Name           string
	Task           string
	ScopePaths     []string
	ScopeSymbols   []string
	AllowedTools   []string
	Isolation      string
	ResultPolicy   string
	DefinitionBody string
}

type TaskReport

type TaskReport struct {
	Executed                     []string `json:"executed,omitempty"`
	Denied                       []string `json:"denied,omitempty"`
	PendingApproval              []string `json:"pending_approval,omitempty"`
	SkippedDueToDeniedDependency []string `json:"skipped_due_to_denied_dependency,omitempty"`
	SkippedDueToDependency       []string `json:"skipped_due_to_dependency,omitempty"`
	SystemSandboxFallback        []string `json:"system_sandbox_fallback,omitempty"`
	StrategyAdjustments          []string `json:"strategy_adjustments,omitempty"`
	RetryReasons                 []string `json:"retry_reasons,omitempty"`
	NoProgressTurns              int      `json:"no_progress_turns,omitempty"`
	Escalations                  []string `json:"escalations,omitempty"`
}

func (TaskReport) HasNonSuccessOutcomes

func (r TaskReport) HasNonSuccessOutcomes() bool

func (TaskReport) HumanSummary

func (r TaskReport) HumanSummary() string

func (TaskReport) HumanSummaryLines

func (r TaskReport) HumanSummaryLines() []string

func (TaskReport) IsEmpty

func (r TaskReport) IsEmpty() bool

func (TaskReport) JSON

func (r TaskReport) JSON() string

func (*TaskReport) RecordDenied

func (r *TaskReport) RecordDenied(name string)

func (*TaskReport) RecordEscalation

func (r *TaskReport) RecordEscalation(reason string)

func (*TaskReport) RecordExecuted

func (r *TaskReport) RecordExecuted(name string)

func (*TaskReport) RecordNoProgressTurn

func (r *TaskReport) RecordNoProgressTurn()

func (*TaskReport) RecordPendingApproval

func (r *TaskReport) RecordPendingApproval(name string)

func (*TaskReport) RecordRetry

func (r *TaskReport) RecordRetry(reason string)

func (*TaskReport) RecordSkippedDueToDeniedDependency

func (r *TaskReport) RecordSkippedDueToDeniedDependency(name string)

func (*TaskReport) RecordSkippedDueToDependency

func (r *TaskReport) RecordSkippedDueToDependency(name string)

func (*TaskReport) RecordStrategyAdjustment

func (r *TaskReport) RecordStrategyAdjustment(note string)

func (*TaskReport) RecordSystemSandboxFallback

func (r *TaskReport) RecordSystemSandboxFallback(note string)

func (*TaskReport) UnmarshalJSON

func (r *TaskReport) UnmarshalJSON(data []byte) error

type ToolDecision

type ToolDecision struct {
	Decision   corepkg.Decision
	ReasonCode string
	Reason     string
	RiskLevel  corepkg.RiskLevel
}

type ToolDecisionInput

type ToolDecisionInput struct {
	ToolName             string
	ToolArguments        string
	AllowedTools         map[string]struct{}
	DeniedTools          map[string]struct{}
	ApprovalPolicy       string
	SafetyClass          tools.SafetyClass
	SandboxEnabled       bool
	SandboxMode          string
	SandboxBackend       string
	SandboxCapability    string
	SandboxRequiredCapab bool
	SandboxShellNetwork  bool
	SandboxWorkerNetwork bool
}

type ToolExecutor

type ToolExecutor interface {
	ExecuteForMode(ctx context.Context, mode planpkg.AgentMode, name, rawArgs string, execCtx *tools.ExecutionContext) (string, error)
}

ToolExecutor defines the tool execution contract consumed by Runner.

type ToolRegistry

type ToolRegistry interface {
	DefinitionsForMode(mode planpkg.AgentMode) []llm.ToolDefinition
	DefinitionsForModeWithFilters(mode planpkg.AgentMode, allowlist, denylist []string) []llm.ToolDefinition
}

ToolRegistry defines the tool definition query contract consumed by Runner.

type ToolSequenceObservation

type ToolSequenceObservation struct {
	Signature        string
	RepeatCount      int
	NameOnlyRepeat   int
	ReachedThreshold bool
	UniqueToolNames  []string
	MatchMode        string
}

type ToolSequenceTracker

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

func NewToolSequenceTracker

func NewToolSequenceTracker(threshold int) *ToolSequenceTracker

func (*ToolSequenceTracker) Observe

type TurnEvent

type TurnEvent struct {
	EventID   corepkg.EventID
	SessionID corepkg.SessionID
	TaskID    corepkg.TaskID
	TraceID   corepkg.TraceID
	TurnID    string
	Sequence  uint64
	Type      TurnEventType
	Timestamp time.Time
	Payload   map[string]any
	ErrorCode string
	Retryable bool

	// Compatibility fields for current runner adapter flow.
	Answer string
	Error  error
}

TurnEvent is the normalized turn event contract emitted by Engine.

func (TurnEvent) IsTerminal

func (e TurnEvent) IsTerminal() bool

type TurnEventType

type TurnEventType string

TurnEventType identifies engine turn event categories.

const (
	TurnEventStart      TurnEventType = "start"
	TurnEventDelta      TurnEventType = "delta"
	TurnEventToolUse    TurnEventType = "tool_use"
	TurnEventToolResult TurnEventType = "tool_result"
	TurnEventComplete   TurnEventType = "complete"
	TurnEventError      TurnEventType = "error"

	// Compatibility aliases kept during Runner->Engine migration.
	TurnEventStarted   = TurnEventStart
	TurnEventCompleted = TurnEventComplete
	TurnEventFailed    = TurnEventError
)

type TurnRequest

type TurnRequest struct {
	Session *session.Session
	Input   RunPromptInput
	Mode    string
	Out     io.Writer
	TraceID corepkg.TraceID
}

TurnRequest defines the minimum input needed to execute one agent turn.

Jump to

Keyboard shortcuts

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