Documentation
¶
Overview ¶
Package agent manages agent lifecycle, sessions, and LLM prompting.
Index ¶
- func AppendMediaMessageToSession(agentID, sessionID string, role domain.MessageRole, content string, ...) error
- func AppendMediaMessageToSessionWithSender(agentID, sessionID string, role domain.MessageRole, content 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 AppendWorkflowMessageToSession(agentID, sessionID, content string, mediaURLs []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 ClearSessionDelivery(agentID, sessionID string)
- func CommandEnvFromContext(ctx context.Context) map[string]string
- func CompleteCLIText(ctx context.Context, model, system, prompt string) (string, error)
- func DeliverMediaToSession(agentID, sessionID, caption, filePath string)
- func EnsureTaskSession(agentID, taskName string) (*domain.Session, error)
- func FilesystemGrantFromContext(ctx context.Context) (string, bool)
- func HasMessageResponse(agentID, sessionID, promptMsgID string) bool
- func HasSessionMediaDelivery(agentID, sessionID string) bool
- func IsProjectTaskScript(ctx context.Context) bool
- func IsSessionProcessing(agentID, sessionID string) bool
- func JobIDFromContext(ctx context.Context) (string, bool)
- func MarkMessageResponded(agentID, sessionID, promptMsgID, responseMsgID string) error
- func MediaFile(mediaURL string) (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 RenameTaskSession(agentID, from, to string) error
- 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 SessionTitle(agentID, sessionID string) string
- func SetActiveTurnObserver(obs func(ActiveTurn))
- 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 SkipReply(jobID, reason string)
- func StopSession(agentID, sessionID string) int
- func TakeSkippedReply(jobID string) (reason string, skipped bool)
- func TaskIDFromContext(ctx context.Context) (string, bool)
- func TaskSessionOwner(a config.AgentConfig, sess *domain.Session) int
- func TurnMediaDir() string
- func TurnMediaFromContext(ctx context.Context) []string
- func UnansweredUserMessageID(agentID, sessionID, content string, mediaURLs []string) string
- func UsageChannelFromContext(ctx context.Context) string
- func WithChannelSession(ctx context.Context, channelType, configuredID, channelID string) context.Context
- func WithCommandEnv(ctx context.Context, env map[string]string) context.Context
- func WithFilesystemGrant(ctx context.Context, root string) context.Context
- func WithJobID(ctx context.Context, jobID string) context.Context
- func WithProjectTaskScript(ctx context.Context) 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
- func WithTurnHold(ctx context.Context, hold *TurnHold) context.Context
- func WithTurnMedia(ctx context.Context, mediaURLs []string) context.Context
- func WithUsageChannel(ctx context.Context, channel string) context.Context
- func WithWriteGuard(ctx context.Context) context.Context
- func WriteGuardFromContext(ctx context.Context) bool
- type ActiveTurn
- type ActiveTurnItem
- type ActiveTurnTool
- type AgentRunner
- func (r *AgentRunner) Agent() *domain.Agent
- func (r *AgentRunner) Config() *config.AgentConfig
- func (r *AgentRunner) Interrupt()
- func (r *AgentRunner) IsVerbose() bool
- func (r *AgentRunner) Prompt(ctx context.Context, message string, consumers ...StreamConsumer)
- func (r *AgentRunner) PromptMedia(ctx context.Context, message string, mediaURLs []string, ...)
- func (r *AgentRunner) PromptMediaWithOverrides(ctx context.Context, message string, mediaURLs []string, ...)
- func (r *AgentRunner) PromptWithOverrides(ctx context.Context, message string, overrides RunOverrides, ...)
- func (r *AgentRunner) SetApproval(mode clidefs.ApprovalMode)
- func (r *AgentRunner) Stop()
- func (r *AgentRunner) Wait()
- type FileChangeEvent
- type Manager
- type RunCheckpoint
- type RunOverrides
- type SessionManager
- func (m *SessionManager) Archive(agentID, sessionID, title string) (*domain.Session, error)
- func (m *SessionManager) Clear(agentID, sessionID string) error
- 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)
- func (m *SessionManager) Load(agentID, sessionID string) (*domain.Session, error)
- func (m *SessionManager) Rekey(agentID, sessionID, name string) (*domain.Session, error)
- func (m *SessionManager) Rename(agentID, sessionID, title string) error
- type SessionMessageObserver
- type Skill
- type StreamConsumer
- type StreamEvent
- type StreamEventType
- type ToolCallIDs
- type ToolCallTurn
- type ToolClient
- type ToolEvent
- type ToolInfo
- type TurnHold
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AppendMediaMessageToSession ¶
func AppendMediaMessageToSession(agentID, sessionID string, role domain.MessageRole, content string, mediaURLs []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 string, mediaURLs []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 AppendWorkflowMessageToSession ¶ added in v0.7.8
func AppendWorkflowMessageToSession(agentID, sessionID, content string, mediaURLs []string, sender *domain.MessageSender, workflows []domain.MessageWorkflow, at time.Time) error
AppendWorkflowMessageToSession records a channel message that workflows handled in place of the agent's chat reply, naming those workflows and their runs, at time at.
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 ClearSessionDelivery ¶ added in v0.7.1
func ClearSessionDelivery(agentID, sessionID string)
ClearSessionDelivery drops every text and media delivery function registered for the session, so its replies stay in Aviary until a new one is registered.
func CommandEnvFromContext ¶ added in v0.7.2
CommandEnvFromContext returns the variables WithCommandEnv set, if any.
func CompleteCLIText ¶ added in v0.7.0
CompleteCLIText asks a CLI-backed model for a single reply to prompt under system, with no tools and no saved CLI session, the way a model API completion is asked. It is for short side queries such as naming a chat.
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 EnsureTaskSession ¶ added in v0.7.2
EnsureTaskSession returns the session a task's runs share, creating it when the task has not run yet. The session is named after the task and titled with the task's name, so it shows the task everywhere instead of "New chat".
func FilesystemGrantFromContext ¶ added in v0.7.0
FilesystemGrantFromContext returns the granted root directory if present.
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 IsProjectTaskScript ¶ added in v0.7.5
IsProjectTaskScript reports whether ctx is a project task's script.
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 MediaFile ¶ added in v0.7.6
MediaFile returns a local file holding mediaURL: the path of a file:// URL or a plain path, or a file under TurnMediaDir that a data URL is saved to. Remote URLs are refused, since nothing local holds them.
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 RenameTaskSession ¶ added in v0.7.2
RenameTaskSession moves a task's session to its new name and retitles it, so a renamed task keeps its run history. It does nothing when the task has no session yet, and leaves an unrelated session already holding the new name alone.
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 SessionTitle ¶ added in v0.7.0
SessionTitle returns the session's display title, or "" when it has none.
func SetActiveTurnObserver ¶ added in v0.7.1
func SetActiveTurnObserver(obs func(ActiveTurn))
SetActiveTurnObserver registers an optional observer that receives a session's active turn whenever it changes, and an empty one when it ends.
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 SkipReply ¶ added in v0.7.10
func SkipReply(jobID, reason string)
SkipReply records that the task or workflow run jobID chose not to reply, so its output is not delivered anywhere; reason is shown in its run log.
func StopSession ¶
StopSession cancels all in-flight prompts for the given session and returns the number of canceled runs.
func TakeSkippedReply ¶ added in v0.7.10
TakeSkippedReply reports whether jobID chose not to reply, with its reason, and forgets the choice.
func TaskIDFromContext ¶
TaskIDFromContext extracts the current scheduled task ID if present.
func TaskSessionOwner ¶ added in v0.7.2
func TaskSessionOwner(a config.AgentConfig, sess *domain.Session) int
TaskSessionOwner returns the index in a.Tasks of the task whose runs share sess, or -1. A task session whose task was deleted, or renamed before renames carried sessions along, has no owner and stays a regular chat.
func TurnMediaDir ¶ added in v0.7.6
func TurnMediaDir() string
TurnMediaDir is where data URLs from a turn are saved as files for tools that need a local path.
func TurnMediaFromContext ¶ added in v0.7.6
TurnMediaFromContext returns the current turn's media URLs.
func UnansweredUserMessageID ¶ added in v0.7.0
UnansweredUserMessageID returns the ID of the session's latest user message when it carries this content and media and has no response yet, so a failed turn can be run again without storing its message twice. Tool records from the failed turn may follow it; any other later message means the turn has moved on, and it returns "".
func UsageChannelFromContext ¶ added in v0.7.8
UsageChannelFromContext returns the channel set by WithUsageChannel.
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 WithCommandEnv ¶ added in v0.7.2
WithCommandEnv sets environment variables for the commands tool calls made with ctx start, on top of aviary's own environment and the agent's .env, as a precompiled project task's script gets AVIARY_CHECKOUT_DIRECTORY.
func WithFilesystemGrant ¶ added in v0.7.0
WithFilesystemGrant grants the tool calls made with ctx read and write access to root, in addition to the agent's static filesystem allowlist. Relative file tool paths and exec's default cwd resolve against root. The grant lasts exactly as long as calls carry ctx, so a job runtime that grants its clone directory loses access when the job's context is no longer used.
func WithProjectTaskScript ¶ added in v0.7.5
WithProjectTaskScript marks ctx as a precompiled project task's script, or the compile and analysis of one. Such a script runs in a fresh clone of its project, where the task would otherwise run as a coding agent with a shell, so exec is available to it whatever the agent's own exec permissions are, confined to the clone its context grants (see WithFilesystemGrant). Listing tools with ctx, which is what compiles, analyzes and runs the script, is how all three see the same tools.
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.
func WithTaskID ¶
WithTaskID stores the current scheduled task ID in context.
func WithTurnHold ¶ added in v0.7.0
WithTurnHold makes the tool calls of a turn run with ctx wait on hold.
func WithTurnMedia ¶ added in v0.7.6
WithTurnMedia stores the media attached to the user message that started the current turn, so tools can act on it, such as attaching a screenshot to a filed issue.
func WithUsageChannel ¶ added in v0.7.8
WithUsageChannel stores the channel a workflow run's usage is attributed to.
func WithWriteGuard ¶ added in v0.7.0
WithWriteGuard marks ctx as a model-driven tool call, where file_write must not overwrite an existing file the session has not read.
func WriteGuardFromContext ¶ added in v0.7.0
WriteGuardFromContext reports whether file_write's read-before-overwrite guard applies to ctx.
Types ¶
type ActiveTurn ¶ added in v0.7.1
type ActiveTurn struct {
AgentID string `json:"agent_id"`
SessionID string `json:"session_id"`
Processing bool `json:"processing"`
Items []ActiveTurnItem `json:"items"`
}
ActiveTurn is what a session's running turns have streamed so far. Any client that opens the session mid-turn restores its live state from it.
func ActiveTurns ¶ added in v0.7.1
func ActiveTurns() []ActiveTurn
ActiveTurns returns every session's active turn.
func GetActiveTurn ¶ added in v0.7.1
func GetActiveTurn(agentID, sessionID string) ActiveTurn
GetActiveTurn returns what the session's running turns have streamed so far.
type ActiveTurnItem ¶ added in v0.7.1
type ActiveTurnItem struct {
Text string `json:"text,omitempty"`
MediaURL string `json:"media_url,omitempty"`
Tool *ActiveTurnTool `json:"tool,omitempty"`
}
ActiveTurnItem is one entry of a running turn, in the order it streamed: a stretch of partial text, a media URL, or a tool call.
type ActiveTurnTool ¶ added in v0.7.1
type ActiveTurnTool struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Args map[string]any `json:"args,omitempty"`
Result string `json:"result,omitempty"`
Error string `json:"error,omitempty"`
Done bool `json:"done,omitempty"`
}
ActiveTurnTool is a tool call made so far in a running turn.
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) Interrupt ¶ added in v0.7.2
func (r *AgentRunner) Interrupt()
Interrupt stops the runner the way Stop does, for Aviary's own shutdown or restart rather than a stop request. Its prompts' stop events are marked Interrupted, and their checkpoints are kept for recovery.
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 string, mediaURLs []string, consumers ...StreamConsumer)
PromptMedia is like Prompt but also attaches media to the user message. Each media URL may be a data URL ("data:image/png;base64,...") or a remote URL. Text file data URLs are inlined into the message the model sees.
func (*AgentRunner) PromptMediaWithOverrides ¶
func (r *AgentRunner) PromptMediaWithOverrides(ctx context.Context, message string, mediaURLs []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) SetApproval ¶ added in v0.7.0
func (r *AgentRunner) SetApproval(mode clidefs.ApprovalMode)
SetApproval records the chat surface's effective approval mode. A CLI conversation started under another mode is replaced on its next turn.
func (*AgentRunner) Stop ¶
func (r *AgentRunner) Stop()
Stop cancels all in-flight prompts for this agent, including those of a runner it replaced.
func (*AgentRunner) Wait ¶
func (r *AgentRunner) Wait()
Wait blocks until all active prompts finish, including those of a runner it replaced.
type FileChangeEvent ¶ added in v0.7.0
type FileChangeEvent struct {
Tool string // the tool that made the change
Path string // absolute path of the changed file
Diff string // unified diff of the change
}
FileChangeEvent describes a file changed by a file editing tool.
func FileChangeFromToolResult ¶ added in v0.7.0
func FileChangeFromToolResult(toolName, result string) (*FileChangeEvent, bool)
FileChangeFromToolResult extracts the file change reported by a successful file_edit, file_multi_edit, or file_write result.
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.
func (*Manager) Reconcile ¶
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 for Aviary's shutdown or restart. Their in-flight prompts are interrupted, not stopped by request, and resume on restart.
func (*Manager) WaitRecovery ¶ added in v0.7.0
func (m *Manager) WaitRecovery()
WaitRecovery blocks until the checkpoint recoveries started by Reconcile have finished.
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"`
// MediaURLs are the media attachments for the message.
MediaURLs []string `json:"media_urls,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
// Retry re-runs the session's latest user message when it matches this
// prompt and was never answered, as the chat's Retry on a failed turn
// does, instead of appending the message again.
Retry bool
// Context is live context for this run only, such as a snapshot of the
// state the agent answers about. It reaches the model with the turn, as
// recalled memory does, and is never written to the session.
Context string
}
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) Archive ¶ added in v0.7.1
func (m *SessionManager) Archive(agentID, sessionID, title string) (*domain.Session, error)
Archive keeps a session and its messages as a regular chat under a new ID, detached from the channel it came from: it loses its channel delivery, and a later message on that channel starts a fresh session. title becomes its display title.
func (*SessionManager) Clear ¶ added in v0.7.0
func (m *SessionManager) Clear(agentID, sessionID string) error
Clear removes every message from the session and keeps the session itself: its ID, name, type, display title, and channel bindings stay, so anything that points at it keeps working. The model's stored conversation and CLI session are dropped too, so the next prompt starts fresh.
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, or is a permanent session such as Main Chat, which can only be cleared.
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.
func (*SessionManager) Load ¶ added in v0.7.1
func (m *SessionManager) Load(agentID, sessionID string) (*domain.Session, error)
Load reads agentID's session sessionID from disk. A session file that starts with a message instead of its header, as happens when messages land after the session file was removed, is repaired by writing the header back, so the session keeps resolving to its agent.
func (*SessionManager) Rekey ¶ added in v0.7.1
func (m *SessionManager) Rekey(agentID, sessionID, name string) (*domain.Session, error)
Rekey moves a named session, its messages and its channel delivery to the new name, which is also its new ID, keeping its type and title. A channel whose ID changes moves its own session this way.
func (*SessionManager) Rename ¶ added in v0.7.0
func (m *SessionManager) Rename(agentID, sessionID, title string) error
Rename sets the session's display title. The session keeps its name, which channels and the default "main" session look it up by.
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
File *FileChangeEvent // set for StreamEventFile
MediaURL string // set for StreamEventMedia (image data URL or remote URL)
Err error // set for StreamEventError
// Interrupted is set on a StreamEventStop that Aviary's own shutdown or
// restart caused, not a stop request. The prompt is kept for recovery.
Interrupted bool
}
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 StreamEventFile StreamEventType = "file" // a tool changed a file )
StreamEventType values.
type ToolCallIDs ¶ added in v0.7.0
type ToolCallIDs struct {
// contains filtered or unexported fields
}
ToolCallIDs gives one run's tool calls IDs when the backend reports none. Without IDs a result is paired with the oldest unfinished call of the same tool, since a runner reports a call's result after announcing it. The zero value is ready to use; it is not safe for concurrent use.
func (*ToolCallIDs) ID ¶ added in v0.7.0
func (t *ToolCallIDs) ID(tool *ToolEvent) string
ID returns the ID of the call or result tool reports.
type ToolCallTurn ¶ added in v0.7.8
type ToolCallTurn struct {
AgentID string
Session string // the session file's path
CalledAt time.Time
Args map[string]any
Result string
// Prompt is the user message that started the call's turn, or nil when
// no user message came before the call.
Prompt *domain.Message
}
ToolCallTurn is one persisted tool call and the user message whose turn made it.
func FindToolCallTurns ¶ added in v0.7.8
func FindToolCallTurns(tool string) ([]ToolCallTurn, error)
FindToolCallTurns returns every call of tool that returned a result in any agent's session history, oldest first, each with the user message whose turn made it, so a tool's past effect can be traced back to the request behind it, such as the screenshots sent with an issue filing. Sessions that cannot be read are skipped.
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 {
// ID ties a call to its result when the backend reports one.
ID string
Name string
Args map[string]any
Result string
Error string
// Done is set on the event reporting a call's outcome, telling it apart
// from the event announcing the call when the result is empty.
Done bool
}
ToolEvent carries structured tool execution details for debug-oriented UIs.
type TurnHold ¶ added in v0.7.0
type TurnHold struct {
// contains filtered or unexported fields
}
TurnHold pauses a running turn's tool calls from outside the turn. While it is engaged, a turn carrying it starts no new tool call: each one waits until the hold is released or the turn is cancelled. A call already running is not interrupted. The zero value is a released hold, and a nil hold never waits.
func TurnHoldFromContext ¶ added in v0.7.0
TurnHoldFromContext returns the turn's hold, or nil when it has none.
func (*TurnHold) Engage ¶ added in v0.7.0
func (h *TurnHold) Engage()
Engage makes tool calls wait until Release.
Source Files
¶
- active_turn.go
- attachments.go
- channel_format.go
- checkpoint.go
- cli_mcp.go
- cli_turn.go
- delivery.go
- file_change.go
- inflight_calls.go
- manager.go
- message_observer.go
- runner.go
- runner_prompt.go
- runner_system_prompt.go
- script_tools.go
- session.go
- session_context.go
- session_key.go
- session_processing.go
- skills.go
- stream.go
- task_session.go
- tool_call_ids.go
- tool_dedupe.go
- tool_defs.go
- tool_turns.go
- tools.go
- turn_hold.go
- turn_media.go