Help us shape the future of Go! Take the 2026 Go Developer Survey

agent

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package agent manages agent lifecycle, sessions, and LLM prompting.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendMediaMessageToSession

func AppendMediaMessageToSession(agentID, sessionID string, role domain.MessageRole, content, mediaURL string) error

AppendMediaMessageToSession appends a message with optional text and media to an existing session and fires the session-message observer.

func AppendMediaMessageToSessionWithSender

func AppendMediaMessageToSessionWithSender(agentID, sessionID string, role domain.MessageRole, content, mediaURL string, sender *domain.MessageSender) error

AppendMediaMessageToSessionWithSender appends a message with optional text, media, and structured sender metadata to an existing session.

func AppendMessageToSession

func AppendMessageToSession(agentID, sessionID string, role domain.MessageRole, content string) error

AppendMessageToSession appends a message to an existing session and fires the session-message observer so WebSocket clients are notified.

func AppendMessageToSessionWithSender

func AppendMessageToSessionWithSender(agentID, sessionID string, role domain.MessageRole, content string, sender *domain.MessageSender) error

AppendMessageToSessionWithSender appends a message with structured sender metadata to an existing session and fires the session-message observer so WebSocket clients are notified.

func AppendReplyToSession

func AppendReplyToSession(agentID, sessionID, content string) error

AppendReplyToSession appends an assistant reply to a session and forwards it to any registered delivery targets for that session.

func BuildLLMToolDefinitions

func BuildLLMToolDefinitions(tools []ToolInfo) []llm.ToolDefinition

BuildLLMToolDefinitions converts tool metadata into provider-native tool definitions.

func BuildSystemPrompt

func BuildSystemPrompt(base string, skills []Skill) string

BuildSystemPrompt prepends all skill contents to a base system prompt.

func ChannelSessionFromContext

func ChannelSessionFromContext(ctx context.Context) (channelType, configuredID, channelID string, ok bool)

ChannelSessionFromContext extracts the channel session info if present.

func DeliverMediaToSession

func DeliverMediaToSession(agentID, sessionID, caption, filePath string)

DeliverMediaToSession calls all registered media delivery functions for the session, forwarding the file to each associated channel.

func HasMessageResponse

func HasMessageResponse(agentID, sessionID, promptMsgID string) bool

HasMessageResponse reports whether promptMsgID already has a response_id recorded in the session JSONL (last-write-wins across all records with that ID).

func HasSessionMediaDelivery

func HasSessionMediaDelivery(agentID, sessionID string) bool

HasSessionMediaDelivery reports whether the session has any registered media delivery functions.

func IsSessionProcessing

func IsSessionProcessing(agentID, sessionID string) bool

IsSessionProcessing returns true when at least one prompt is currently active for the given session.

func JobIDFromContext

func JobIDFromContext(ctx context.Context) (string, bool)

JobIDFromContext extracts the current scheduled job ID if present.

func MarkMessageResponded

func MarkMessageResponded(agentID, sessionID, promptMsgID, responseMsgID string) error

MarkMessageResponded appends a response marker to the session JSONL indicating that promptMsgID was successfully answered by responseMsgID. The marker has an empty Role so it is filtered from normal message listings, but the response_id is merged into the original message when listing or looking up by ID.

func NormalizeScriptToolArguments

func NormalizeScriptToolArguments(ctx context.Context, name string, args map[string]any) map[string]any

NormalizeScriptToolArguments injects hidden runtime context into tool calls made from embedded scripts so scripts operate on the current agent/session.

func RegisterSessionDelivery

func RegisterSessionDelivery(agentID, sessionID, channelType, channelID string, fn func(string))

RegisterSessionDelivery registers fn as the delivery function for channelType/channelID on the given session. A second call with the same session+channel overwrites the previous entry (idempotent).

func RegisterSessionMediaDelivery

func RegisterSessionMediaDelivery(agentID, sessionID, channelType, channelID string, fn func(caption, path string))

RegisterSessionMediaDelivery registers a media delivery function for channelType/channelID on the given session. fn receives (caption, filePath).

func SessionAgentIDFromContext

func SessionAgentIDFromContext(ctx context.Context) (string, bool)

SessionAgentIDFromContext extracts the session's agent ID if present.

func SessionIDFromContext

func SessionIDFromContext(ctx context.Context) (string, bool)

SessionIDFromContext extracts the session ID if present.

func SessionRuntimeKey

func SessionRuntimeKey(agentID, sessionID string) string

SessionRuntimeKey namespaces session-local runtime state by agent.

func SessionSenderFromContext

func SessionSenderFromContext(ctx context.Context) (*domain.MessageSender, bool)

SessionSenderFromContext extracts the structured sender for the current user turn.

func SetSessionMessageObserver

func SetSessionMessageObserver(obs SessionMessageObserver)

SetSessionMessageObserver registers an optional observer for persisted session messages.

func SetSessionProcessingObserver

func SetSessionProcessingObserver(obs func(agentID, sessionID string, processing bool))

SetSessionProcessingObserver registers an optional observer for processing state changes in a session.

func SetToolClientFactory

func SetToolClientFactory(fn func(context.Context) (ToolClient, error))

SetToolClientFactory injects the runtime tool client factory used by AgentRunner.

func ShouldDeliverReply

func ShouldDeliverReply(text string) bool

ShouldDeliverReply reports whether text should be forwarded to any external delivery target. Empty replies and the explicit NO_REPLY sentinel are suppressed.

func StopSession

func StopSession(agentID, sessionID string) int

StopSession cancels all in-flight prompts for the given session and returns the number of canceled runs.

func TaskIDFromContext

func TaskIDFromContext(ctx context.Context) (string, bool)

TaskIDFromContext extracts the current scheduled task ID if present.

func WithChannelSession

func WithChannelSession(ctx context.Context, channelType, configuredID, channelID string) context.Context

WithChannelSession stores the originating configured channel and target ID in context so that prompt execution and scheduled tasks can route replies back to the exact source channel by default.

func WithJobID

func WithJobID(ctx context.Context, jobID string) context.Context

WithJobID stores the current scheduled job ID in context.

func WithSessionAgentID

func WithSessionAgentID(ctx context.Context, agentID string) context.Context

WithSessionAgentID stores the agent ID that owns the current session in context.

func WithSessionID

func WithSessionID(ctx context.Context, sessionID string) context.Context

WithSessionID stores a concrete session ID in context for prompt execution.

func WithSessionSender

func WithSessionSender(ctx context.Context, sender *domain.MessageSender) context.Context

WithSessionSender stores structured sender information for the current user turn.

func WithTaskID

func WithTaskID(ctx context.Context, taskID string) context.Context

WithTaskID stores the current scheduled task ID in context.

Types

type AgentRunner

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

AgentRunner manages an agent's active prompts and lifecycle.

func NewAgentRunner

func NewAgentRunner(a *domain.Agent, cfg *config.AgentConfig, provider llm.Provider, factory *llm.Factory) *AgentRunner

NewAgentRunner creates an AgentRunner for the given agent.

func (*AgentRunner) Agent

func (r *AgentRunner) Agent() *domain.Agent

Agent returns the domain agent.

func (*AgentRunner) Config

func (r *AgentRunner) Config() *config.AgentConfig

Config returns the agent's config snapshot.

func (*AgentRunner) IsVerbose

func (r *AgentRunner) IsVerbose() bool

IsVerbose reports whether verbose mode is enabled for this agent. When true the runner emits StreamEventStatus events before each tool call.

func (*AgentRunner) Prompt

func (r *AgentRunner) Prompt(ctx context.Context, message string, consumers ...StreamConsumer)

Prompt sends a message to the agent and fans out stream events to consumers. Each call runs in its own goroutine; multiple concurrent calls are supported.

func (*AgentRunner) PromptMedia

func (r *AgentRunner) PromptMedia(ctx context.Context, message, mediaURL string, consumers ...StreamConsumer)

PromptMedia is like Prompt but also attaches an image to the user message. mediaURL may be a data URL ("data:image/png;base64,...") or a remote URL. Pass an empty string for text-only messages.

func (*AgentRunner) PromptMediaWithOverrides

func (r *AgentRunner) PromptMediaWithOverrides(ctx context.Context, message, mediaURL string, overrides RunOverrides, consumers ...StreamConsumer)

PromptMediaWithOverrides is like PromptMedia but also applies per-run overrides for model, fallbacks, and tool permissions.

func (*AgentRunner) PromptWithOverrides

func (r *AgentRunner) PromptWithOverrides(ctx context.Context, message string, overrides RunOverrides, consumers ...StreamConsumer)

PromptWithOverrides is like Prompt but applies the provided overrides for this call only. Model, Fallbacks, RestrictTools, and DisabledTools in overrides take precedence over agent-level defaults when non-empty.

func (*AgentRunner) Stop

func (r *AgentRunner) Stop()

Stop cancels all in-flight prompts for this agent.

func (*AgentRunner) Wait

func (r *AgentRunner) Wait()

Wait blocks until all active prompts finish.

type Manager

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

Manager maintains a registry of AgentRunners and reconciles them with config.

func NewManager

func NewManager(factory *llm.Factory) *Manager

NewManager creates a new Manager with an optional LLM factory.

func (*Manager) Get

func (m *Manager) Get(name string) (*AgentRunner, bool)

Get returns the runner for the named agent.

func (*Manager) GetByID

func (m *Manager) GetByID(agentID string) (*AgentRunner, bool)

GetByID returns the runner for a concrete agent ID.

func (*Manager) List

func (m *Manager) List() []*domain.Agent

List returns a snapshot of all agents in config entry order.

func (*Manager) Reconcile

func (m *Manager) Reconcile(cfg *config.Config)

Reconcile idempotently adds, updates, or removes agents based on cfg. It is safe to call concurrently and from a config watcher goroutine.

func (*Manager) Stop

func (m *Manager) Stop()

Stop stops all agents.

type RunCheckpoint

type RunCheckpoint struct {
	// AgentName is the name of the agent that owns this checkpoint.
	AgentName string `json:"agent_name"`
	// SessionID is the session the prompt was running in.
	SessionID string `json:"session_id"`
	// Message is the original user message to re-issue.
	Message string `json:"message"`
	// MediaURL is an optional media attachment for the message.
	MediaURL string `json:"media_url,omitempty"`
	// Overrides holds any per-run model/tool overrides that were active.
	Overrides RunOverrides `json:"overrides,omitempty"`
	// CreatedAt is when the checkpoint was written (prompt start time).
	CreatedAt time.Time `json:"created_at"`
	// RetryCount tracks how many times this checkpoint has been re-issued.
	RetryCount int `json:"retry_count,omitempty"`
	// LastRecoveredAt is when the checkpoint was last re-issued.
	LastRecoveredAt time.Time `json:"last_recovered_at,omitempty"`
}

RunCheckpoint stores the state of an in-flight agent prompt so it can be resumed after a server restart or config reload. Checkpoint files are written to <agentDir>/checkpoints/ at the start of each prompt and deleted on completion. If a checkpoint is older than the configured failed_task_timeout when the server restarts, the agent notifies the session that it gave up instead of resuming.

type RunOverrides

type RunOverrides struct {
	Model            string
	Fallbacks        []string
	RestrictTools    []string
	DisabledTools    []string
	Bare             bool
	History          *bool
	SuppressDelivery bool
}

RunOverrides defines per-run overrides for model, fallbacks, and tools.

type SessionManager

type SessionManager struct{}

SessionManager creates and persists agent sessions.

func NewSessionManager

func NewSessionManager() *SessionManager

NewSessionManager creates a SessionManager.

func (*SessionManager) Create

func (m *SessionManager) Create(agentID string) (*domain.Session, error)

Create creates a new session for the given agent and persists it.

func (*SessionManager) CreateWithName

func (m *SessionManager) CreateWithName(agentID, name string) (*domain.Session, error)

CreateWithName creates a new unique session with the given display name. Unlike GetOrCreateNamed, this always creates a fresh session (no dedup).

func (*SessionManager) Delete

func (m *SessionManager) Delete(agentID, sessionID string) error

Delete removes the session file for the given session ID. It returns an error if the session cannot be found or deleted.

func (*SessionManager) GetOrCreate

func (m *SessionManager) GetOrCreate(agentID string) (*domain.Session, error)

GetOrCreate returns the agent's main session, creating it if it doesn't exist.

func (*SessionManager) GetOrCreateNamed

func (m *SessionManager) GetOrCreateNamed(agentID, name string) (*domain.Session, error)

GetOrCreateNamed returns the named session for an agent, creating it if needed. The session type is inferred from the name: "main" → main, names containing ":" → channel, anything else → user.

func (*SessionManager) GetOrCreateNamedTyped

func (m *SessionManager) GetOrCreateNamedTyped(agentID, name string, typ domain.SessionType) (*domain.Session, error)

GetOrCreateNamedTyped is like GetOrCreateNamed but uses the provided session type when creating a new session instead of inferring it from the name.

func (*SessionManager) List

func (m *SessionManager) List(agentID string) ([]*domain.Session, error)

List returns all sessions for agentID, sorted by creation time with "main" first.

type SessionMessageObserver

type SessionMessageObserver func(agentID, sessionID, role string)

SessionMessageObserver is invoked whenever a session message is persisted.

type Skill

type Skill struct {
	Name        string // filename stem, e.g. "summarise"
	Description string // optional frontmatter description
	Content     string // markdown body without frontmatter
}

Skill represents a discovered SKILL.md file that can be used as a prompt prefix.

func DiscoverSkills

func DiscoverSkills(dir string) ([]Skill, error)

DiscoverSkills walks dir and all subdirectories looking for SKILL.md files. Each SKILL.md is returned as a Skill with Name derived from its parent directory.

type StreamConsumer

type StreamConsumer func(StreamEvent)

StreamConsumer receives StreamEvents.

type StreamEvent

type StreamEvent struct {
	Type     StreamEventType
	AgentID  string
	Text     string // set for StreamEventText
	Tool     *ToolEvent
	MediaURL string // set for StreamEventMedia (image data URL or remote URL)
	Err      error  // set for StreamEventError
}

StreamEvent is a single event emitted during an agent response.

type StreamEventType

type StreamEventType string

StreamEventType identifies the kind of event in a streaming response.

const (
	StreamEventText   StreamEventType = "text"   // partial text from the LLM
	StreamEventTool   StreamEventType = "tool"   // tool execution metadata
	StreamEventMedia  StreamEventType = "media"  // image data URL from the LLM
	StreamEventDone   StreamEventType = "done"   // stream complete
	StreamEventError  StreamEventType = "error"  // error occurred
	StreamEventStop   StreamEventType = "stop"   // agent was stopped mid-stream
	StreamEventStatus StreamEventType = "status" // verbose progress message before a tool call
)

StreamEventType values.

type ToolClient

type ToolClient interface {
	ListTools(ctx context.Context) ([]ToolInfo, error)
	CallToolText(ctx context.Context, name string, args map[string]any) (string, error)
	Close() error
}

ToolClient executes tool calls and enumerates available tools.

func NewToolClient

func NewToolClient(ctx context.Context) (ToolClient, error)

NewToolClient returns the currently configured runtime tool client.

type ToolEvent

type ToolEvent struct {
	Name   string
	Args   map[string]any
	Result string
	Error  string
}

ToolEvent carries structured tool execution details for debug-oriented UIs.

type ToolInfo

type ToolInfo struct {
	Name        string
	Description string
	InputSchema any
}

ToolInfo is a provider-agnostic capability descriptor exposed to the model.

Jump to

Keyboard shortcuts

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