agent

package
v0.50.7 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: AGPL-3.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrChatTimeout = agenterr.ErrChatTimeout

ErrChatTimeout is returned when the main agent chat exceeds its wall-clock timeout.

MessageText extracts and joins all text from a MessageContent.

Functions

func AgentWorkspaceDir added in v0.49.0

func AgentWorkspaceDir(base, agentID string) string

AgentWorkspaceDir returns the user-independent agent directory that holds the agent definition and agent-level skills.

func BuildGroupSessionKey added in v0.42.0

func BuildGroupSessionKey(agentID, groupID string) string

BuildGroupSessionKey constructs a session key for a group chat. All participants in the same group share one session per agent. Format: {agentID}:group:{groupID}

func BuildSessionKey

func BuildSessionKey(agentID, platform, externalUserID, channelContext string) string

BuildSessionKey constructs a session key from agent, platform, user, and context. Format: {agentID}:{platform}:{externalUserID}:{channelContext}

func BuildUserSessionKey

func BuildUserSessionKey(agentID string, authUserID string, channelContext string) string

BuildUserSessionKey constructs a session key for a linked auth user. Linked users share a single session across all channels (for the same agent and channel context), so the key omits the platform-specific external ID. Format: {agentID}:user:{authUserID}:{channelContext}

func ChannelFromContext

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

ChannelFromContext returns the current chat channel when present.

func ExcludedToolsFromContext

func ExcludedToolsFromContext(ctx context.Context) []string

ExcludedToolsFromContext returns the per-run excluded tool names when present.

func GroupAgentDir added in v0.49.0

func GroupAgentDir(base, groupID, agentID string) string

GroupAgentDir returns the per-(group, agent) private area under a group home.

func GroupHomeDir added in v0.49.0

func GroupHomeDir(base, groupID string) string

GroupHomeDir returns the home directory for a channel group — a principal in the users tree, shared by all the group's agents. The "group-" prefix keeps a group home from colliding with a user home of the same raw ID.

func SaveAsset

func SaveAsset(assetsDir, fileName string, data []byte) (string, error)

SaveAsset writes data to assetsDir with a timestamp-prefixed filename to avoid collisions, returning the absolute path of the saved file.

func SetupAgentWorkspace added in v0.49.0

func SetupAgentWorkspace(base, agentID string) (string, error)

SetupAgentWorkspace ensures the user-independent agent directory exists. Creates {base}/agents/{agentID}/.agents/skills/ and returns the agent directory.

func SetupGroupWorkspace added in v0.42.0

func SetupGroupWorkspace(base, groupID, agentID string) (string, error)

SetupGroupWorkspace mirrors SetupUserWorkspace for a group account.

func SetupUserWorkspace

func SetupUserWorkspace(base, userID, agentID string) (string, error)

SetupUserWorkspace ensures a user home and the per-(user, agent) area exist. Creates the user home (.agents/skills, data, assets — shared by all the user's agents) and the agent's private subdir (where its projects live). Returns the user home directory, which is the sandbox workspace root and HOME.

func SystemDBSkillsDir added in v0.49.0

func SystemDBSkillsDir(base string) string

SystemDBSkillsDir returns the directory holding DB-installed system-scope skills, a sibling of the shipped built-in skills dir (UserSkillsDir(base), read by ListSystemSkills). Keeping them apart is load-bearing: SyncAllToDisk deletes disk files absent from the DB, so mirroring DB system skills into the built-in dir would wipe the built-ins (they are not DB rows). Isolating backends mount it read-only.

func SystemOverrideFromContext

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

SystemOverrideFromContext returns the per-run system prompt override when present.

func UserAgentDir added in v0.49.0

func UserAgentDir(base, userID, agentID string) string

UserAgentDir returns the per-(user, agent) private area under a user home. Projects owned by the agent live under this directory.

func UserAssetsDir

func UserAssetsDir(userHome string) string

UserAssetsDir returns the per-user assets directory within a user home. Uploaded files from all channels are stored here, shared across the user's agents, under the user-data root mounted as /user (reachable in-sandbox at $STELLA_USER_DIR/assets).

func UserDataDir added in v0.49.0

func UserDataDir(userHome string) string

UserDataDir returns the shared user-data root within a user home. Toolchains, caches, user-level skills/delegates, and uploaded assets live here, shared by all the user's agents; it is mounted as /user in the two-root sandbox layout. Takes the resolved home so it composes with both user and group homes.

func UserHomeDir added in v0.49.0

func UserHomeDir(base, userID string) string

UserHomeDir returns the home directory for a user, shared by all the user's agents.

func UserSkillsDir

func UserSkillsDir(userHome string) string

UserSkillsDir returns the user-level skills directory within a user home.

func ValidateProjectDir added in v0.34.0

func ValidateProjectDir(baseDir, userRoot string) error

ValidateProjectDir checks that baseDir is a safe subpath of userRoot. It rejects paths containing ".." traversal or paths outside the workspace.

func WithChannel

func WithChannel(ctx context.Context, channel string) context.Context

WithChannel returns a child context that carries the current chat channel.

func WithExcludedTools

func WithExcludedTools(ctx context.Context, names ...string) context.Context

WithExcludedTools returns a child context that hides the named tools for a single run.

func WithSystemOverride

func WithSystemOverride(ctx context.Context, system string) context.Context

WithSystemOverride returns a child context that carries a per-run system prompt override.

func WriterSkillDiskLayout added in v0.49.0

func WriterSkillDiskLayout(base, userID, agentID string) skills.SkillDiskLayout

WriterSkillDiskLayout builds the layout the disk-mirroring writer uses, rooted at base (config.StellaHome()). An empty userID/agentID drops the scopes that need it, so those skills are not mirrored to disk.

Types

type ChannelChatRequest added in v0.40.0

type ChannelChatRequest struct {
	SessionKey string // system-derived session key (e.g. "agent:telegram:group:123")
	UserID     string
	AgentID    string
	Channel    session.Channel
	Message    MessageContent
	Model      string
}

ChannelChatRequest describes a chat turn on a non-private channel/group session identified by a Stella-derived session key.

type ChatRequest added in v0.40.0

type ChatRequest struct {
	SessionID string
	UserID    string
	AgentID   string
	ProjectID string
	Channel   session.Channel
	// Kind overrides the default session kind (KindChat). Used by non-chat
	// callers such as the scheduler (KindScheduler).
	Kind    session.Kind
	GroupID string // non-empty for group sessions; overlaid onto session.Info after Ensure
	Message MessageContent
	Model   string
	// CurrentSpeaker is the human speaking this group turn. Personalization
	// target only (D9): forwarded to the runtime as WithCurrentSpeaker, never
	// used as the session/runtime UserID. Zero value for DM turns.
	CurrentSpeaker memory.CurrentSpeaker
	// RuntimeOpts are forwarded verbatim to Runtime.Chat.
	RuntimeOpts []agentruntime.Option
}

ChatRequest describes a foreground chat turn.

type CompactionConfig

type CompactionConfig struct {
	// MaxTokens triggers compaction when the estimated token count exceeds this.
	// 0 (or omitted) uses the default of 80000. Negative values disable
	// automatic compaction. Manual /compact still works.
	MaxTokens int `yaml:"max_tokens"`
	// KeepTail is the number of recent user turns to preserve verbatim
	// after compaction. Default: 6.
	KeepTail int `yaml:"keep_tail"`
}

CompactionConfig controls automatic session compaction.

func (CompactionConfig) WithDefaults

func (c CompactionConfig) WithDefaults() CompactionConfig

WithDefaults returns a copy with zero-value fields replaced by defaults. MaxTokens 0 -> 80000; negative values are preserved (meaning disabled).

type DelegateRequest added in v0.40.0

type DelegateRequest struct {
	// SessionID, when non-empty, resumes an existing delegate session.
	// When empty, a new delegate session is created.
	SessionID     string
	UserID        string
	AgentID       string
	ProjectID     string
	Task          string
	System        string
	Model         string
	ExcludedTools []string
}

DelegateRequest describes a delegate session turn.

type DelegateResult added in v0.40.0

type DelegateResult struct {
	SessionID string
	Output    string
	Complete  bool
}

DelegateResult is the output of a delegate turn.

type Event

type Event = agentruntime.Event

Event is the consumer-facing stream event.

type FileEvent

type FileEvent = agentruntime.FileEvent

FileEvent carries a local file path to be sent to the channel.

type ImageEvent

type ImageEvent = agentruntime.ImageEvent

ImageEvent carries a base64-encoded image to be sent to the channel.

type MessageContent

type MessageContent = agentruntime.MessageContent

MessageContent is the type for user messages passed through the runner pipeline. It is either string (text-only) or []ai.ContentBlock (multimodal).

type NewRunnerFunc

type NewRunnerFunc = agentruntime.NewRunnerFunc

NewRunnerFunc creates a new Runner with the given params.

type PluginHooksBuilder

type PluginHooksBuilder func(ctx context.Context) []hooks.HookPlugin

PluginHooksBuilder creates hook plugins from enabled plugin state.

type PluginToolsBuilder

type PluginToolsBuilder func(ctx context.Context, build pkgplugins.ToolBuildContext) []tools.Tool

PluginToolsBuilder creates tools from enabled plugin state.

type PoolManager

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

PoolManager manages one Service per enabled agent. It reads enabled agents from the config Store and creates a Service (session.Registry + runtime.Runtime) per agent.

func NewPoolManager

func NewPoolManager(store config.Store, mem memory.Provider, opts ...PoolManagerOption) *PoolManager

func (*PoolManager) AddBuiltinTool

func (pm *PoolManager) AddBuiltinTool(ctx context.Context, tool tools.Tool) error

AddBuiltinTool appends a tool and rebuilds all service factories.

func (*PoolManager) Close

func (pm *PoolManager) Close() error

Close shuts down all services and hook plugins.

func (*PoolManager) Default added in v0.40.0

func (pm *PoolManager) Default() *Service

Default returns any service (first found).

func (*PoolManager) GetService added in v0.40.0

func (pm *PoolManager) GetService(agentID string) *Service

GetService returns the Service for the given agent ID, or nil if not found.

func (*PoolManager) HookPlugins

func (pm *PoolManager) HookPlugins() []hooks.HookPlugin

HookPlugins returns a snapshot of the active hook plugins: the reloadable user plugins plus the stable core hooks. Ordering is irrelevant — NewHookSet sorts by Priority — so core hooks are simply appended.

func (*PoolManager) InvalidateAgent added in v0.48.0

func (pm *PoolManager) InvalidateAgent(agentID string) error

InvalidateAgent closes all live runners for one agent across every user.

func (*PoolManager) InvalidateAll added in v0.48.0

func (pm *PoolManager) InvalidateAll() error

InvalidateAll closes every live runner across all services.

func (*PoolManager) InvalidateUser

func (pm *PoolManager) InvalidateUser(userID string) error

InvalidateUser closes all live runners for userID across all services.

func (*PoolManager) ReloadPluginHooks

func (pm *PoolManager) ReloadPluginHooks(ctx context.Context) error

ReloadPluginHooks rebuilds the hook plugin set and propagates to every service.

func (*PoolManager) ReloadPluginProviders

func (pm *PoolManager) ReloadPluginProviders(ctx context.Context) error

ReloadPluginProviders rebuilds the runner factory for every service.

func (*PoolManager) ReloadPluginTools

func (pm *PoolManager) ReloadPluginTools(ctx context.Context) error

ReloadPluginTools rebuilds the runner factory for every service.

func (*PoolManager) SetOAuthRegistry

func (pm *PoolManager) SetOAuthRegistry(r *oauth.ProviderRegistry)

func (*PoolManager) SetTokenEnsurer added in v0.38.3

func (pm *PoolManager) SetTokenEnsurer(ctx context.Context, te sandbox.TokenEnsurer)

SetTokenEnsurer wires the per-user token ensurer so sandbox sessions guarantee a STELLA_TOKEN exists in the vault before loading env.

func (*PoolManager) SetVaultEnvLoader

func (pm *PoolManager) SetVaultEnvLoader(ctx context.Context, v sandbox.VaultEnvLoader)

func (*PoolManager) StartAll

func (pm *PoolManager) StartAll(ctx context.Context) error

StartAll reads enabled agents from the store and creates a Service per agent.

func (*PoolManager) SyncAgent

func (pm *PoolManager) SyncAgent(ctx context.Context, agentID string) error

SyncAgent reloads one agent's configuration. If the agent was deleted or disabled, its service is closed and removed. Otherwise the factory and runners are rebuilt.

type PoolManagerOption

type PoolManagerOption func(*PoolManager)

PoolManagerOption configures a PoolManager.

func WithBeforeRunBuilderPM

func WithBeforeRunBuilderPM(b BeforeRunBuilder) PoolManagerOption

func WithBuiltinTools

func WithBuiltinTools(tools []tools.Tool) PoolManagerOption

func WithCompactionPM

func WithCompactionPM(cfg CompactionConfig) PoolManagerOption

func WithCoreHooks added in v0.41.0

func WithCoreHooks(h []hooks.HookPlugin) PoolManagerOption

WithCoreHooks registers server-level hooks (e.g. the OTel trace hook) that live for the whole PoolManager lifetime. Unlike plugin hooks they are never rebuilt or closed on reload, so in-flight runners can keep calling them; they are closed exactly once in Close.

func WithIdleTimeoutPM

func WithIdleTimeoutPM(d time.Duration) PoolManagerOption

func WithPluginHooksBuilder

func WithPluginHooksBuilder(b PluginHooksBuilder) PoolManagerOption

func WithPluginToolsBuilder

func WithPluginToolsBuilder(b PluginToolsBuilder) PoolManagerOption

func WithProjectEnsurerPM added in v0.34.0

func WithProjectEnsurerPM(fn ProjectEnsurerFunc) PoolManagerOption

func WithProjectResolver added in v0.34.0

func WithProjectResolver(r ProjectResolverFunc) PoolManagerOption

func WithPromptSectionsBuilder

func WithPromptSectionsBuilder(b prompt.SectionsBuilder) PoolManagerOption

func WithProviderStreamBuilder added in v0.28.0

func WithProviderStreamBuilder(b ProviderStreamBuilder) PoolManagerOption

func WithTokenManager

func WithTokenManager(tm *oauth.TokenManager) PoolManagerOption

func WithToolLifecyclePM

func WithToolLifecyclePM(tl *coreagent.ToolLifecycle) PoolManagerOption

type ProjectEnsurerFunc added in v0.34.0

type ProjectEnsurerFunc func(ctx context.Context, agentID, userID string) (projectID string, err error)

ProjectEnsurerFunc ensures a default project exists for an agent+user pair. Returns the project ID. Called when a session is created without a project.

type ProjectResolverFunc added in v0.34.0

type ProjectResolverFunc func(ctx context.Context, projectID, userID string) (baseDir string, err error)

ProjectResolverFunc resolves a project ID to its base directory path. Returns the absolute base_dir for the project.

type ProviderStreamBuilder added in v0.28.0

type ProviderStreamBuilder func(api, apiKey, baseURL string) (providers.StreamFunc, error)

type Runner

type Runner = agentruntime.Runner

Runner executes prompts against an AI backend.

type RunnerParams

type RunnerParams = agentruntime.RunnerParams

RunnerParams holds parameters for creating a new Runner instance.

type SchedulerChatRequest added in v0.40.0

type SchedulerChatRequest struct {
	SessionID string // scheduler-derived session ID
	UserID    string
	AgentID   string
	Message   MessageContent
	Model     string
}

SchedulerChatRequest describes a scheduler-initiated chat turn.

type Service added in v0.40.0

type Service struct {
	Sessions *session.Registry
	Runtime  *agentruntime.Runtime
	// AgentID is the agent this service belongs to.
	// Used by RunDelegateSession when the caller does not supply an agent ID.
	AgentID string
}

Service is a thin composition facade over session.Registry and runtime.Runtime. It provides ergonomic entry points for common use cases without hiding the conceptual split: policy lives in Session, execution lives in Runtime.

Callers that need fine-grained control can use Sessions and Runtime directly.

func (*Service) Chat added in v0.40.0

func (s *Service) Chat(ctx context.Context, req ChatRequest) <-chan Event

Chat resolves (or creates) a session and executes a chat turn.

When SessionID is empty, a new session is created with a generated ID. When SessionID is non-empty, the session must already exist (resume-only); unknown IDs return an error instead of silently creating.

func (*Service) ChatForChannel added in v0.40.0

func (s *Service) ChatForChannel(ctx context.Context, req ChannelChatRequest) <-chan Event

ChatForChannel resolves or creates a channel/group chat session using a trusted system-derived session key. Unlike Chat, this method allows exact-ID creation because the key is derived by Stella, not by user/model input.

func (*Service) ChatForGoalDecomposition added in v0.50.0

func (s *Service) ChatForGoalDecomposition(ctx context.Context, req TaskChatRequest) <-chan Event

ChatForGoalDecomposition runs one persisted worker turn on a goal's decomposition planning session. Unlike a worker (execution) session that session is KindDelegate (#525: the plan session is resumable through the delegate tool and re-openable in the UI), so it must be resolved with RequireKind=KindDelegate — routing it through ChatForTask fails with a kind mismatch and starves the goal's decomposition budget. The session is pre-minted at BeginDecomposition, so this is resume-only and never creates.

func (*Service) ChatForScheduler added in v0.40.0

func (s *Service) ChatForScheduler(ctx context.Context, req SchedulerChatRequest) <-chan Event

ChatForScheduler resolves or creates a scheduler session using a trusted scheduler-derived session ID. Exact-ID creation is allowed because the scheduler system owns the ID derivation.

func (*Service) ChatForTask added in v0.46.0

func (s *Service) ChatForTask(ctx context.Context, req TaskChatRequest) <-chan Event

ChatForTask runs one persisted chat turn on a task session. Exact-ID creation is allowed because the task system owns the ID. The per-run extra tools force a fresh runner, which is evicted once the turn finishes so the tools never leak into later turns on the same session.

func (*Service) CompactSession added in v0.40.0

func (s *Service) CompactSession(ctx context.Context, info session.Info) (string, error)

CompactSession runs full compaction on the session identified by sessionID. This is a best-effort operation: it returns the compaction summary or an error.

func (*Service) Delegate added in v0.40.0

func (s *Service) Delegate(ctx context.Context, req DelegateRequest) (DelegateResult, error)

Delegate runs a delegate turn through a persisted child session.

When SessionID is empty, a new delegate session is created with a generated ID. When SessionID is non-empty, the session must already exist (resume-only); this prevents model-supplied session_id from reserving arbitrary future IDs.

func (*Service) History added in v0.40.0

func (s *Service) History(ctx context.Context, info session.Info) []ai.Message

History returns the raw message history for the given session.

func (*Service) MintTaskSession added in v0.40.0

func (s *Service) MintTaskSession(ctx context.Context, userID, executorAgentID, projectID string) (session.Info, error)

MintTaskSession creates a new task worker session under the resolved agent. The session is always new (generated ID) and uses KindTask/ChannelTask.

func (*Service) NewSession added in v0.40.0

func (s *Service) NewSession(ctx context.Context, userID, agentID, projectID string, kind session.Kind, channel session.Channel) (session.Info, error)

NewSession creates a new session with a generated ID. Used by the HTTP API when the web UI creates a session — always new, never resume.

func (*Service) ResolveChannelSession added in v0.40.0

func (s *Service) ResolveChannelSession(ctx context.Context, sessionKey, userID, agentID string, channel session.Channel) (session.Info, error)

ResolveChannelSession resolves or creates a channel/group chat session using a trusted system-derived session key. This is the session-only variant of ChatForChannel — it returns the Info without executing a chat turn.

func (*Service) ResolveMainSession added in v0.40.0

func (s *Service) ResolveMainSession(ctx context.Context, userID, agentID string) (session.Info, error)

ResolveMainSession resolves the main session for a user+agent pair, creating one if missing. It is the canonical replacement for Pool.ResolveSession on private user channels.

func (*Service) RunDelegateSession added in v0.40.0

RunDelegateSession implements delegatetool.SessionRunner so that Service can be passed directly to delegate tool constructors. UserID is resolved from ctx; AgentID falls back to s.AgentID.

func (*Service) SessionLive added in v0.49.3

func (s *Service) SessionLive(sessionID string) bool

SessionLive reports whether a turn is currently in flight on the session.

func (*Service) SubscribeSession added in v0.49.3

func (s *Service) SubscribeSession(sessionID string) (<-chan Event, func())

SubscribeSession registers a read-only listener for a session's live turn events, regardless of who initiated the turn. Used by the SSE endpoint to let the web UI watch scheduler/task/delegate turns in real time.

type ServiceManager added in v0.40.0

type ServiceManager interface {
	// GetService returns the Service for the given agent ID, or nil if not found.
	GetService(agentID string) *Service
	// Default returns any service (first found). Useful for single-agent deployments.
	Default() *Service
}

ServiceManager provides multi-agent Service lookup. It replaces PoolManager for callers migrated to the new model.

type SessionInfo

type SessionInfo = memory.SessionInfo

SessionInfo is an alias for memory.SessionInfo.

type SessionPluginViewBuilder

type SessionPluginViewBuilder func(ctx context.Context) (pkgplugins.SessionPluginView, error)

type StepEvent added in v0.33.0

type StepEvent = agentruntime.StepEvent

StepEvent marks the boundary of an agentic step.

type TaskChatRequest added in v0.46.0

type TaskChatRequest struct {
	SessionID  string // task session minted at task creation
	UserID     string
	AgentID    string
	ProjectID  string
	Message    MessageContent
	ExtraTools []tools.Tool // per-run tools (e.g. task_control)
}

TaskChatRequest describes one worker turn on a durable task session.

type ToolUseEvent

type ToolUseEvent = agentruntime.ToolUseEvent

ToolUseEvent describes a tool invocation in progress or completed.

Directories

Path Synopsis
Package runtime executes agent conversations in already-resolved sessions.
Package runtime executes agent conversations in already-resolved sessions.
Package session owns agent-session lifecycle.
Package session owns agent-session lifecycle.

Jump to

Keyboard shortcuts

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