runtime

package
v1.53.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	ApprovalDecisionAllow    = "allow"
	ApprovalDecisionDeny     = "deny"
	ApprovalDecisionCanceled = "canceled"

	ApprovalSourceYolo                    = "yolo"
	ApprovalSourceSessionPermissionsAllow = "session_permissions_allow"
	ApprovalSourceSessionPermissionsDeny  = "session_permissions_deny"
	ApprovalSourceTeamPermissionsAllow    = "team_permissions_allow"
	ApprovalSourceTeamPermissionsDeny     = "team_permissions_deny"
	ApprovalSourcePreToolUseHookAllow     = "pre_tool_use_hook_allow"
	ApprovalSourcePreToolUseHookDeny      = "pre_tool_use_hook_deny"
	ApprovalSourceReadOnlyHint            = "readonly_hint"
	ApprovalSourceUserApproved            = "user_approved"
	ApprovalSourceUserApprovedSession     = "user_approved_session"
	ApprovalSourceUserApprovedTool        = "user_approved_tool"
	ApprovalSourceUserRejected            = "user_rejected"
	ApprovalSourceContextCanceled         = "context_canceled"
)

Verdicts and sources for hooks.EventOnToolApprovalDecision. Constants instead of literals so the contract between executeWithApproval and the hook protocol is discoverable from the runtime side and a typo trips a compile error.

View Source
const (
	// ResumeTypeApprove approves the single pending tool call.
	ResumeTypeApprove = toolexec.ResumeTypeApprove
	// ResumeTypeApproveSession approves the pending tool call and every
	// subsequent permission-gated call for the rest of the session.
	ResumeTypeApproveSession = toolexec.ResumeTypeApproveSession
	// ResumeTypeApproveTool approves the pending call and every future
	// call to the same tool name within the session.
	ResumeTypeApproveTool = toolexec.ResumeTypeApproveTool
	// ResumeTypeReject rejects the pending tool call.
	ResumeTypeReject = toolexec.ResumeTypeReject
)
View Source
const BuiltinCacheResponse = "cache_response"

BuiltinCacheResponse is the name of the builtin stop hook that persists an agent's response into its configured response cache. It is auto-injected by [LocalRuntime.hooksExec] when the agent has a cache configured, mirroring the way builtins.AddDate et al. are auto-injected from agent flags via builtins.ApplyAgentDefaults.

Variables

This section is empty.

Functions

func IsValidResumeType

func IsValidResumeType(t ResumeType) bool

IsValidResumeType validates confirmation values coming from /resume.

The runtime may be resumed by multiple entry points (API, CLI, TUI, tests). Even if upstream layers perform validation, the runtime must never assume the ResumeType is valid; accepting invalid values leads to confusing downstream behaviour where tool execution fails without a clear cause.

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 {
	AgentContext

	Type      string `json:"type"`
	Content   string `json:"content"`
	SessionID string `json:"session_id,omitempty"`
}

func (*AgentChoiceEvent) GetSessionID added in v1.32.1

func (e *AgentChoiceEvent) GetSessionID() string

type AgentChoiceReasoningEvent

type AgentChoiceReasoningEvent struct {
	AgentContext

	Type      string `json:"type"`
	Content   string `json:"content"`
	SessionID string `json:"session_id,omitempty"`
}

func (*AgentChoiceReasoningEvent) GetSessionID added in v1.32.1

func (e *AgentChoiceReasoningEvent) GetSessionID() string

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 {
	AgentContext

	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"`
}

AgentInfoEvent is sent when agent information is available or changes

type AgentSwitchingEvent

type AgentSwitchingEvent struct {
	AgentContext

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

AgentSwitchingEvent is sent when agent switching starts or stops

type AuthorizationEvent

type AuthorizationEvent struct {
	AgentContext

	Type         string                  `json:"type"`
	Confirmation tools.ElicitationAction `json:"confirmation"`
}

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) FollowUpSession added in v1.44.0

func (c *Client) FollowUpSession(ctx context.Context, sessionID string, messages []api.Message) error

FollowUpSession queues messages for end-of-turn processing.

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) SteerSession added in v1.44.0

func (c *Client) SteerSession(ctx context.Context, sessionID string, messages []api.Message) error

SteerSession injects user messages into a running session mid-turn.

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 CurrentAgentInfo

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

type ElicitationError

type ElicitationError struct {
	Action  string
	Message string
}

ElicitationError represents a declined or cancelled elicitation, exposed to callers that prefer error-style propagation over an Action value.

func (*ElicitationError) Error

func (e *ElicitationError) Error() string

type ElicitationRequestEvent

type ElicitationRequestEvent struct {
	AgentContext

	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"`
}

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 the callback signature an embedder can supply to handle inbound elicitation requests directly (e.g. an HTTP server).

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.

Returned by the embedder via ResumeElicitation when the user responds to a schema-driven prompt that an MCP server (or the runtime) requested.

type ErrorEvent

type ErrorEvent struct {
	AgentContext

	Type  string `json:"type"`
	Error string `json:"error"`
}

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, sessionID, content string) Event

func AgentChoiceReasoning

func AgentChoiceReasoning(agentName, sessionID, 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 HookFinished added in v1.53.0

func HookFinished(event hooks.EventType, sessionID string, result *hooks.Result, dispatchErr error, duration time.Duration, agentName string) Event

func HookStarted added in v1.53.0

func HookStarted(event hooks.EventType, sessionID, 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 string) Event

func RAGIndexingProgress

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

func RAGIndexingStarted

func RAGIndexingStarted(ragName, strategyName string) Event

func SessionCompaction

func SessionCompaction(sessionID, status, agentName string) Event

func SessionSummary

func SessionSummary(sessionID, summary, agentName string, firstKeptEntry int) 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(toolCallID string, 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 EventObserver added in v1.53.0

type EventObserver interface {
	// OnRunStart fires once when [LocalRuntime.RunStream] begins, before
	// any event is dispatched. Use it for one-shot lifecycle work like
	// persisting initial session metadata.
	OnRunStart(ctx context.Context, sess *session.Session)
	// OnEvent fires once per event, after the runtime emits it but
	// before the consumer's channel receives it. Observers cannot
	// modify or suppress events (a future extension may relax this);
	// to drop an event from persistence, simply ignore it inside
	// OnEvent.
	OnEvent(ctx context.Context, sess *session.Session, event Event)
}

EventObserver receives the runtime's event stream as it's produced. Implementations subscribe to lifecycle moments and act on them — persisting to a store, forwarding to a metrics pipeline, writing an audit transcript, etc.

Concurrency: the runtime invokes observers synchronously from the goroutine that forwards events to the consumer's channel, in registration order. A slow observer therefore back-pressures both downstream observers and the consumer; long-running work (network I/O, file syncing) should fan out to a private goroutine.

Errors: observers do not return errors. The runtime cannot recover from a misbehaving observer (it can't unregister it mid-stream and can't ask the consumer to retry), so an observer must log internally and never panic. The contract is "best-effort observation" rather than "all-or-nothing transactional".

Observers see every event the runtime emits, including sub-session events (from delegated tasks via transfer_task) and SessionScoped-mismatch events. Filtering is the observer's responsibility; see PersistenceObserver for the canonical pattern.

type HookBlockedEvent

type HookBlockedEvent struct {
	AgentContext

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

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

type HookFinishedEvent added in v1.53.0

type HookFinishedEvent struct {
	AgentContext

	Type       string          `json:"type"`
	SessionID  string          `json:"session_id"`
	HookEvent  hooks.EventType `json:"hook_event"`
	DurationMs int64           `json:"duration_ms"`
	Allowed    bool            `json:"allowed"`
	Error      string          `json:"error,omitempty"`
	Message    string          `json:"message,omitempty"`
}

HookFinishedEvent is emitted when a configured hook event completes.

func (*HookFinishedEvent) GetSessionID added in v1.53.0

func (e *HookFinishedEvent) GetSessionID() string

type HookStartedEvent added in v1.53.0

type HookStartedEvent struct {
	AgentContext

	Type      string          `json:"type"`
	SessionID string          `json:"session_id"`
	HookEvent hooks.EventType `json:"hook_event"`
}

HookStartedEvent is emitted when a configured hook event begins dispatching.

func (*HookStartedEvent) GetSessionID added in v1.53.0

func (e *HookStartedEvent) GetSessionID() string

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) FollowUp added in v1.44.0

func (r *LocalRuntime) FollowUp(msg QueuedMessage) error

FollowUp enqueues a message to be processed after the current agent turn finishes. Unlike Steer, follow-ups are popped one at a time and each gets a full undivided agent turn.

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. Returns an error if no elicitation is in progress or if the context is cancelled before the response can be delivered.

func (*LocalRuntime) Run

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

Run executes the agent loop synchronously and returns the final session messages. This is a convenience wrapper around RunStream for non-streaming callers.

func (*LocalRuntime) RunAgent

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

Background tasks run with tools pre-approved because there is no user present to respond to interactive approval prompts during async execution. This is a deliberate design trade-off: the user implicitly authorises all tool calls made by the sub-agent when they approve run_background_agent. Callers should be aware that prompt injection in the sub-agent's context could exploit this gate-bypass.

TODO: propagate the parent session's per-tool permission rules once the runtime supports per-session permission scoping rather than a single shared ToolsApproved flag.

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. The returned channel is closed when the loop terminates (success, error, or context cancellation). Each iteration: sends messages to the model, streams the response, executes any tool calls, and loops until the model signals stop or the iteration limit is reached.

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) Steer added in v1.44.0

func (r *LocalRuntime) Steer(msg QueuedMessage) error

Steer enqueues a user message for urgent mid-turn injection into the running agent loop. The message will be picked up after the current batch of tool calls finishes but before the loop checks whether to stop.

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").

Summarize is the public entry point used by user-driven /compact actions; it reports compactionReasonManual to BeforeCompaction / AfterCompaction hooks and "manual" to PreCompact hooks. Internal callers (proactive threshold, overflow recovery) use [LocalRuntime.compactWithReason] directly to forward a more specific reason.

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.

func (*LocalRuntime) WithAgentModel added in v1.53.0

func (r *LocalRuntime) WithAgentModel(ctx context.Context, agentName, modelRef string) (restore func(), err error)

WithAgentModel applies modelRef as a model override on the named agent and returns a function that restores the previous override safely.

The returned restore func is always non-nil. On success it uses pointer-identity compare-and-swap on the agent's override, so a concurrent change made between the apply and the restore (e.g. by the TUI model picker) is preserved instead of being clobbered. The post- apply snapshot is captured atomically with the store inside SetModelOverride, so there is no window where a concurrent change could be misattributed to this scope. On error the agent is left untouched and restore is a no-op, so callers can always defer it without nil-checking.

type MCPInitFinishedEvent

type MCPInitFinishedEvent struct {
	AgentContext

	Type string `json:"type"`
}

type MCPInitStartedEvent

type MCPInitStartedEvent struct {
	AgentContext

	Type string `json:"type"`
}

MCPInitStartedEvent is for MCP initialization lifecycle events

type MaxIterationsReachedEvent

type MaxIterationsReachedEvent struct {
	AgentContext

	Type          string `json:"type"`
	MaxIterations int    `json:"max_iterations"`
}

type MessageAddedEvent

type MessageAddedEvent struct {
	AgentContext

	Type      string           `json:"type"`
	SessionID string           `json:"session_id"`
	Message   *session.Message `json:"-"`
}

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

func (*MessageAddedEvent) GetSessionID added in v1.32.1

func (e *MessageAddedEvent) GetSessionID() string

type MessageQueue added in v1.44.0

type MessageQueue interface {
	// Enqueue adds a message to the queue. Returns false if the queue is
	// full or the context is cancelled.
	Enqueue(ctx context.Context, msg QueuedMessage) bool
	// Dequeue removes and returns the next message from the queue.
	// Returns the message and true, or a zero value and false if the
	// queue is empty. Must not block.
	Dequeue(ctx context.Context) (QueuedMessage, bool)
	// Drain returns all pending messages and removes them from the queue.
	// Must not block — if the queue is empty it returns nil.
	Drain(ctx context.Context) []QueuedMessage
}

MessageQueue is the interface for storing messages that are injected into the agent loop. Implementations must be safe for concurrent use: Enqueue is called from API handlers while Dequeue/Drain are called from the agent loop goroutine.

The default implementation is NewInMemoryMessageQueue. Callers that need durable or distributed storage can provide their own implementation via the WithSteerQueue or WithFollowUpQueue options.

func NewInMemoryMessageQueue added in v1.44.0

func NewInMemoryMessageQueue(capacity int) MessageQueue

NewInMemoryMessageQueue creates a MessageQueue backed by a buffered channel with the given capacity.

type MessageUsage

type MessageUsage struct {
	chat.Usage

	Cost         float64
	Model        string
	FinishReason chat.FinishReason `json:"finish_reason,omitempty"`
}

MessageUsage contains per-message usage data to include in TokenUsageEvent. It embeds chat.Usage and adds Cost, Model, and FinishReason 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

	// Family is the model family (e.g., "claude", "gpt").
	Family string
	// InputCost is the price (in USD) per 1M input tokens.
	InputCost float64
	// OutputCost is the price (in USD) per 1M output tokens.
	OutputCost float64
	// CacheReadCost is the price (in USD) per 1M cached input tokens.
	CacheReadCost float64
	// CacheWriteCost is the price (in USD) per 1M cache-write tokens.
	CacheWriteCost float64
	// ContextLimit is the maximum context window size in tokens.
	ContextLimit int
	// OutputLimit is the maximum number of tokens the model can produce
	// in a single response.
	OutputLimit int64
	// InputModalities lists the input modalities supported by the model
	// (e.g., "text", "image", "audio").
	InputModalities []string
	// OutputModalities lists the output modalities the model can produce.
	OutputModalities []string
}

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

type ModelFallbackEvent

type ModelFallbackEvent struct {
	AgentContext

	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
}

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 WithClock added in v1.53.0

func WithClock(now func() time.Time) Opt

WithClock replaces the runtime's clock. Defaults to time.Now. Tests that need deterministic timestamps (assistant message CreatedAt, fallback cooldown windows, tool-call latency) can pass a fake clock so assertions don't depend on wall-clock advancement.

func WithCurrentAgent

func WithCurrentAgent(agentName string) Opt

func WithEnv

func WithEnv(env []string) Opt

WithEnv sets the environment variables for hooks execution

func WithEventObserver added in v1.53.0

func WithEventObserver(o EventObserver) Opt

WithEventObserver appends o to the runtime's observer chain. Observers are invoked in registration order, synchronously, on every event the runtime produces. Multiple calls are additive.

The runtime auto-registers a PersistenceObserver for the configured session store; users do not need to wire persistence themselves. Custom observers (telemetry, audit, metrics, A2A forward) compose alongside that one.

func WithFollowUpQueue added in v1.44.0

func WithFollowUpQueue(q MessageQueue) Opt

WithFollowUpQueue sets a custom MessageQueue for end-of-turn follow-up messages. If not provided, an in-memory buffered queue is used.

func WithManagedOAuth

func WithManagedOAuth(managed bool) Opt

func WithMaxOverflowCompactions added in v1.53.0

func WithMaxOverflowCompactions(n int) Opt

WithMaxOverflowCompactions overrides how many consecutive context-overflow auto-compactions the run loop is allowed to attempt before surfacing the error. Defaults to defaultMaxOverflowCompactions (1).

Tests use this to exercise both branches of the overflow-recovery code path: pass 0 to verify the failure surface immediately; pass a higher number to verify the loop bounds compaction attempts. Negative values are clamped to 0.

func WithModelStore

func WithModelStore(store ModelStore) Opt

func WithModelSwitcherConfig

func WithModelSwitcherConfig(cfg *ModelSwitcherConfig) Opt

WithModelSwitcherConfig sets the model switcher configuration for the runtime.

func WithRetryOnRateLimit added in v1.32.3

func WithRetryOnRateLimit() Opt

WithRetryOnRateLimit enables automatic retry with backoff for HTTP 429 (rate limit) errors when no fallback models are available. When enabled, the runtime will honor the Retry-After header from the provider's response to determine wait time before retrying, falling back to exponential backoff if the header is absent.

This is off by default. It is intended for library consumers that run agents programmatically and prefer to wait for rate limits to clear rather than fail immediately.

When fallback models are configured, 429 errors always skip to the next model regardless of this setting.

func WithSessionCompaction

func WithSessionCompaction(sessionCompaction bool) Opt

func WithSessionStore

func WithSessionStore(store session.Store) Opt

func WithSteerQueue added in v1.44.0

func WithSteerQueue(q MessageQueue) Opt

WithSteerQueue sets a custom MessageQueue for mid-turn message injection. If not provided, an in-memory buffered queue is used.

func WithTelemetry added in v1.53.0

func WithTelemetry(t Telemetry) Opt

WithTelemetry replaces the runtime's Telemetry sink. Defaults to a pass-through to the package-level pkg/telemetry helpers. Tests pass a recorder to assert that the runtime emitted the expected lifecycle events without setting up an OTel client.

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 {
	AgentContext

	Type           string         `json:"type"`
	ToolCall       tools.ToolCall `json:"tool_call"`
	ToolDefinition *tools.Tool    `json:"tool_definition,omitempty"`
}

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 PersistenceObserver added in v1.53.0

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

PersistenceObserver is the stock EventObserver that mirrors the runtime's event stream to a session.Store:

  • persists the initial session row on [OnRunStart] for non-sub-session runs;
  • tracks streaming assistant content (AgentChoice and AgentChoiceReasoning) into a single growing message row, finalised on MessageAddedEvent;
  • persists user messages, sub-session attachments, summaries, token usage, and session-title updates as they fly past.

Sub-session and SessionScoped-mismatch filtering live inside [OnEvent] so callers don't have to think about them.

The runtime auto-registers one of these in NewLocalRuntime against the configured store. Custom sinks (telemetry, audit, A2A, ...) layer alongside via WithEventObserver.

func (*PersistenceObserver) OnEvent added in v1.53.0

func (p *PersistenceObserver) OnEvent(ctx context.Context, sess *session.Session, event Event)

OnEvent applies the per-event-type persistence rules. Sub-session events are skipped (the parent absorbs them on SubSessionCompleted), and any SessionScoped event tagged with a different session id (forwarded sub-agent streaming events) is filtered out so it can't pollute the parent's transcript.

func (*PersistenceObserver) OnRunStart added in v1.53.0

func (p *PersistenceObserver) OnRunStart(ctx context.Context, sess *session.Session)

OnRunStart persists the session row before the run loop starts. Sub-sessions skip this: the parent session's store absorbs them via the SubSessionCompletedEvent handling in OnEvent.

type QueuedMessage added in v1.44.0

type QueuedMessage struct {
	Content      string
	MultiContent []chat.MessagePart
}

QueuedMessage is a user message waiting to be injected into the agent loop, either mid-turn (via the steer queue) or at end-of-turn (via the follow-up queue).

type RAGIndexingCompletedEvent

type RAGIndexingCompletedEvent struct {
	AgentContext

	Type         string `json:"type"`
	RAGName      string `json:"rag_name"`
	StrategyName string `json:"strategy_name"`
}

type RAGIndexingProgressEvent

type RAGIndexingProgressEvent struct {
	AgentContext

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

type RAGIndexingStartedEvent

type RAGIndexingStartedEvent struct {
	AgentContext

	Type         string `json:"type"`
	RAGName      string `json:"rag_name"`
	StrategyName string `json:"strategy_name"`
}

RAGIndexingStartedEvent is for RAG lifecycle events

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)

	// SteerSession injects user messages into a running session mid-turn
	SteerSession(ctx context.Context, sessionID string, messages []api.Message) error

	// FollowUpSession queues messages for end-of-turn processing
	FollowUpSession(ctx context.Context, sessionID string, messages []api.Message) 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) FollowUp added in v1.44.0

func (r *RemoteRuntime) FollowUp(msg QueuedMessage) error

FollowUp enqueues a message for end-of-turn processing on the remote server.

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) Steer added in v1.44.0

func (r *RemoteRuntime) Steer(msg QueuedMessage) error

Steer enqueues a user message for mid-turn injection into the running agent loop on the remote server.

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 = toolexec.ResumeRequest

ResumeRequest carries the user's confirmation decision along with an optional reason (used when rejecting a tool call to help the model understand why). The struct fields live in toolexec.ResumeRequest; this alias is kept for readers who land here from the runtime API.

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 = toolexec.ResumeType

ResumeType identifies the user's response to a confirmation request.

The runtime emits a TOOL_PERMISSION_REQUEST event whenever a tool call requires user approval, then blocks until the embedder calls Resume(...) with one of the values below.

ResumeType, ResumeRequest, and the ResumeType* constants are aliased from toolexec so the dispatcher and the runtime share one definition without circular imports.

func ValidResumeTypes

func ValidResumeTypes() []ResumeType

ValidResumeTypes returns all allowed confirmation values, in declaration order.

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

	// Steer enqueues a user message for urgent mid-turn injection into the
	// running agent loop. Returns an error if the queue is full or steering
	// is not available.
	Steer(msg QueuedMessage) error
	// FollowUp enqueues a message for end-of-turn processing. Each follow-up
	// gets a full undivided agent turn. Returns an error if the queue is full.
	FollowUp(msg QueuedMessage) error

	// 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 runtime ready to drive an agent loop. It is a thin alias for NewLocalRuntime returning the Runtime interface, kept for source compatibility with callers written before persistence became an EventObserver. Persistence is auto-registered against the configured (or default in-memory) session store; pass WithSessionStore to override and WithEventObserver to layer additional observers (telemetry, audit, ...).

type SessionCompactionEvent

type SessionCompactionEvent struct {
	AgentContext

	Type      string `json:"type"`
	SessionID string `json:"session_id"`
	Status    string `json:"status"`
}

type SessionScoped added in v1.32.1

type SessionScoped interface {
	GetSessionID() string
}

SessionScoped is implemented by events that belong to a specific session. The PersistentRuntime uses this to filter out sub-session events that should not be persisted into the parent session's history.

type SessionSummaryEvent

type SessionSummaryEvent struct {
	AgentContext

	Type           string `json:"type"`
	SessionID      string `json:"session_id"`
	Summary        string `json:"summary"`
	FirstKeptEntry int    `json:"first_kept_entry,omitempty"`
}

type SessionTitleEvent

type SessionTitleEvent struct {
	AgentContext

	Type      string `json:"type"`
	SessionID string `json:"session_id"`
	Title     string `json:"title"`
}

type ShellOutputEvent

type ShellOutputEvent struct {
	AgentContext

	Type   string `json:"type"`
	Output string `json:"output"`
}

type StreamStartedEvent

type StreamStartedEvent struct {
	AgentContext

	Type      string `json:"type"`
	SessionID string `json:"session_id,omitempty"`
}

type StreamStoppedEvent

type StreamStoppedEvent struct {
	AgentContext

	Type      string `json:"type"`
	SessionID string `json:"session_id,omitempty"`
}

type SubSessionCompletedEvent

type SubSessionCompletedEvent struct {
	AgentContext

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

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.

type SubSessionConfig added in v1.32.5

type SubSessionConfig struct {
	// Task is the user-facing task description.
	Task string
	// ExpectedOutput is an optional description of what the sub-agent should produce.
	ExpectedOutput string
	// SystemMessage, when non-empty, replaces the default task-based system
	// message. This is used by skill sub-agents whose system prompt is the
	// skill content itself rather than the team delegation boilerplate.
	SystemMessage string
	// AgentName is the name of the agent that will execute the sub-session.
	AgentName string
	// Title is a human-readable label for the sub-session (e.g. "Transferred task").
	Title string
	// ToolsApproved overrides whether tools are pre-approved in the child session.
	ToolsApproved bool
	// PinAgent, when true, pins the child session to AgentName via
	// session.WithAgentName. This is required for concurrent background
	// tasks that must not share the runtime's mutable currentAgent field.
	PinAgent bool
	// ImplicitUserMessage, when non-empty, overrides the default "Please proceed."
	// user message sent to the child session. This allows callers like skill
	// sub-agents to pass the task description as the user message.
	ImplicitUserMessage string
	// ExcludedTools lists tool names that should be filtered out of the agent's
	// tool list for the child session. This prevents recursive tool calls
	// (e.g. run_skill calling itself in a skill sub-session).
	ExcludedTools []string
}

SubSessionConfig describes the shape of a child session: system prompt, implicit user message, agent identity, tool approval, exclusions, etc. It is the data input to [newSubSession]; the orchestration around running such a session (telemetry, current-agent switching, event forwarding) lives in [LocalRuntime.runForwarding] and [LocalRuntime.runCollecting].

type TeamInfoEvent

type TeamInfoEvent struct {
	AgentContext

	Type            string         `json:"type"`
	AvailableAgents []AgentDetails `json:"available_agents"`
	CurrentAgent    string         `json:"current_agent"`
}

TeamInfoEvent is sent when team information is available

type Telemetry added in v1.53.0

type Telemetry interface {
	// RecordSessionStart is fired once at the top of RunStream.
	RecordSessionStart(ctx context.Context, agentName, sessionID string)
	// RecordSessionEnd is fired when the run loop exits.
	RecordSessionEnd(ctx context.Context)
	// RecordError is fired when the run loop or a model call surfaces a fatal error.
	RecordError(ctx context.Context, message string)
	// RecordToolCall is fired after every tool invocation, regardless of outcome.
	RecordToolCall(ctx context.Context, toolName, sessionID, agentName string, duration time.Duration, err error)
	// RecordTokenUsage is fired after each model response that reports usage.
	RecordTokenUsage(ctx context.Context, model string, inputTokens, outputTokens int64, cost float64)
}

Telemetry is the runtime's hook for recording observability events.

The default implementation forwards every call to the package-level helpers in pkg/telemetry, which themselves no-op when no telemetry client is attached to the context — preserving the runtime's historical "telemetry is best-effort" semantics for production code.

Tests can inject a recording implementation via WithTelemetry to assert that the runtime emitted the expected lifecycle events without standing up a full OTel pipeline.

type TokenUsageEvent

type TokenUsageEvent struct {
	AgentContext

	Type      string `json:"type"`
	SessionID string `json:"session_id"`
	Usage     *Usage `json:"usage"`
}

func (*TokenUsageEvent) GetSessionID added in v1.53.0

func (e *TokenUsageEvent) GetSessionID() string

GetSessionID makes TokenUsageEvent satisfy SessionScoped so the observer fan-out can drop sub-session events without each observer re-implementing the check.

type ToolCallConfirmationEvent

type ToolCallConfirmationEvent struct {
	AgentContext

	Type           string         `json:"type"`
	ToolCall       tools.ToolCall `json:"tool_call"`
	ToolDefinition tools.Tool     `json:"tool_definition"`
}

type ToolCallEvent

type ToolCallEvent struct {
	AgentContext

	Type           string         `json:"type"`
	ToolCall       tools.ToolCall `json:"tool_call"`
	ToolDefinition tools.Tool     `json:"tool_definition"`
}

ToolCallEvent is sent when a tool call is received

type ToolCallResponseEvent

type ToolCallResponseEvent struct {
	AgentContext

	Type           string                `json:"type"`
	ToolCallID     string                `json:"tool_call_id"`
	ToolDefinition tools.Tool            `json:"tool_definition"`
	Response       string                `json:"response"`
	Result         *tools.ToolCallResult `json:"result,omitempty"`
}

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 {
	AgentContext

	Type           string `json:"type"`
	AvailableTools int    `json:"available_tools"`
	Loading        bool   `json:"loading"`
}

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 {
	AgentContext

	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
}

UserMessageEvent is sent when a user message is received

type WarningEvent

type WarningEvent struct {
	AgentContext

	Type    string `json:"type"`
	Message string `json:"message"`
}

Directories

Path Synopsis
Package compactor owns session-aware compaction work that used to live inline in pkg/runtime: extracting the conversation to summarize, computing the kept-tail boundary, and running the default LLM-based summarization strategy.
Package compactor owns session-aware compaction work that used to live inline in pkg/runtime: extracting the conversation to summarize, computing the kept-tail boundary, and running the default LLM-based summarization strategy.
Package toolexec hosts utilities used by the runtime to execute tool calls.
Package toolexec hosts utilities used by the runtime to execute tool calls.

Jump to

Keyboard shortcuts

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