loop

package
v0.0.33 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2025 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Agent

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

func NewAgent

func NewAgent(config AgentConfig) *Agent

NewAgent creates a new Agent. It is not usable until Init() is called.

func (*Agent) BranchName

func (a *Agent) BranchName() string

BranchName returns the git branch name for the conversation.

func (*Agent) BranchPrefix

func (a *Agent) BranchPrefix() string

BranchPrefix returns the configured branch prefix

func (*Agent) CancelToolUse

func (a *Agent) CancelToolUse(toolUseID string, cause error) error

func (*Agent) CancelTurn

func (a *Agent) CancelTurn(cause error)

func (*Agent) CompactConversation

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

CompactConversation compacts the current conversation by generating a summary and restarting the conversation with that summary as the initial context

func (*Agent) CurrentState

func (a *Agent) CurrentState() State

CurrentState returns the current state of the agent's state machine.

func (*Agent) CurrentStateName

func (a *Agent) CurrentStateName() string

StateName implements CodingAgent.

func (*Agent) CurrentTodoContent

func (a *Agent) CurrentTodoContent() string

CurrentTodoContent returns the current todo list data as JSON. It returns an empty string if no todos exist.

func (*Agent) DetectGitChanges

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

DetectGitChanges checks for new git commits and pushes them if found

func (*Agent) Diff

func (a *Agent) Diff(commit *string) (string, error)

Diff returns a unified diff of changes made since the agent was instantiated.

func (*Agent) DiffStats

func (a *Agent) DiffStats() (int, int)

DiffStats returns the number of lines added and removed from sketch-base to HEAD

func (*Agent) ExternalMessage added in v0.0.28

func (a *Agent) ExternalMessage(ctx context.Context, msg ExternalMessage) error

ExternalMessage implements CodingAgent. TODO: Debounce and/or coalesce these messages so they're less disruptive to the conversation.

func (*Agent) FirstMessageIndex

func (a *Agent) FirstMessageIndex() int

func (*Agent) GatherMessages

func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error)

func (*Agent) GetConvo added in v0.0.12

func (a *Agent) GetConvo() ConvoInterface

GetConvo returns the conversation interface for debugging purposes.

func (*Agent) GetPorts added in v0.0.2

func (a *Agent) GetPorts() []portlist.Port

GetPorts returns the cached list of open TCP ports.

func (*Agent) GitOrigin

func (a *Agent) GitOrigin() string

GitOrigin returns the URL of the git remote 'origin' if it exists.

func (*Agent) GitUsername

func (a *Agent) GitUsername() string

GitUsername returns the git user name from the agent config.

func (*Agent) IncrementRetryNumber

func (a *Agent) IncrementRetryNumber()

IncrementRetryNumber increments the retry number for branch naming conflicts

func (*Agent) Init

func (a *Agent) Init(ini AgentInit) error

func (*Agent) IsInContainer

func (a *Agent) IsInContainer() bool

func (*Agent) LinkToGitHub

func (a *Agent) LinkToGitHub() bool

LinkToGitHub returns whether GitHub branch linking is enabled

func (*Agent) Loop

func (a *Agent) Loop(ctxOuter context.Context)

func (*Agent) MessageCount

func (a *Agent) MessageCount() int

MessageCount implements CodingAgent.

func (*Agent) Messages

func (a *Agent) Messages(start int, end int) []AgentMessage

Messages implements CodingAgent.

func (*Agent) ModelName added in v0.0.24

func (a *Agent) ModelName() string

ModelName returns the name of the model the agent is using.

func (*Agent) NewIterator

func (a *Agent) NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator

NewIterator implements CodingAgent.

func (*Agent) NewStateTransitionIterator

func (a *Agent) NewStateTransitionIterator(ctx context.Context) StateTransitionIterator

NewStateTransitionIterator returns an iterator that receives state transitions.

func (*Agent) OS

func (a *Agent) OS() string

OS returns the operating system of the client.

func (*Agent) OnRequest

func (a *Agent) OnRequest(ctx context.Context, convo *conversation.Convo, id string, msg *llm.Message)

OnRequest implements ant.Listener.

func (*Agent) OnResponse

func (a *Agent) OnResponse(ctx context.Context, convo *conversation.Convo, id string, resp *llm.Response)

OnResponse implements conversation.Listener. Responses contain messages from the LLM that need to be displayed (as well as tool calls that we send along when they're done). (It would be reasonable to also mention tool calls when they're started, but we don't do that yet.)

func (*Agent) OnToolCall

func (a *Agent) OnToolCall(ctx context.Context, convo *conversation.Convo, id string, toolName string, toolInput json.RawMessage, content llm.Content)

OnToolCall implements ant.Listener and tracks the start of a tool call.

func (*Agent) OnToolResult

func (a *Agent) OnToolResult(ctx context.Context, convo *conversation.Convo, toolID string, toolName string, toolInput json.RawMessage, content llm.Content, result *string, err error)

OnToolResult implements ant.Listener.

func (*Agent) OpenBrowser

func (a *Agent) OpenBrowser(url string)

func (*Agent) OriginalBudget

func (a *Agent) OriginalBudget() conversation.Budget

func (*Agent) OutsideHostname

func (a *Agent) OutsideHostname() string

OutsideHostname returns the hostname of the outside system.

func (*Agent) OutsideOS

func (a *Agent) OutsideOS() string

OutsideOS returns the operating system of the outside system.

func (*Agent) OutsideWorkingDir

func (a *Agent) OutsideWorkingDir() string

OutsideWorkingDir returns the working directory on the outside system.

func (*Agent) OutstandingLLMCallCount

func (a *Agent) OutstandingLLMCallCount() int

OutstandingLLMCallCount returns the number of outstanding LLM calls.

func (*Agent) OutstandingToolCalls

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

OutstandingToolCalls returns the names of outstanding tool calls.

func (*Agent) PassthroughUpstream added in v0.0.15

func (a *Agent) PassthroughUpstream() bool

PassthroughUpstream returns whether passthrough upstream is enabled.

func (*Agent) Ready

func (a *Agent) Ready() <-chan struct{}

func (*Agent) RepoRoot

func (a *Agent) RepoRoot() string

RepoRoot returns the git repository root directory.

func (*Agent) SSHConnectionString

func (a *Agent) SSHConnectionString() string

SSHConnectionString returns the SSH connection string for the container.

func (*Agent) SessionID

func (a *Agent) SessionID() string

func (*Agent) SetSlug

func (a *Agent) SetSlug(slug string)

SetSlug sets a human-readable identifier for the conversation.

func (*Agent) ShouldCompact

func (a *Agent) ShouldCompact() bool

ShouldCompact checks if the conversation should be compacted based on token usage

func (*Agent) SkabandAddr

func (a *Agent) SkabandAddr() string

SkabandAddr returns the skaband address if configured

func (*Agent) SketchGitBase

func (a *Agent) SketchGitBase() string

SketchGitBase returns the Git commit hash that was saved when the agent was instantiated.

func (*Agent) SketchGitBaseRef

func (a *Agent) SketchGitBaseRef() string

SketchGitBaseRef distinguishes between the typical container version, where sketch-base is unambiguous, and the "unsafe" version, where we need to use a session id to disambiguate.

func (*Agent) Slug

func (a *Agent) Slug() string

Slug returns the slug identifier for this conversation.

func (*Agent) TokenContextWindow added in v0.0.6

func (a *Agent) TokenContextWindow() int

TokenContextWindow implements CodingAgent.

func (*Agent) TotalUsage

func (a *Agent) TotalUsage() conversation.CumulativeUsage

func (*Agent) URL

func (a *Agent) URL() string

func (*Agent) Upstream

func (a *Agent) Upstream() string

Upstream returns the upstream branch for git work

func (*Agent) UserMessage

func (a *Agent) UserMessage(ctx context.Context, msg string)

func (*Agent) WorkingDir

func (a *Agent) WorkingDir() string

WorkingDir implements CodingAgent.

type AgentConfig

type AgentConfig struct {
	Context      context.Context
	Service      llm.Service
	Budget       conversation.Budget
	GitUsername  string
	GitEmail     string
	SessionID    string
	ClientGOOS   string
	ClientGOARCH string
	InDocker     bool
	OneShot      bool
	WorkingDir   string
	// Model is the name of the LLM model being used
	Model string
	// Outside information
	OutsideHostname   string
	OutsideOS         string
	OutsideWorkingDir string

	// Outtie's HTTP to, e.g., open a browser
	OutsideHTTP string
	// Outtie's Git server
	GitRemoteAddr string
	// Original git origin URL from host repository, if any
	OriginalGitOrigin string
	// Upstream branch for git work
	Upstream string
	// Commit to checkout from Outtie
	Commit string
	// Prefix for git branches created by sketch
	BranchPrefix string
	// LinkToGitHub enables GitHub branch linking in UI
	LinkToGitHub bool
	// SSH connection string for connecting to the container
	SSHConnectionString string
	// Skaband client for session history (optional)
	SkabandClient *skabandclient.SkabandClient
	// MCP server configurations
	MCPServers []string
	// Timeout configuration for bash tool
	BashTimeouts *claudetool.Timeouts
	// PassthroughUpstream configures upstream remote for passthrough to innie
	PassthroughUpstream bool
	// FetchOnLaunch enables git fetch during initialization
	FetchOnLaunch bool
}

AgentConfig contains configuration for creating a new Agent.

type AgentGitState

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

AgentGitState holds the state necessary for pushing to a remote git repo when sketch branch changes. If gitRemoteAddr is set, then we push to sketch/ any time we notice we need to.

func (*AgentGitState) BranchName

func (ags *AgentGitState) BranchName(prefix string) string

func (*AgentGitState) DiffStats

func (ags *AgentGitState) DiffStats() (int, int)

func (*AgentGitState) HasSeenCommits

func (ags *AgentGitState) HasSeenCommits() bool

HasSeenCommits returns true if any commits have been processed

func (*AgentGitState) IncrementRetryNumber

func (ags *AgentGitState) IncrementRetryNumber()

func (*AgentGitState) RetryNumber

func (ags *AgentGitState) RetryNumber() int

func (*AgentGitState) SetSlug

func (ags *AgentGitState) SetSlug(slug string)

func (*AgentGitState) Slug

func (ags *AgentGitState) Slug() string

func (*AgentGitState) Upstream

func (ags *AgentGitState) Upstream() string

type AgentInit

type AgentInit struct {
	NoGit bool // only for testing

	InDocker bool
	HostAddr string
}

type AgentMessage

type AgentMessage struct {
	Type CodingAgentMessageType `json:"type"`
	// EndOfTurn indicates that the AI is done working and is ready for the next user input.
	EndOfTurn bool `json:"end_of_turn"`

	Content         string           `json:"content"`
	ExternalMessage *ExternalMessage `json:"external_message,omitempty"`
	ToolName        string           `json:"tool_name,omitempty"`
	ToolInput       string           `json:"input,omitempty"`
	ToolResult      string           `json:"tool_result,omitempty"`
	ToolError       bool             `json:"tool_error,omitempty"`
	ToolCallId      string           `json:"tool_call_id,omitempty"`

	// ToolCalls is a list of all tool calls requested in this message (name and input pairs)
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`

	// ToolResponses is a list of all responses to tool calls requested in this message (name and input pairs)
	ToolResponses []AgentMessage `json:"toolResponses,omitempty"`

	// Commits is a list of git commits for a commit message
	Commits []*GitCommit `json:"commits,omitempty"`

	Timestamp            time.Time  `json:"timestamp"`
	ConversationID       string     `json:"conversation_id"`
	ParentConversationID *string    `json:"parent_conversation_id,omitempty"`
	Usage                *llm.Usage `json:"usage,omitempty"`

	// Message timing information
	StartTime *time.Time     `json:"start_time,omitempty"`
	EndTime   *time.Time     `json:"end_time,omitempty"`
	Elapsed   *time.Duration `json:"elapsed,omitempty"`

	// Turn duration - the time taken for a complete agent turn
	TurnDuration *time.Duration `json:"turnDuration,omitempty"`

	// HideOutput indicates that this message should not be rendered in the UI.
	// This is useful for subconversations that generate output that shouldn't be shown to the user.
	HideOutput bool `json:"hide_output,omitempty"`

	// TodoContent contains the agent's todo file content when it has changed
	TodoContent *string `json:"todo_content,omitempty"`

	// Display contains content to be displayed to the user, set by tools
	Display any `json:"display,omitempty"`

	Idx int `json:"idx"`
}

func (*AgentMessage) Attr

func (a *AgentMessage) Attr() slog.Attr

func (*AgentMessage) SetConvo

func (m *AgentMessage) SetConvo(convo *conversation.Convo)

SetConvo sets m.ConversationID, m.ParentConversationID, and m.HideOutput based on convo.

type CodingAgent

type CodingAgent interface {
	// Init initializes an agent inside a docker container.
	Init(AgentInit) error

	// Ready returns a channel closed after Init successfully called.
	Ready() <-chan struct{}

	// URL reports the HTTP URL of this agent.
	URL() string

	// UserMessage enqueues a message to the agent and returns immediately.
	UserMessage(ctx context.Context, msg string)

	// Returns an iterator that finishes when the context is done and
	// starts with the given message index.
	NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator

	// Returns an iterator that notifies of state transitions until the context is done.
	NewStateTransitionIterator(ctx context.Context) StateTransitionIterator

	// Loop begins the agent loop returns only when ctx is cancelled.
	Loop(ctx context.Context)

	// BranchPrefix returns the configured branch prefix
	BranchPrefix() string

	// LinkToGitHub returns whether GitHub branch linking is enabled
	LinkToGitHub() bool

	CancelTurn(cause error)

	CancelToolUse(toolUseID string, cause error) error

	// Returns a subset of the agent's message history.
	Messages(start int, end int) []AgentMessage

	// Returns the current number of messages in the history
	MessageCount() int

	TotalUsage() conversation.CumulativeUsage
	OriginalBudget() conversation.Budget

	WorkingDir() string
	RepoRoot() string

	// Diff returns a unified diff of changes made since the agent was instantiated.
	// If commit is non-nil, it shows the diff for just that specific commit.
	Diff(commit *string) (string, error)

	// SketchGitBase returns the commit that's the "base" for Sketch's work. It
	// starts out as the commit where sketch started, but a user can move it if need
	// be, for example in the case of a rebase. It is stored as a git tag.
	SketchGitBase() string

	// SketchGitBase returns the symbolic name for the "base" for Sketch's work.
	// (Typically, this is "sketch-base")
	SketchGitBaseRef() string

	// Slug returns the slug identifier for this session.
	Slug() string

	// BranchName returns the git branch name for the conversation.
	BranchName() string

	// IncrementRetryNumber increments the retry number for branch naming conflicts.
	IncrementRetryNumber()

	// OS returns the operating system of the client.
	OS() string

	// SessionID returns the unique session identifier.
	SessionID() string

	// SSHConnectionString returns the SSH connection string for the container.
	SSHConnectionString() string

	// DetectGitChanges checks for new git commits and pushes them if found
	DetectGitChanges(ctx context.Context) error

	// OutstandingLLMCallCount returns the number of outstanding LLM calls.
	OutstandingLLMCallCount() int

	// OutstandingToolCalls returns the names of outstanding tool calls.
	OutstandingToolCalls() []string
	OutsideOS() string
	OutsideHostname() string
	OutsideWorkingDir() string
	GitOrigin() string

	// GitUsername returns the git user name from the agent config.
	GitUsername() string

	// PassthroughUpstream returns whether passthrough upstream is enabled.
	PassthroughUpstream() bool

	// DiffStats returns the number of lines added and removed from sketch-base to HEAD
	DiffStats() (int, int)
	// OpenBrowser is a best-effort attempt to open a browser at url in outside sketch.
	OpenBrowser(url string)

	// IsInContainer returns true if the agent is running in a container
	IsInContainer() bool
	// FirstMessageIndex returns the index of the first message in the current conversation
	FirstMessageIndex() int

	CurrentStateName() string
	// CurrentTodoContent returns the current todo list data as JSON, or empty string if no todos exist
	CurrentTodoContent() string

	// CompactConversation compacts the current conversation by generating a summary
	// and restarting the conversation with that summary as the initial context
	CompactConversation(ctx context.Context) error

	// SkabandAddr returns the skaband address if configured
	SkabandAddr() string

	// GetPorts returns the cached list of open TCP ports
	GetPorts() []portlist.Port

	// TokenContextWindow returns the TokenContextWindow size of the model the agent is using.
	TokenContextWindow() int

	// ModelName returns the name of the model the agent is using.
	ModelName() string

	// ExternalMessage enqueues an external message to the agent and returns immediately.
	ExternalMessage(ctx context.Context, msg ExternalMessage) error
}

type CodingAgentMessageType

type CodingAgentMessageType string
const (
	UserMessageType     CodingAgentMessageType = "user"
	AgentMessageType    CodingAgentMessageType = "agent"
	ErrorMessageType    CodingAgentMessageType = "error"
	BudgetMessageType   CodingAgentMessageType = "budget" // dedicated for "out of budget" errors
	ToolUseMessageType  CodingAgentMessageType = "tool"
	CommitMessageType   CodingAgentMessageType = "commit"   // for displaying git commits
	AutoMessageType     CodingAgentMessageType = "auto"     // for automated notifications like autoformatting
	CompactMessageType  CodingAgentMessageType = "compact"  // for conversation compaction notifications
	PortMessageType     CodingAgentMessageType = "port"     // for port monitoring events
	SlugMessageType     CodingAgentMessageType = "slug"     // for slug updates
	ExternalMessageType CodingAgentMessageType = "external" // for external notifications

)

type ConvoInterface

type ConvoInterface interface {
	CumulativeUsage() conversation.CumulativeUsage
	LastUsage() llm.Usage
	ResetBudget(conversation.Budget)
	OverBudget() error
	SendMessage(message llm.Message) (*llm.Response, error)
	SendUserTextMessage(s string, otherContents ...llm.Content) (*llm.Response, error)
	GetID() string
	ToolResultContents(ctx context.Context, resp *llm.Response) ([]llm.Content, bool, error)
	ToolResultCancelContents(resp *llm.Response) ([]llm.Content, error)
	CancelToolUse(toolUseID string, cause error) error
	SubConvoWithHistory() *conversation.Convo
	DebugJSON() ([]byte, error)
}

ConvoInterface defines the interface for conversation interactions

type ExternalMessage added in v0.0.28

type ExternalMessage struct {
	MessageType string `json:"message_type"`
	Body        any    `json:"body"`
	TextContent string `json:"text_content"`
}

ExternalMsg represents a message from a source external to the agent/user conversation, such as the outcome of a github workflow run.

type GitCommit

type GitCommit struct {
	Hash         string `json:"hash"`                    // Full commit hash
	Subject      string `json:"subject"`                 // Commit subject line
	Body         string `json:"body"`                    // Full commit message body
	PushedBranch string `json:"pushed_branch,omitempty"` // If set, this commit was pushed to this branch
}

GitCommit represents a single git commit for a commit message

type MessageIterator

type MessageIterator interface {
	// Next blocks until the next message is available. It may
	// return nil if the underlying iterator context is done.
	Next() *AgentMessage
	Close()
}

type MessageIteratorImpl

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

func (*MessageIteratorImpl) Close

func (m *MessageIteratorImpl) Close()

func (*MessageIteratorImpl) Next

func (m *MessageIteratorImpl) Next() *AgentMessage

type MockConvo

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

MockConvo is a custom mock for conversation.Convo interface

func NewMockConvo

func NewMockConvo(t *testing.T) *MockConvo

NewMockConvo creates a new mock Convo

func (*MockConvo) AssertExpectations

func (m *MockConvo) AssertExpectations(t *testing.T)

AssertExpectations checks that all expectations were met

func (*MockConvo) CancelToolUse

func (m *MockConvo) CancelToolUse(toolUseID string, cause error) error

CancelToolUse cancels a tool use

func (*MockConvo) CumulativeUsage

func (m *MockConvo) CumulativeUsage() conversation.CumulativeUsage

func (*MockConvo) DebugJSON added in v0.0.12

func (m *MockConvo) DebugJSON() ([]byte, error)

DebugJSON returns mock conversation data as JSON for debugging purposes

func (*MockConvo) ExpectCall

func (m *MockConvo) ExpectCall(method string, args ...any) *mockExpectation

ExpectCall sets up an expectation for a method call

func (*MockConvo) GetID

func (m *MockConvo) GetID() string

func (*MockConvo) LastUsage

func (m *MockConvo) LastUsage() llm.Usage

func (*MockConvo) OverBudget

func (m *MockConvo) OverBudget() error

func (*MockConvo) ResetBudget

func (m *MockConvo) ResetBudget(_ conversation.Budget)

func (*MockConvo) SendMessage

func (m *MockConvo) SendMessage(message llm.Message) (*llm.Response, error)

func (*MockConvo) SendUserTextMessage

func (m *MockConvo) SendUserTextMessage(message string, otherContents ...llm.Content) (*llm.Response, error)

func (*MockConvo) SubConvoWithHistory

func (m *MockConvo) SubConvoWithHistory() *conversation.Convo

func (*MockConvo) ToolResultCancelContents

func (m *MockConvo) ToolResultCancelContents(resp *llm.Response) ([]llm.Content, error)

func (*MockConvo) ToolResultContents

func (m *MockConvo) ToolResultContents(ctx context.Context, resp *llm.Response) ([]llm.Content, bool, error)

type PortMonitor

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

PortMonitor monitors open/listening TCP ports and sends notifications to an Agent when ports are detected or removed.

func NewPortMonitor

func NewPortMonitor(agent *Agent, interval time.Duration) *PortMonitor

NewPortMonitor creates a new PortMonitor instance.

func (*PortMonitor) GetPorts added in v0.0.2

func (pm *PortMonitor) GetPorts() []portlist.Port

GetPorts returns the cached list of open ports.

func (*PortMonitor) Start

func (pm *PortMonitor) Start(ctx context.Context) error

Start begins monitoring ports in a background goroutine.

func (*PortMonitor) Stop added in v0.0.2

func (pm *PortMonitor) Stop()

Stop stops the port monitor.

type State

type State int

State represents the possible states of the Agent state machine

const (
	// StateUnknown is the default state
	StateUnknown State = iota
	// StateReady is the initial state when the agent is initialized and ready to operate
	StateReady
	// StateWaitingForUserInput occurs when the agent is waiting for a user message to start a turn
	StateWaitingForUserInput
	// StateSendingToLLM occurs when the agent is sending message(s) to the LLM
	StateSendingToLLM
	// StateProcessingLLMResponse occurs when the agent is processing a response from the LLM
	StateProcessingLLMResponse
	// StateEndOfTurn occurs when processing is completed without tool use, and the turn ends
	StateEndOfTurn
	// StateToolUseRequested occurs when the LLM has requested to use a tool
	StateToolUseRequested
	// StateCheckingForCancellation occurs when the agent checks if user requested cancellation
	StateCheckingForCancellation
	// StateRunningTool occurs when the agent is executing the requested tool
	StateRunningTool
	// StateCheckingGitCommits occurs when the agent checks for new git commits after tool execution
	StateCheckingGitCommits
	// StateRunningAutoformatters occurs when the agent runs code formatters on new commits
	StateRunningAutoformatters
	// StateCheckingBudget occurs when the agent verifies if budget limits are exceeded
	StateCheckingBudget
	// StateGatheringAdditionalMessages occurs when the agent collects user messages that arrived during tool execution
	StateGatheringAdditionalMessages
	// StateSendingToolResults occurs when the agent sends tool results back to the LLM
	StateSendingToolResults
	// StateCancelled occurs when an operation was cancelled by the user
	StateCancelled
	// StateBudgetExceeded occurs when the budget limit was reached
	StateBudgetExceeded
	// StateError occurs when an error occurred during processing
	StateError
	// StateCompacting occurs when the agent is compacting the conversation
	StateCompacting
)

func (State) String

func (i State) String() string

type StateMachine

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

StateMachine manages the Agent's states and transitions

func NewStateMachine

func NewStateMachine() *StateMachine

NewStateMachine creates a new state machine initialized to StateReady

func (*StateMachine) AddTransitionListener

func (sm *StateMachine) AddTransitionListener(listener chan<- StateTransition) func()

AddTransitionListener adds a listener channel that will be notified of state transitions Returns a function that can be called to remove the listener

func (*StateMachine) CanTransition

func (sm *StateMachine) CanTransition(from, to State) bool

CanTransition returns true if a transition from the from state to the to state is valid

func (*StateMachine) ClearTransitionCallback

func (sm *StateMachine) ClearTransitionCallback()

ClearTransitionCallback removes any previously set transition callback

func (*StateMachine) CurrentState

func (sm *StateMachine) CurrentState() State

CurrentState returns the current state

func (*StateMachine) ForceTransition

func (sm *StateMachine) ForceTransition(ctx context.Context, newState State, reason string)

ForceTransition forces a transition regardless of whether it's valid according to the state machine rules This should be used only in critical situations like cancellation or error recovery

func (*StateMachine) History

func (sm *StateMachine) History() []StateTransition

History returns the transition history of the state machine

func (*StateMachine) IsInErrorState

func (sm *StateMachine) IsInErrorState() bool

IsInErrorState returns whether the current state is an error state

func (*StateMachine) IsInTerminalState

func (sm *StateMachine) IsInTerminalState() bool

IsInTerminalState returns whether the current state is a terminal state

func (*StateMachine) PreviousState

func (sm *StateMachine) PreviousState() State

PreviousState returns the previous state

func (*StateMachine) RemoveTransitionListener

func (sm *StateMachine) RemoveTransitionListener(listener chan<- StateTransition)

RemoveTransitionListener removes a previously added listener

func (*StateMachine) Reset

func (sm *StateMachine) Reset()

Reset resets the state machine to the initial ready state

func (*StateMachine) SetMaxHistorySize

func (sm *StateMachine) SetMaxHistorySize(size int)

SetMaxHistorySize sets the maximum number of transitions to keep in history

func (*StateMachine) SetTransitionCallback

func (sm *StateMachine) SetTransitionCallback(callback func(ctx context.Context, from, to State, event TransitionEvent))

SetTransitionCallback sets a function to be called on every state transition

func (*StateMachine) TimeInState

func (sm *StateMachine) TimeInState() time.Duration

TimeInState returns how long the machine has been in the current state

func (*StateMachine) Transition

func (sm *StateMachine) Transition(ctx context.Context, newState State, event string) error

Transition attempts to transition from the current state to the given state

func (*StateMachine) TransitionWithEvent

func (sm *StateMachine) TransitionWithEvent(ctx context.Context, newState State, event TransitionEvent) error

TransitionWithEvent attempts to transition from the current state to the given state with the provided event information

type StateTransition

type StateTransition struct {
	From  State
	To    State
	Event TransitionEvent
}

StateTransition represents a transition from one state to another

type StateTransitionIterator

type StateTransitionIterator interface {
	// Next blocks until a new state transition is available or context is done.
	// Returns nil if the context is cancelled.
	Next() *StateTransition
	// Close removes the listener and cleans up resources.
	Close()
}

StateTransitionIterator provides an iterator over state transitions.

type StateTransitionIteratorImpl

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

StateTransitionIteratorImpl implements StateTransitionIterator using a state machine listener.

func (*StateTransitionIteratorImpl) Close

func (s *StateTransitionIteratorImpl) Close()

Close removes the listener and cleans up resources.

func (*StateTransitionIteratorImpl) Next

Next blocks until a new state transition is available or the context is cancelled.

type ToolCall

type ToolCall struct {
	Name          string        `json:"name"`
	Input         string        `json:"input"`
	ToolCallId    string        `json:"tool_call_id"`
	ResultMessage *AgentMessage `json:"result_message,omitempty"`
	Args          string        `json:"args,omitempty"`
	Result        string        `json:"result,omitempty"`
}

ToolCall represents a single tool call within an agent message

type TransitionEvent

type TransitionEvent struct {
	// Description provides a human-readable description of the event
	Description string
	// Data can hold any additional information about the event
	Data interface{}
	// Timestamp is when the event occurred
	Timestamp time.Time
}

TransitionEvent represents an event that causes a state transition

Directories

Path Synopsis
Package server provides HTTP server functionality for the sketch loop.
Package server provides HTTP server functionality for the sketch loop.
gzhandler
Package gzhandler provides an HTTP file server implementation that serves pre-compressed files when available to clients that support gzip encoding.
Package gzhandler provides an HTTP file server implementation that serves pre-compressed files when available to clients that support gzip encoding.

Jump to

Keyboard shortcuts

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