runtime

package
v1.30.0 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2026 License: Apache-2.0 Imports: 52 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// DefaultFallbackRetries is the default number of retries per model with exponential
	// backoff for retryable errors (5xx, timeouts). 2 retries means 3 total attempts.
	// This handles transient provider issues without immediately failing over.
	DefaultFallbackRetries = 2

	// DefaultFallbackCooldown is the default duration to stick with a fallback model
	// after a non-retryable error before retrying the primary.
	DefaultFallbackCooldown = 1 * time.Minute
)

Fallback configuration constants

Variables

This section is empty.

Functions

func IsValidResumeType

func IsValidResumeType(t ResumeType) bool

IsValidResumeType validates confirmation values coming from /resume

func ResolveCommand

func ResolveCommand(ctx context.Context, rt Runtime, userInput string) string

ResolveCommand transforms a /command into its expanded instruction text. It processes: 1. Command lookup from agent commands 2. Tool command execution (!tool_name(arg=value)) - tools executed and output inserted 3. JavaScript expressions (${...}) - evaluated with access to all agent tools and args array

  • ${args[0]}, ${args[1]}, etc. for positional arguments
  • ${args} or ${args.join(" ")} for all arguments
  • ${tool({...})} for tool calls

Types

type AgentChoiceEvent

type AgentChoiceEvent struct {
	Type    string `json:"type"`
	Content string `json:"content"`
	AgentContext
}

type AgentChoiceReasoningEvent

type AgentChoiceReasoningEvent struct {
	Type    string `json:"type"`
	Content string `json:"content"`
	AgentContext
}

type AgentContext

type AgentContext struct {
	AgentName string    `json:"agent_name,omitempty"`
	Timestamp time.Time `json:"timestamp"`
}

AgentContext carries optional agent attribution and timestamp for an event.

func (AgentContext) GetAgentName

func (a AgentContext) GetAgentName() string

GetAgentName returns the agent name for events embedding AgentContext.

type AgentDetails

type AgentDetails struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Provider    string         `json:"provider"`
	Model       string         `json:"model"`
	Commands    types.Commands `json:"commands,omitempty"`
}

AgentDetails contains information about an agent for display in the sidebar

type AgentInfoEvent

type AgentInfoEvent struct {
	Type           string `json:"type"`
	AgentName      string `json:"agent_name"`
	Model          string `json:"model"` // this is in provider/model format (e.g., "openai/gpt-4o")
	Description    string `json:"description"`
	WelcomeMessage string `json:"welcome_message,omitempty"`
	AgentContext
}

AgentInfoEvent is sent when agent information is available or changes

type AgentSwitchingEvent

type AgentSwitchingEvent struct {
	Type      string `json:"type"`
	Switching bool   `json:"switching"`
	FromAgent string `json:"from_agent,omitempty"`
	ToAgent   string `json:"to_agent,omitempty"`
	AgentContext
}

AgentSwitchingEvent is sent when agent switching starts or stops

type AuthorizationEvent

type AuthorizationEvent struct {
	Type         string                  `json:"type"`
	Confirmation tools.ElicitationAction `json:"confirmation"`
	AgentContext
}

type Client

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

Client is an HTTP client for the docker agent server API

func NewClient

func NewClient(baseURL string, opts ...ClientOption) (*Client, error)

NewClient creates a new HTTP client for the docker agent server

func (*Client) CreateAgent

func (c *Client) CreateAgent(ctx context.Context, prompt string) (*api.CreateAgentResponse, error)

CreateAgent creates a new agent using a prompt

func (*Client) CreateAgentConfig

func (c *Client) CreateAgentConfig(ctx context.Context, filename, model, description, instruction string) (*api.CreateAgentConfigResponse, error)

CreateAgentConfig creates a new agent manually with YAML configuration

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, sessTemplate *session.Session) (*session.Session, error)

CreateSession creates a new session

func (*Client) DeleteAgent

func (c *Client) DeleteAgent(ctx context.Context, filePath string) (*api.DeleteAgentResponse, error)

DeleteAgent deletes an agent by file path

func (*Client) DeleteSession

func (c *Client) DeleteSession(ctx context.Context, id string) error

DeleteSession deletes a session by ID

func (*Client) EditAgentConfig

func (c *Client) EditAgentConfig(ctx context.Context, filename string, config latest.Config) (*api.EditAgentConfigResponse, error)

EditAgentConfig edits an agent configuration

func (*Client) ExportAgents

func (c *Client) ExportAgents(ctx context.Context) (*api.ExportAgentsResponse, error)

ExportAgents exports multiple agents as a zip file

func (*Client) GetAgent

func (c *Client) GetAgent(ctx context.Context, id string) (*latest.Config, error)

GetAgent retrieves an agent by ID

func (*Client) GetAgentToolCount

func (c *Client) GetAgentToolCount(ctx context.Context, agentFilename, agentName string) (int, error)

GetAgentToolCount returns the number of tools available for an agent.

func (*Client) GetAgents

func (c *Client) GetAgents(ctx context.Context) ([]api.Agent, error)

GetAgents retrieves all available agents

func (*Client) GetDesktopToken

func (c *Client) GetDesktopToken(ctx context.Context) (*api.DesktopTokenResponse, error)

GetDesktopToken retrieves a desktop authentication token

func (*Client) GetSession

func (c *Client) GetSession(ctx context.Context, id string) (*api.SessionResponse, error)

GetSession retrieves a session by ID

func (*Client) GetSessions

func (c *Client) GetSessions(ctx context.Context) ([]api.SessionsResponse, error)

GetSessions retrieves all sessions

func (*Client) ImportAgent

func (c *Client) ImportAgent(ctx context.Context, filePath string) (*api.ImportAgentResponse, error)

ImportAgent imports an agent from a file path

func (*Client) PullAgent

func (c *Client) PullAgent(ctx context.Context, name string) (*api.PullAgentResponse, error)

PullAgent pulls an agent from a remote registry

func (*Client) PushAgent

func (c *Client) PushAgent(ctx context.Context, filepath, tag string) (*api.PushAgentResponse, error)

PushAgent pushes an agent to a remote registry

func (*Client) ResumeElicitation

func (c *Client) ResumeElicitation(ctx context.Context, sessionID string, action tools.ElicitationAction, content map[string]any) error

func (*Client) ResumeSession

func (c *Client) ResumeSession(ctx context.Context, id, confirmation, reason, toolName string) error

ResumeSession resumes a session by ID with optional rejection reason or tool name

func (*Client) RunAgent

func (c *Client) RunAgent(ctx context.Context, sessionID, agent string, messages []api.Message) (<-chan Event, error)

RunAgent executes an agent and returns a channel of streaming events

func (*Client) RunAgentWithAgentName

func (c *Client) RunAgentWithAgentName(ctx context.Context, sessionID, agent, agentName string, messages []api.Message) (<-chan Event, error)

RunAgentWithAgentName executes an agent with a specific agent name and returns a channel of streaming events

func (*Client) UpdateSessionTitle

func (c *Client) UpdateSessionTitle(ctx context.Context, sessionID, title string) error

UpdateSessionTitle updates the title of a session

type ClientOption

type ClientOption func(*Client)

ClientOption is a function for configuring the Client

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the HTTP client timeout

type ContextOverflowError

type ContextOverflowError struct {
	Underlying error
}

ContextOverflowError wraps an underlying error to indicate that the failure was caused by the conversation context exceeding the model's context window. This is used to trigger auto-compaction in the runtime loop instead of surfacing raw HTTP errors to the user.

func (*ContextOverflowError) Error

func (e *ContextOverflowError) Error() string

func (*ContextOverflowError) Unwrap

func (e *ContextOverflowError) Unwrap() error

type CurrentAgentInfo

type CurrentAgentInfo struct {
	Name        string
	Description string
	Commands    types.Commands
}

type ElicitationError

type ElicitationError struct {
	Action  string
	Message string
}

ElicitationError represents an error from a declined/cancelled elicitation

func (*ElicitationError) Error

func (e *ElicitationError) Error() string

type ElicitationRequestEvent

type ElicitationRequestEvent struct {
	Type          string         `json:"type"`
	Message       string         `json:"message"`
	Mode          string         `json:"mode,omitempty"` // "form" or "url"
	Schema        any            `json:"schema,omitempty"`
	URL           string         `json:"url,omitempty"`
	ElicitationID string         `json:"elicitation_id,omitempty"`
	Meta          map[string]any `json:"meta,omitempty"`
	AgentContext
}

ElicitationRequestEvent is sent when an elicitation request is received from an MCP server

type ElicitationRequestHandler

type ElicitationRequestHandler func(ctx context.Context, message string, schema map[string]any) (map[string]any, error)

ElicitationRequestHandler is a function type for handling elicitation requests

type ElicitationResult

type ElicitationResult struct {
	Action  tools.ElicitationAction
	Content map[string]any // The submitted form data (only present when action is "accept")
}

ElicitationResult represents the result of an elicitation request

type ErrorEvent

type ErrorEvent struct {
	Type  string `json:"type"`
	Error string `json:"error"`
	AgentContext
}

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
}

ErrorResponse represents an error response from the API

type Event

type Event interface {
	GetAgentName() string
}

func AgentChoice

func AgentChoice(agentName, content string) Event

func AgentChoiceReasoning

func AgentChoiceReasoning(agentName, content string) Event

func AgentInfo

func AgentInfo(agentName, model, description, welcomeMessage string) Event

func AgentSwitching

func AgentSwitching(switching bool, fromAgent, toAgent string) Event

func Authorization

func Authorization(confirmation tools.ElicitationAction, agentName string) Event

func ElicitationRequest

func ElicitationRequest(message, mode string, schema any, url, elicitationID string, meta map[string]any, agentName string) Event

func Error

func Error(msg string) Event

func HookBlocked

func HookBlocked(toolCall tools.ToolCall, toolDefinition tools.Tool, message, agentName string) Event

func MCPInitFinished

func MCPInitFinished(agentName string) Event

func MCPInitStarted

func MCPInitStarted(agentName string) Event

func MaxIterationsReached

func MaxIterationsReached(maxIterations int) Event

func MessageAdded

func MessageAdded(sessionID string, msg *session.Message, agentName string) Event

func ModelFallback

func ModelFallback(agentName, failedModel, fallbackModel, reason string, attempt, maxAttempts int) Event

ModelFallback creates a new ModelFallbackEvent.

func NewTokenUsageEvent

func NewTokenUsageEvent(sessionID, agentName string, usage *Usage) Event

NewTokenUsageEvent creates a TokenUsageEvent with the given usage data.

func PartialToolCall

func PartialToolCall(toolCall tools.ToolCall, toolDefinition tools.Tool, agentName string) Event

func RAGIndexingCompleted

func RAGIndexingCompleted(ragName, strategyName, agentName string) Event

func RAGIndexingProgress

func RAGIndexingProgress(ragName, strategyName string, current, total int, agentName string) Event

func RAGIndexingStarted

func RAGIndexingStarted(ragName, strategyName, agentName string) Event

func SessionCompaction

func SessionCompaction(sessionID, status, agentName string) Event

func SessionSummary

func SessionSummary(sessionID, summary, agentName string) Event

func SessionTitle

func SessionTitle(sessionID, title string) Event

func ShellOutput

func ShellOutput(output string) Event

func StreamStarted

func StreamStarted(sessionID, agentName string) Event

func StreamStopped

func StreamStopped(sessionID, agentName string) Event

func SubSessionCompleted

func SubSessionCompleted(parentSessionID string, subSession any, agentName string) Event

func TeamInfo

func TeamInfo(availableAgents []AgentDetails, currentAgent string) Event

func ToolCall

func ToolCall(toolCall tools.ToolCall, toolDefinition tools.Tool, agentName string) Event

func ToolCallConfirmation

func ToolCallConfirmation(toolCall tools.ToolCall, toolDefinition tools.Tool, agentName string) Event

func ToolCallResponse

func ToolCallResponse(toolCall tools.ToolCall, toolDefinition tools.Tool, result *tools.ToolCallResult, response, agentName string) Event

func ToolsetInfo

func ToolsetInfo(availableTools int, loading bool, agentName string) Event

func UserMessage

func UserMessage(message, sessionID string, multiContent []chat.MessagePart, sessionPos ...int) Event

func Warning

func Warning(message, agentName string) Event

type HookBlockedEvent

type HookBlockedEvent struct {
	Type           string         `json:"type"`
	ToolCall       tools.ToolCall `json:"tool_call"`
	ToolDefinition tools.Tool     `json:"tool_definition"`
	Message        string         `json:"message"`
	AgentContext
}

HookBlockedEvent is sent when a pre-tool hook blocks a tool call

type LocalRuntime

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

LocalRuntime manages the execution of agents

func NewLocalRuntime

func NewLocalRuntime(agents *team.Team, opts ...Opt) (*LocalRuntime, error)

NewLocalRuntime creates a new LocalRuntime without the persistence wrapper. This is useful for testing or when persistence is handled externally.

func (*LocalRuntime) AvailableModels

func (r *LocalRuntime) AvailableModels(ctx context.Context) []ModelChoice

AvailableModels implements ModelSwitcher for LocalRuntime.

func (*LocalRuntime) Close

func (r *LocalRuntime) Close() error

Close releases resources held by the runtime, including the session store.

func (*LocalRuntime) CurrentAgent

func (r *LocalRuntime) CurrentAgent() *agent.Agent

CurrentAgent returns the current agent

func (*LocalRuntime) CurrentAgentCommands

func (r *LocalRuntime) CurrentAgentCommands(context.Context) types.Commands

func (*LocalRuntime) CurrentAgentInfo

func (r *LocalRuntime) CurrentAgentInfo(context.Context) CurrentAgentInfo

func (*LocalRuntime) CurrentAgentName

func (r *LocalRuntime) CurrentAgentName() string

func (*LocalRuntime) CurrentAgentSkillsToolset

func (r *LocalRuntime) CurrentAgentSkillsToolset() *builtin.SkillsToolset

CurrentAgentSkillsToolset returns the skills toolset for the current agent, or nil if not enabled.

func (*LocalRuntime) CurrentAgentSubAgentNames

func (r *LocalRuntime) CurrentAgentSubAgentNames() []string

CurrentAgentSubAgentNames implements agenttool.Runner.

func (*LocalRuntime) CurrentAgentTools

func (r *LocalRuntime) CurrentAgentTools(ctx context.Context) ([]tools.Tool, error)

CurrentAgentTools returns the tools available to the current agent. This starts the toolsets if needed and returns all available tools.

func (*LocalRuntime) CurrentMCPPrompts

func (r *LocalRuntime) CurrentMCPPrompts(ctx context.Context) map[string]mcptools.PromptInfo

CurrentMCPPrompts returns the available MCP prompts from all active MCP toolsets for the current agent. It discovers prompts by calling ListPrompts on each MCP toolset and aggregates the results into a map keyed by prompt name.

func (*LocalRuntime) EmitStartupInfo

func (r *LocalRuntime) EmitStartupInfo(ctx context.Context, sess *session.Session, events chan Event)

EmitStartupInfo emits initial agent, team, and toolset information for immediate sidebar display. When sess is non-nil and contains token data, a TokenUsageEvent is also emitted so that the sidebar can display context usage percentage on session restore.

func (*LocalRuntime) ExecuteMCPPrompt

func (r *LocalRuntime) ExecuteMCPPrompt(ctx context.Context, promptName string, arguments map[string]string) (string, error)

ExecuteMCPPrompt executes an MCP prompt with provided arguments and returns the content.

func (*LocalRuntime) InitializeRAG

func (r *LocalRuntime) InitializeRAG(ctx context.Context, events chan Event)

InitializeRAG is called within RunStream as a fallback when background init wasn't used (e.g., for exec command or API mode where there's no App)

func (*LocalRuntime) OnToolsChanged

func (r *LocalRuntime) OnToolsChanged(handler func(Event))

OnToolsChanged registers a handler that is called when an MCP toolset reports a tool list change outside of a RunStream. This allows the UI to update the tool count immediately.

func (*LocalRuntime) PermissionsInfo

func (r *LocalRuntime) PermissionsInfo() *PermissionsInfo

PermissionsInfo returns the team-level permission patterns. Returns nil if no permissions are configured.

func (*LocalRuntime) ResetStartupInfo

func (r *LocalRuntime) ResetStartupInfo()

ResetStartupInfo resets the startup info emission flag. This should be called when replacing a session to allow re-emission of agent, team, and toolset info to the UI.

func (*LocalRuntime) Resume

func (r *LocalRuntime) Resume(_ context.Context, req ResumeRequest)

func (*LocalRuntime) ResumeElicitation

func (r *LocalRuntime) ResumeElicitation(ctx context.Context, action tools.ElicitationAction, content map[string]any) error

ResumeElicitation sends an elicitation response back to a waiting elicitation request

func (*LocalRuntime) Run

func (r *LocalRuntime) Run(ctx context.Context, sess *session.Session) ([]session.Message, error)

Run starts the agent's interaction loop

func (*LocalRuntime) RunAgent

RunAgent implements agenttool.Runner. It starts a sub-agent synchronously and blocks until completion or cancellation.

func (*LocalRuntime) RunStream

func (r *LocalRuntime) RunStream(ctx context.Context, sess *session.Session) <-chan Event

RunStream starts the agent's interaction loop and returns a channel of events

func (*LocalRuntime) SessionStore

func (r *LocalRuntime) SessionStore() session.Store

SessionStore returns the session store for browsing/loading past sessions.

func (*LocalRuntime) SetAgentModel

func (r *LocalRuntime) SetAgentModel(ctx context.Context, agentName, modelRef string) error

SetAgentModel implements ModelSwitcher for LocalRuntime.

func (*LocalRuntime) SetCurrentAgent

func (r *LocalRuntime) SetCurrentAgent(agentName string) error

func (*LocalRuntime) StartBackgroundRAGInit

func (r *LocalRuntime) StartBackgroundRAGInit(ctx context.Context, sendEvent func(Event))

StartBackgroundRAGInit initializes RAG in background and forwards events Should be called early (e.g., by App) to start indexing before RunStream

func (*LocalRuntime) Summarize

func (r *LocalRuntime) Summarize(ctx context.Context, sess *session.Session, additionalPrompt string, events chan Event)

Summarize generates a summary for the session based on the conversation history. The additionalPrompt parameter allows users to provide additional instructions for the summarization (e.g., "focus on code changes" or "include action items").

func (*LocalRuntime) TitleGenerator

func (r *LocalRuntime) TitleGenerator() *sessiontitle.Generator

TitleGenerator returns a title generator for automatic session title generation.

func (*LocalRuntime) UpdateSessionTitle

func (r *LocalRuntime) UpdateSessionTitle(ctx context.Context, sess *session.Session, title string) error

UpdateSessionTitle persists the session title via the session store.

type MCPInitFinishedEvent

type MCPInitFinishedEvent struct {
	Type string `json:"type"`
	AgentContext
}

type MCPInitStartedEvent

type MCPInitStartedEvent struct {
	Type string `json:"type"`
	AgentContext
}

MCPInitStartedEvent is for MCP initialization lifecycle events

type MaxIterationsReachedEvent

type MaxIterationsReachedEvent struct {
	Type          string `json:"type"`
	MaxIterations int    `json:"max_iterations"`
	AgentContext
}

type MessageAddedEvent

type MessageAddedEvent struct {
	Type      string           `json:"type"`
	SessionID string           `json:"session_id"`
	Message   *session.Message `json:"-"`
	AgentContext
}

MessageAddedEvent is emitted when a message is added to the session. This event is used by the PersistentRuntime wrapper to persist messages.

func (*MessageAddedEvent) GetAgentName

func (e *MessageAddedEvent) GetAgentName() string

type MessageUsage

type MessageUsage struct {
	chat.Usage
	chat.RateLimit
	Cost  float64
	Model string
}

MessageUsage contains per-message usage data to include in TokenUsageEvent. It embeds chat.Usage and adds Cost and Model fields.

type ModelChoice

type ModelChoice struct {
	// Name is the display name (config key)
	Name string
	// Ref is the model reference used internally (e.g., "my_model" or "openai/gpt-4o")
	Ref string
	// Provider is the provider name (e.g., "openai", "anthropic")
	Provider string
	// Model is the specific model name (e.g., "gpt-4o", "claude-sonnet-4-0")
	Model string
	// IsDefault indicates this is the agent's configured default model
	IsDefault bool
	// IsCurrent indicates this is the currently active model for the agent
	IsCurrent bool
	// IsCustom indicates this is a custom model from the session history (not from config)
	IsCustom bool
	// IsCatalog indicates this is a model from the models.dev catalog
	IsCatalog bool
}

ModelChoice represents a model available for selection in the TUI picker.

type ModelFallbackEvent

type ModelFallbackEvent struct {
	Type          string `json:"type"`
	FailedModel   string `json:"failed_model"`
	FallbackModel string `json:"fallback_model"`
	Reason        string `json:"reason"`
	Attempt       int    `json:"attempt"`      // Current attempt number (1-indexed)
	MaxAttempts   int    `json:"max_attempts"` // Total attempts allowed for this model
	AgentContext
}

ModelFallbackEvent is emitted when the runtime switches to a fallback model after the previous model in the chain fails. This can happen due to: - Retryable errors (5xx, timeouts) after exhausting retries - Non-retryable errors (429, 4xx) which skip retries and move immediately to fallback

type ModelStore

type ModelStore interface {
	GetModel(ctx context.Context, modelID string) (*modelsdev.Model, error)
	GetDatabase(ctx context.Context) (*modelsdev.Database, error)
}

type ModelSwitcher

type ModelSwitcher interface {
	// SetAgentModel sets a model override for the specified agent.
	// modelRef can be:
	// - "" (empty) to clear the override and use the agent's default model
	// - A model name from the config (e.g., "my_fast_model")
	// - An inline model spec (e.g., "openai/gpt-4o")
	SetAgentModel(ctx context.Context, agentName, modelRef string) error

	// AvailableModels returns the list of models available for selection.
	// This includes all models defined in the config, with the current agent's
	// default model marked as IsDefault.
	AvailableModels(ctx context.Context) []ModelChoice
}

ModelSwitcher is an optional interface for runtimes that support changing the model for the current agent at runtime. This is used by the TUI for model switching.

type ModelSwitcherConfig

type ModelSwitcherConfig struct {
	// Models is the map of model names to configurations from the loaded config
	Models map[string]latest.ModelConfig
	// Providers is the map of custom provider configurations
	Providers map[string]latest.ProviderConfig
	// ModelsGateway is the gateway URL if configured
	ModelsGateway string
	// EnvProvider provides access to environment variables
	EnvProvider environment.Provider
	// AgentDefaultModels maps agent names to their configured default model references
	AgentDefaultModels map[string]string
}

ModelSwitcherConfig holds the configuration needed for model switching. This is populated by the app layer when creating the runtime.

type Opt

type Opt func(*LocalRuntime)

func WithCurrentAgent

func WithCurrentAgent(agentName string) Opt

func WithEnv

func WithEnv(env []string) Opt

WithEnv sets the environment variables for hooks execution

func WithManagedOAuth

func WithManagedOAuth(managed bool) Opt

func WithModelStore

func WithModelStore(store ModelStore) Opt

func WithModelSwitcherConfig

func WithModelSwitcherConfig(cfg *ModelSwitcherConfig) Opt

WithModelSwitcherConfig sets the model switcher configuration for the runtime.

func WithSessionCompaction

func WithSessionCompaction(sessionCompaction bool) Opt

func WithSessionStore

func WithSessionStore(store session.Store) Opt

func WithTracer

func WithTracer(t trace.Tracer) Opt

WithTracer sets a custom OpenTelemetry tracer; if not provided, tracing is disabled (no-op).

func WithWorkingDir

func WithWorkingDir(dir string) Opt

WithWorkingDir sets the working directory for hooks execution

type PartialToolCallEvent

type PartialToolCallEvent struct {
	Type           string         `json:"type"`
	ToolCall       tools.ToolCall `json:"tool_call"`
	ToolDefinition tools.Tool     `json:"tool_definition"`
	AgentContext
}

PartialToolCallEvent is sent when a tool call is first received (partial/complete)

type PermissionsInfo

type PermissionsInfo struct {
	Allow []string
	Ask   []string
	Deny  []string
}

PermissionsInfo contains the allow, ask, and deny patterns for tool permissions.

type PersistentRuntime

type PersistentRuntime struct {
	*LocalRuntime
}

PersistentRuntime wraps a LocalRuntime and persists session changes to a store based on emitted events.

func (*PersistentRuntime) Run

Run wraps the inner runtime's Run method

func (*PersistentRuntime) RunStream

func (r *PersistentRuntime) RunStream(ctx context.Context, sess *session.Session) <-chan Event

RunStream wraps the inner runtime's RunStream and intercepts events to persist session changes to the store.

type RAGIndexingCompletedEvent

type RAGIndexingCompletedEvent struct {
	Type         string `json:"type"`
	RAGName      string `json:"rag_name"`
	StrategyName string `json:"strategy_name"`
	AgentContext
}

type RAGIndexingProgressEvent

type RAGIndexingProgressEvent struct {
	Type         string `json:"type"`
	RAGName      string `json:"rag_name"`
	StrategyName string `json:"strategy_name"`
	Current      int    `json:"current"`
	Total        int    `json:"total"`
	AgentContext
}

type RAGIndexingStartedEvent

type RAGIndexingStartedEvent struct {
	Type         string `json:"type"`
	RAGName      string `json:"rag_name"`
	StrategyName string `json:"strategy_name"`
	AgentContext
}

RAGIndexingStartedEvent is for RAG lifecycle events

type RAGInitializer

type RAGInitializer interface {
	StartBackgroundRAGInit(ctx context.Context, sendEvent func(Event))
}

RAGInitializer is implemented by runtimes that support background RAG initialization. Local runtimes use this to start indexing early; remote runtimes typically do not.

type RemoteClient

type RemoteClient interface {
	// GetAgent retrieves an agent configuration by ID
	GetAgent(ctx context.Context, id string) (*latest.Config, error)

	// CreateSession creates a new session
	CreateSession(ctx context.Context, sessTemplate *session.Session) (*session.Session, error)

	// ResumeSession resumes a paused session with optional rejection reason or tool name
	ResumeSession(ctx context.Context, id, confirmation, reason, toolName string) error

	// ResumeElicitation sends an elicitation response
	ResumeElicitation(ctx context.Context, sessionID string, action tools.ElicitationAction, content map[string]any) error

	// RunAgent executes an agent and returns a channel of streaming events
	RunAgent(ctx context.Context, sessionID, agent string, messages []api.Message) (<-chan Event, error)

	// RunAgentWithAgentName executes an agent with a specific agent name
	RunAgentWithAgentName(ctx context.Context, sessionID, agent, agentName string, messages []api.Message) (<-chan Event, error)

	// UpdateSessionTitle updates the title of a session
	UpdateSessionTitle(ctx context.Context, sessionID, title string) error

	// GetAgentToolCount returns the number of tools available for an agent
	GetAgentToolCount(ctx context.Context, agentFilename, agentName string) (int, error)
}

RemoteClient is the interface that both HTTP and Connect-RPC clients implement for communicating with a remote docker agent server.

type RemoteRuntime

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

RemoteRuntime implements the Runtime interface using a remote client. It works with any client that implements the RemoteClient interface, including both HTTP (Client) and Connect-RPC (ConnectRPCClient) clients.

func NewRemoteRuntime

func NewRemoteRuntime(client RemoteClient, opts ...RemoteRuntimeOption) (*RemoteRuntime, error)

NewRemoteRuntime creates a new remote runtime that implements the Runtime interface. It accepts any client that implements the RemoteClient interface.

func (*RemoteRuntime) Close

func (r *RemoteRuntime) Close() error

Close is a no-op for remote runtimes.

func (*RemoteRuntime) CurrentAgentInfo

func (r *RemoteRuntime) CurrentAgentInfo(ctx context.Context) CurrentAgentInfo

func (*RemoteRuntime) CurrentAgentName

func (r *RemoteRuntime) CurrentAgentName() string

CurrentAgentName returns the name of the currently active agent

func (*RemoteRuntime) CurrentAgentSkillsToolset

func (r *RemoteRuntime) CurrentAgentSkillsToolset() *builtin.SkillsToolset

CurrentAgentSkillsToolset returns nil for remote runtimes since skills are managed server-side.

func (*RemoteRuntime) CurrentAgentTools

func (r *RemoteRuntime) CurrentAgentTools(_ context.Context) ([]tools.Tool, error)

CurrentAgentTools returns the tools for the current agent. For remote runtime, this returns nil as tools are managed server-side.

func (*RemoteRuntime) CurrentMCPPrompts

func (r *RemoteRuntime) CurrentMCPPrompts(context.Context) map[string]mcp.PromptInfo

CurrentMCPPrompts is not supported on remote runtimes.

func (*RemoteRuntime) EmitStartupInfo

func (r *RemoteRuntime) EmitStartupInfo(ctx context.Context, _ *session.Session, events chan Event)

EmitStartupInfo emits initial agent, team, and toolset information

func (*RemoteRuntime) ExecuteMCPPrompt

func (r *RemoteRuntime) ExecuteMCPPrompt(context.Context, string, map[string]string) (string, error)

ExecuteMCPPrompt is not supported on remote runtimes.

func (*RemoteRuntime) PermissionsInfo

func (r *RemoteRuntime) PermissionsInfo() *PermissionsInfo

PermissionsInfo returns nil for remote runtime since permissions are handled server-side.

func (*RemoteRuntime) ResetStartupInfo

func (r *RemoteRuntime) ResetStartupInfo()

ResetStartupInfo is a no-op for remote runtime.

func (*RemoteRuntime) Resume

func (r *RemoteRuntime) Resume(ctx context.Context, req ResumeRequest)

Resume allows resuming execution after user confirmation

func (*RemoteRuntime) ResumeElicitation

func (r *RemoteRuntime) ResumeElicitation(ctx context.Context, action tools.ElicitationAction, content map[string]any) error

ResumeElicitation sends an elicitation response back to a waiting elicitation request

func (*RemoteRuntime) Run

func (r *RemoteRuntime) Run(ctx context.Context, sess *session.Session) ([]session.Message, error)

Run starts the agent's interaction loop and returns the final messages

func (*RemoteRuntime) RunStream

func (r *RemoteRuntime) RunStream(ctx context.Context, sess *session.Session) <-chan Event

RunStream starts the agent's interaction loop and returns a channel of events

func (*RemoteRuntime) SessionStore

func (r *RemoteRuntime) SessionStore() session.Store

SessionStore returns nil for remote runtime since session storage is handled server-side.

func (*RemoteRuntime) SetCurrentAgent

func (r *RemoteRuntime) SetCurrentAgent(agentName string) error

SetCurrentAgent sets the currently active agent for subsequent user messages

func (*RemoteRuntime) Summarize

func (r *RemoteRuntime) Summarize(_ context.Context, sess *session.Session, _ string, events chan Event)

Summarize generates a summary for the session

func (*RemoteRuntime) TitleGenerator

func (r *RemoteRuntime) TitleGenerator() *sessiontitle.Generator

TitleGenerator is not supported on remote runtimes (titles are generated server-side).

func (*RemoteRuntime) UpdateSessionTitle

func (r *RemoteRuntime) UpdateSessionTitle(ctx context.Context, sess *session.Session, title string) error

UpdateSessionTitle updates the title of the current session on the remote server.

type RemoteRuntimeOption

type RemoteRuntimeOption func(*RemoteRuntime)

RemoteRuntimeOption is a function for configuring the RemoteRuntime

func WithRemoteAgentFilename

func WithRemoteAgentFilename(filename string) RemoteRuntimeOption

WithRemoteAgentFilename sets the agent filename to use with the remote API

func WithRemoteCurrentAgent

func WithRemoteCurrentAgent(agentName string) RemoteRuntimeOption

WithRemoteCurrentAgent sets the current agent name

type ResumeRequest

type ResumeRequest struct {
	Type     ResumeType
	Reason   string // Optional; primarily used with ResumeTypeReject
	ToolName string // Optional; used with ResumeTypeApproveTool to specify which tool to always allow
}

ResumeRequest carries the user's confirmation decision along with an optional reason (used when rejecting a tool call to help the model understand why).

func ResumeApprove

func ResumeApprove() ResumeRequest

ResumeApprove creates a ResumeRequest to approve a single tool call.

func ResumeApproveSession

func ResumeApproveSession() ResumeRequest

ResumeApproveSession creates a ResumeRequest to approve all tool calls for the session.

func ResumeApproveTool

func ResumeApproveTool(toolName string) ResumeRequest

ResumeApproveTool creates a ResumeRequest to always approve a specific tool for the session.

func ResumeReject

func ResumeReject(reason string) ResumeRequest

ResumeReject creates a ResumeRequest to reject a tool call with an optional reason.

type ResumeType

type ResumeType string
const (
	ResumeTypeApprove        ResumeType = "approve"
	ResumeTypeApproveSession ResumeType = "approve-session"
	ResumeTypeApproveTool    ResumeType = "approve-tool"
	ResumeTypeReject         ResumeType = "reject"
)

func ValidResumeTypes

func ValidResumeTypes() []ResumeType

ValidResumeTypes returns all allowed confirmation values

type Runtime

type Runtime interface {
	// CurrentAgentInfo returns information about the currently active agent
	CurrentAgentInfo(ctx context.Context) CurrentAgentInfo
	// CurrentAgentName returns the name of the currently active agent
	CurrentAgentName() string
	// SetCurrentAgent sets the currently active agent for subsequent user messages
	SetCurrentAgent(agentName string) error
	// CurrentAgentTools returns the tools for the active agent
	CurrentAgentTools(ctx context.Context) ([]tools.Tool, error)
	// EmitStartupInfo emits initial agent, team, and toolset information for immediate display.
	// When sess is non-nil and contains token data, a TokenUsageEvent is also emitted
	// so the UI can display context usage percentage on session restore.
	EmitStartupInfo(ctx context.Context, sess *session.Session, events chan Event)
	// ResetStartupInfo resets the startup info emission flag, allowing re-emission
	ResetStartupInfo()
	// RunStream starts the agent's interaction loop and returns a channel of events
	RunStream(ctx context.Context, sess *session.Session) <-chan Event
	// Run starts the agent's interaction loop and returns the final messages
	Run(ctx context.Context, sess *session.Session) ([]session.Message, error)
	// Resume allows resuming execution after user confirmation.
	// The ResumeRequest carries the decision type and an optional reason (for rejections).
	Resume(ctx context.Context, req ResumeRequest)
	// ResumeElicitation sends an elicitation response back to a waiting elicitation request
	ResumeElicitation(_ context.Context, action tools.ElicitationAction, content map[string]any) error
	// SessionStore returns the session store for browsing/loading past sessions.
	// Returns nil if no persistent session store is configured.
	SessionStore() session.Store

	// Summarize generates a summary for the session
	Summarize(ctx context.Context, sess *session.Session, additionalPrompt string, events chan Event)

	// PermissionsInfo returns the team-level permission patterns (allow/ask/deny).
	// Returns nil if no permissions are configured.
	PermissionsInfo() *PermissionsInfo

	// CurrentAgentSkillsToolset returns the skills toolset for the current agent, or nil if skills are not enabled.
	CurrentAgentSkillsToolset() *builtin.SkillsToolset

	// CurrentMCPPrompts returns MCP prompts available from the current agent's toolsets.
	// Returns an empty map if no MCP prompts are available.
	CurrentMCPPrompts(ctx context.Context) map[string]mcptools.PromptInfo

	// ExecuteMCPPrompt executes a named MCP prompt with the given arguments.
	ExecuteMCPPrompt(ctx context.Context, promptName string, arguments map[string]string) (string, error)

	// UpdateSessionTitle persists a new title for the current session.
	UpdateSessionTitle(ctx context.Context, sess *session.Session, title string) error

	// TitleGenerator returns a generator for automatic session titles, or nil
	// if the runtime does not support local title generation (e.g. remote runtimes).
	TitleGenerator() *sessiontitle.Generator

	// Close releases resources held by the runtime (e.g., session store connections).
	Close() error
}

Runtime defines the contract for runtime execution

func New

func New(agents *team.Team, opts ...Opt) (Runtime, error)

New creates a new runtime for an agent and its team. The runtime automatically persists session changes to the configured store. Returns a Runtime interface which wraps LocalRuntime with persistence handling.

type SessionCompactionEvent

type SessionCompactionEvent struct {
	Type      string `json:"type"`
	SessionID string `json:"session_id"`
	Status    string `json:"status"`
	AgentContext
}

type SessionSummaryEvent

type SessionSummaryEvent struct {
	Type      string `json:"type"`
	SessionID string `json:"session_id"`
	Summary   string `json:"summary"`
	AgentContext
}

type SessionTitleEvent

type SessionTitleEvent struct {
	Type      string `json:"type"`
	SessionID string `json:"session_id"`
	Title     string `json:"title"`
	AgentContext
}

type ShellOutputEvent

type ShellOutputEvent struct {
	Type   string `json:"type"`
	Output string `json:"output"`
	AgentContext
}

type StreamStartedEvent

type StreamStartedEvent struct {
	Type      string `json:"type"`
	SessionID string `json:"session_id,omitempty"`
	AgentContext
}

type StreamStoppedEvent

type StreamStoppedEvent struct {
	Type      string `json:"type"`
	SessionID string `json:"session_id,omitempty"`
	AgentContext
}

type SubSessionCompletedEvent

type SubSessionCompletedEvent struct {
	Type            string `json:"type"`
	ParentSessionID string `json:"parent_session_id"`
	SubSession      any    `json:"sub_session"` // *session.Session
	AgentContext
}

SubSessionCompletedEvent is emitted when a sub-session completes and is added to parent. This event is used by the PersistentRuntime wrapper to persist sub-sessions.

func (*SubSessionCompletedEvent) GetAgentName

func (e *SubSessionCompletedEvent) GetAgentName() string

type TeamInfoEvent

type TeamInfoEvent struct {
	Type            string         `json:"type"`
	AvailableAgents []AgentDetails `json:"available_agents"`
	CurrentAgent    string         `json:"current_agent"`
	AgentContext
}

TeamInfoEvent is sent when team information is available

type TokenUsageEvent

type TokenUsageEvent struct {
	Type      string `json:"type"`
	SessionID string `json:"session_id"`
	Usage     *Usage `json:"usage"`
	AgentContext
}

type ToolCallConfirmationEvent

type ToolCallConfirmationEvent struct {
	Type           string         `json:"type"`
	ToolCall       tools.ToolCall `json:"tool_call"`
	ToolDefinition tools.Tool     `json:"tool_definition"`
	AgentContext
}

type ToolCallEvent

type ToolCallEvent struct {
	Type           string         `json:"type"`
	ToolCall       tools.ToolCall `json:"tool_call"`
	ToolDefinition tools.Tool     `json:"tool_definition"`
	AgentContext
}

ToolCallEvent is sent when a tool call is received

type ToolCallResponseEvent

type ToolCallResponseEvent struct {
	Type           string                `json:"type"`
	ToolCall       tools.ToolCall        `json:"tool_call"`
	ToolDefinition tools.Tool            `json:"tool_definition"`
	Response       string                `json:"response"`
	Result         *tools.ToolCallResult `json:"result,omitempty"`
	AgentContext
}

type ToolHandlerFunc

type ToolHandlerFunc func(ctx context.Context, sess *session.Session, toolCall tools.ToolCall, events chan Event) (*tools.ToolCallResult, error)

ToolHandlerFunc is a function type for handling tool calls

type ToolsChangeSubscriber

type ToolsChangeSubscriber interface {
	OnToolsChanged(handler func(Event))
}

ToolsChangeSubscriber is implemented by runtimes that can notify when toolsets report a change in their tool list (e.g. after an MCP ToolListChanged notification). The provided callback is invoked outside of any RunStream, so the UI can update the tool count immediately.

type ToolsetInfoEvent

type ToolsetInfoEvent struct {
	Type           string `json:"type"`
	AvailableTools int    `json:"available_tools"`
	Loading        bool   `json:"loading"`
	AgentContext
}

ToolsetInfoEvent is sent when toolset information is available When Loading is true, more tools may still be loading (e.g., MCP servers starting)

type Usage

type Usage struct {
	InputTokens   int64         `json:"input_tokens"`
	OutputTokens  int64         `json:"output_tokens"`
	ContextLength int64         `json:"context_length"`
	ContextLimit  int64         `json:"context_limit"`
	Cost          float64       `json:"cost"`
	LastMessage   *MessageUsage `json:"last_message,omitempty"`
}

func SessionUsage

func SessionUsage(sess *session.Session, contextLimit int64) *Usage

SessionUsage builds a Usage from the session's current token counts, the model's context limit, and the session's own cost.

type UserMessageEvent

type UserMessageEvent struct {
	Type            string             `json:"type"`
	Message         string             `json:"message"`
	MultiContent    []chat.MessagePart `json:"multi_content,omitempty"`
	SessionID       string             `json:"session_id"`
	SessionPosition int                `json:"session_position"` // Index in session.Messages, -1 if unknown
	AgentContext
}

UserMessageEvent is sent when a user message is received

type WarningEvent

type WarningEvent struct {
	Type    string `json:"type"`
	Message string `json:"message"`
	AgentContext
}

Jump to

Keyboard shortcuts

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