Documentation
¶
Overview ¶
Package agent manages agent lifecycle, sessions, and LLM prompting.
Index ¶
- func AppendMediaMessageToSession(agentID, sessionID string, role domain.MessageRole, content, mediaURL string) error
- func AppendMediaMessageToSessionWithSender(agentID, sessionID string, role domain.MessageRole, content, mediaURL string, ...) error
- func AppendMessageToSession(agentID, sessionID string, role domain.MessageRole, content string) error
- func AppendMessageToSessionWithSender(agentID, sessionID string, role domain.MessageRole, content string, ...) error
- func AppendReplyToSession(agentID, sessionID, content string) error
- func BuildLLMToolDefinitions(tools []ToolInfo) []llm.ToolDefinition
- func BuildSystemPrompt(base string, skills []Skill) string
- func ChannelSessionFromContext(ctx context.Context) (channelType, configuredID, channelID string, ok bool)
- func DeliverMediaToSession(agentID, sessionID, caption, filePath string)
- func HasMessageResponse(agentID, sessionID, promptMsgID string) bool
- func HasSessionMediaDelivery(agentID, sessionID string) bool
- func IsSessionProcessing(agentID, sessionID string) bool
- func JobIDFromContext(ctx context.Context) (string, bool)
- func MarkMessageResponded(agentID, sessionID, promptMsgID, responseMsgID string) error
- func NormalizeScriptToolArguments(ctx context.Context, name string, args map[string]any) map[string]any
- func RegisterSessionDelivery(agentID, sessionID, channelType, channelID string, fn func(string))
- func RegisterSessionMediaDelivery(agentID, sessionID, channelType, channelID string, ...)
- func SessionAgentIDFromContext(ctx context.Context) (string, bool)
- func SessionIDFromContext(ctx context.Context) (string, bool)
- func SessionRuntimeKey(agentID, sessionID string) string
- func SessionSenderFromContext(ctx context.Context) (*domain.MessageSender, bool)
- func SetSessionMessageObserver(obs SessionMessageObserver)
- func SetSessionProcessingObserver(obs func(agentID, sessionID string, processing bool))
- func SetToolClientFactory(fn func(context.Context) (ToolClient, error))
- func ShouldDeliverReply(text string) bool
- func StopSession(agentID, sessionID string) int
- func TaskIDFromContext(ctx context.Context) (string, bool)
- func WithChannelSession(ctx context.Context, channelType, configuredID, channelID string) context.Context
- func WithJobID(ctx context.Context, jobID string) context.Context
- func WithSessionAgentID(ctx context.Context, agentID string) context.Context
- func WithSessionID(ctx context.Context, sessionID string) context.Context
- func WithSessionSender(ctx context.Context, sender *domain.MessageSender) context.Context
- func WithTaskID(ctx context.Context, taskID string) context.Context
- type AgentRunner
- func (r *AgentRunner) Agent() *domain.Agent
- func (r *AgentRunner) Config() *config.AgentConfig
- func (r *AgentRunner) IsVerbose() bool
- func (r *AgentRunner) Prompt(ctx context.Context, message string, consumers ...StreamConsumer)
- func (r *AgentRunner) PromptMedia(ctx context.Context, message, mediaURL string, consumers ...StreamConsumer)
- func (r *AgentRunner) PromptMediaWithOverrides(ctx context.Context, message, mediaURL string, overrides RunOverrides, ...)
- func (r *AgentRunner) PromptWithOverrides(ctx context.Context, message string, overrides RunOverrides, ...)
- func (r *AgentRunner) Stop()
- func (r *AgentRunner) Wait()
- type Manager
- type RunCheckpoint
- type RunOverrides
- type SessionManager
- func (m *SessionManager) Create(agentID string) (*domain.Session, error)
- func (m *SessionManager) CreateWithName(agentID, name string) (*domain.Session, error)
- func (m *SessionManager) Delete(agentID, sessionID string) error
- func (m *SessionManager) GetOrCreate(agentID string) (*domain.Session, error)
- func (m *SessionManager) GetOrCreateNamed(agentID, name string) (*domain.Session, error)
- func (m *SessionManager) GetOrCreateNamedTyped(agentID, name string, typ domain.SessionType) (*domain.Session, error)
- func (m *SessionManager) List(agentID string) ([]*domain.Session, error)
- type SessionMessageObserver
- type Skill
- type StreamConsumer
- type StreamEvent
- type StreamEventType
- type ToolClient
- type ToolEvent
- type ToolInfo
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 ¶
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 ¶
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 ¶
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 ¶
HasSessionMediaDelivery reports whether the session has any registered media delivery functions.
func IsSessionProcessing ¶
IsSessionProcessing returns true when at least one prompt is currently active for the given session.
func JobIDFromContext ¶
JobIDFromContext extracts the current scheduled job ID if present.
func MarkMessageResponded ¶
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 ¶
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 ¶
SessionAgentIDFromContext extracts the session's agent ID if present.
func SessionIDFromContext ¶
SessionIDFromContext extracts the session ID if present.
func SessionRuntimeKey ¶
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 ¶
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 ¶
ShouldDeliverReply reports whether text should be forwarded to any external delivery target. Empty replies and the explicit NO_REPLY sentinel are suppressed.
func StopSession ¶
StopSession cancels all in-flight prompts for the given session and returns the number of canceled runs.
func TaskIDFromContext ¶
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 WithSessionAgentID ¶
WithSessionAgentID stores the agent ID that owns the current session in context.
func WithSessionID ¶
WithSessionID stores a concrete session ID in context for prompt execution.
func WithSessionSender ¶
WithSessionSender stores structured sender information for the current user turn.
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 ¶
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.
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.
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 ¶
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 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.