agent

package
v0.10.2 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildSessionKey added in v0.8.0

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 added in v0.9.0

func BuildUserSessionKey(agentID string, authUserID int64, 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 NewRunnerFactory added in v0.8.0

func NewRunnerFactory(snap *config.Snapshot, extraTools []tools.Tool, pluginToolsBuilder PluginToolsBuilder, providerRegistryBuilder func(api, apiKey, baseURL string) (*providers.Registry, error), promptToolsFn func(context.Context) ([]pkgplugins.PromptToolInfo, error), promptSectionsFn func(context.Context, pkgplugins.SystemPromptContext) ([]pkgplugins.SystemPromptSection, error), toolLifecycle *coreagent.ToolLifecycle) (runner.NewRunnerFunc, error)

NewRunnerFactory creates a runner.NewRunnerFunc for a given config snapshot. The returned factory creates runners scoped to one agent's provider, model, workspace, and system prompt. Memory provider, user ID, and agent ID are injected per-session from RunnerParams. Runner execution is always user-scoped, so per-user workspace directories are created for every runner instance.

Hooks are not part of the factory — they are injected via RunnerParams.HooksFn by the Pool, keeping hook lifecycle fully decoupled from model/provider config.

func SetupUserWorkspace added in v0.9.0

func SetupUserWorkspace(agentID, basePath string, userID int64) (string, error)

SetupUserWorkspace ensures per-user directories exist within an agent workspace. Creates:

  • basePath/workspaces/{agentID}/users/{userID}/.agents/skills/
  • basePath/workspaces/{agentID}/users/{userID}/data/

Returns the absolute path to the user's workspace directory (basePath/workspaces/{agentID}/users/{userID}/).

func SetupWorkspace added in v0.8.0

func SetupWorkspace(agentID, basePath string) (string, error)

SetupWorkspace ensures the per-agent workspace directory exists. Creates: basePath/workspaces/{agentID}/skills/ Returns the absolute path to the agent's workspace directory.

func UserRoot added in v0.10.1

func UserRoot(userWorkspace string) string

UserRoot returns the per-user writable root path within a user workspace.

func UserSkillsDir added in v0.9.0

func UserSkillsDir(userWorkspace string) string

UserSkillsDir returns the per-user skills directory path within a user workspace.

Types

type BeforeRunBuilder added in v0.9.0

type BeforeRunBuilder func(ctx context.Context, build pkgplugins.BeforeRunContext) (pkgplugins.BeforeRunResult, error)

PromptToolsBuilder returns structured prompt inventory for the active plugin host.

type ChatOption

type ChatOption func(*chatOptions)

ChatOption configures a single Chat call.

func WithModel

func WithModel(model string) ChatOption

WithModel overrides the model for this Chat call. If the session already has a runner with a different model, the runner is replaced.

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 message entries to preserve verbatim
	// after compaction. Default: 20.
	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 ExtraToolsFactory added in v0.8.0

type ExtraToolsFactory func(snap *config.Snapshot) []tools.Tool

ExtraToolsFactory creates agent-specific extra tools given a snapshot. It allows callers to inject tools that depend on per-agent configuration (e.g. scheduler, memory retrieval).

type PluginHooksBuilder added in v0.9.0

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

PluginHooksBuilder creates hook plugins from enabled plugin state. Called at startup and on hot-reload when a hook plugin is toggled.

type PluginToolsBuilder added in v0.9.0

type PluginToolsBuilder func(ctx context.Context, build plugintools.BuildContext) []tools.Tool

PluginToolsBuilder creates tools from enabled plugin state. Called per runner so tool builders receive the active sandbox host.

type Pool

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

Pool manages a set of sessions, each with its own history and runner. It is the only type channels interact with.

func NewPool

func NewPool(factory runner.NewRunnerFunc, mem memory.Provider, opts ...PoolOption) *Pool

NewPool creates a new Pool with the given runner factory and memory provider. The memory provider is required — it is the sole persistence layer for sessions.

func (*Pool) ActiveSession

func (p *Pool) ActiveSession(channel string) (SessionInfo, bool)

ActiveSession returns the most recent non-archived session for a channel.

func (*Pool) AgentID added in v0.8.0

func (p *Pool) AgentID() string

AgentID returns the agent ID this pool belongs to.

func (*Pool) ArchiveSession

func (p *Pool) ArchiveSession(sessionID string) error

ArchiveSession marks a session as archived, closes its runner, but keeps history on disk. The session is removed from the in-memory map; its metadata persists in the index.

func (*Pool) Chat

func (p *Pool) Chat(ctx context.Context, sessionID string, message runner.MessageContent, opts ...ChatOption) <-chan runner.Event

Chat sends a message in a session and streams back events. Internally: gets/creates runner, passes history, collects events, appends to session log, streams to caller.

func (*Pool) Close

func (p *Pool) Close() error

Close shuts down all sessions and runners.

func (*Pool) CompactSession

func (p *Pool) CompactSession(ctx context.Context, sessionID string) (string, error)

CompactSession delegates compaction to the memory engine and returns the summary text on success.

func (*Pool) CreateSession

func (p *Pool) CreateSession(channel string, userID ...int64) (SessionInfo, error)

CreateSession creates a new session with a generated ID and persists its metadata.

func (*Pool) GetSession

func (p *Pool) GetSession(sessionID string) (SessionInfo, error)

GetSession returns metadata for a session.

func (*Pool) History

func (p *Pool) History(sessionID string) []ai.Message

History returns the message history for a session, loading from the memory provider. Returns nil if the session has no history or the provider does not support it.

func (*Pool) ListSessions

func (p *Pool) ListSessions(includeArchived bool) ([]SessionInfo, error)

ListSessions returns metadata for all sessions.

func (*Pool) NeedsCompaction

func (p *Pool) NeedsCompaction(sessionID string) bool

NeedsCompaction reports whether a session's estimated token count exceeds the compaction threshold. Returns false if compaction is disabled or the memory provider does not support compaction.

func (*Pool) ResetRunners added in v0.10.0

func (p *Pool) ResetRunners() error

ResetRunners closes all live session runners but keeps session metadata and history. The next chat on each session will recreate a runner from the current factory.

func (*Pool) ResolveSession

func (p *Pool) ResolveSession(channel string, userID ...int64) (SessionInfo, error)

ResolveSession returns the active session for a channel, creating one if needed. The check-and-create is atomic to prevent duplicate sessions under concurrent access. An optional userID associates the session with a user (stored in conversations table).

func (*Pool) RotateSession

func (p *Pool) RotateSession(channel string, userID ...int64) (SessionInfo, error)

RotateSession archives the active session for a channel (if any) and creates a new one.

func (*Pool) SetDefaultModel

func (p *Pool) SetDefaultModel(model string)

SetDefaultModel updates the default model used for new runners. Call this alongside SetFactory when the user switches models at runtime.

func (*Pool) SetFactory

func (p *Pool) SetFactory(factory runner.NewRunnerFunc)

SetFactory replaces the runner factory used for new runners. Existing runners are not affected until their session is reset.

func (*Pool) SetFastModel added in v0.10.0

func (p *Pool) SetFastModel(model string)

SetFastModel updates the fast model used for compaction and utility work.

func (*Pool) SetHooks added in v0.9.0

func (p *Pool) SetHooks(fn func() []hooks.HookPlugin)

SetHooks updates the hook getter used when creating new runners. Changing hooks never requires rebuilding the factory or resetting sessions — new runners created after this call will use the updated hooks.

func (*Pool) StartReaper

func (p *Pool) StartReaper(ctx context.Context)

StartReaper runs a background goroutine that periodically checks for idle or dead runners. It returns when ctx is cancelled.

type PoolManager added in v0.8.0

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

PoolManager manages a map of agent ID to Pool. It reads enabled agents from the config Store and creates one Pool per agent.

func NewPoolManager added in v0.8.0

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

NewPoolManager creates a new PoolManager.

func (*PoolManager) Close added in v0.8.0

func (pm *PoolManager) Close() error

Close shuts down all pools and hook plugins.

func (*PoolManager) DefaultPool added in v0.8.0

func (pm *PoolManager) DefaultPool() *Pool

DefaultPool returns the first pool found in the map, or nil if empty. Useful for backward compatibility with code expecting a single pool.

func (*PoolManager) Get added in v0.8.0

func (pm *PoolManager) Get(agentID string) *Pool

Get returns the Pool for the given agent ID, or nil if not found.

func (*PoolManager) HookPlugins added in v0.9.0

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

HookPlugins returns a snapshot copy of the current enabled hook plugins. Returns a copy so callers cannot mutate or alias the internal slice.

func (*PoolManager) ReloadPluginHooks added in v0.9.0

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

ReloadPluginHooks rebuilds the hook plugin set from current plugin state and propagates it to every pool. No factory rebuild is needed — hooks live on the Pool and are injected via RunnerParams at runner-creation time.

func (*PoolManager) ReloadPluginProviders added in v0.9.0

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

ReloadPluginProviders rebuilds the runner factory for every pool so new sessions pick up changed provider credentials or enabled state. Provider creds are resolved from the Snapshot at factory-build time, so a simple factory rebuild is sufficient.

func (*PoolManager) ReloadPluginTools added in v0.9.0

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

ReloadPluginTools updates the runner factory for every pool. Plugin tools are built per runner so builders can receive the active sandbox host.

func (*PoolManager) StartAll added in v0.8.0

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

StartAll reads enabled agents from the store, creates a Pool per agent with per-agent runner factory, and starts reapers.

func (*PoolManager) SyncAgent added in v0.10.0

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

SyncAgent reloads one agent's pool configuration immediately. If the agent was deleted or disabled, its pool is closed and removed. If it exists and is enabled, an existing pool is rebuilt and its live session runners are reset so subsequent requests use the latest snapshot.

type PoolManagerOption added in v0.8.0

type PoolManagerOption func(*PoolManager)

PoolManagerOption configures a PoolManager.

func WithBeforeRunBuilderPM added in v0.9.0

func WithBeforeRunBuilderPM(b BeforeRunBuilder) PoolManagerOption

func WithCompactionPM added in v0.8.0

func WithCompactionPM(cfg CompactionConfig) PoolManagerOption

WithCompactionPM sets the compaction config for all pools.

func WithExtraToolsFactory added in v0.8.0

func WithExtraToolsFactory(f ExtraToolsFactory) PoolManagerOption

WithExtraToolsFactory sets the function that creates per-agent extra tools.

func WithIdleTimeoutPM added in v0.8.0

func WithIdleTimeoutPM(d time.Duration) PoolManagerOption

WithIdleTimeoutPM sets the idle timeout for all pools.

func WithPluginHooksBuilder added in v0.9.0

func WithPluginHooksBuilder(b PluginHooksBuilder) PoolManagerOption

WithPluginHooksBuilder sets the function that builds hooks from plugin state.

func WithPluginToolsBuilder added in v0.9.0

func WithPluginToolsBuilder(b PluginToolsBuilder) PoolManagerOption

WithPluginToolsBuilder sets the function that builds tools from plugin state.

func WithPromptSectionsBuilder added in v0.9.0

func WithPromptSectionsBuilder(b PromptSectionsBuilder) PoolManagerOption

func WithPromptToolsBuilder added in v0.9.0

func WithPromptToolsBuilder(b PromptToolsBuilder) PoolManagerOption

WithPromptToolsBuilder sets the function that returns prompt inventory items.

func WithProviderRegistryBuilder added in v0.9.0

func WithProviderRegistryBuilder(b ProviderRegistryBuilder) PoolManagerOption

func WithSharedExtraTools added in v0.8.0

func WithSharedExtraTools(tools []tools.Tool) PoolManagerOption

WithSharedExtraTools sets tools shared across all agents (e.g. scheduler, memory).

func WithToolLifecyclePM added in v0.9.0

func WithToolLifecyclePM(tl *coreagent.ToolLifecycle) PoolManagerOption

type PoolOption

type PoolOption func(*Pool)

PoolOption configures a Pool.

func WithAgentID added in v0.8.0

func WithAgentID(id string) PoolOption

WithAgentID sets the agent ID this pool belongs to.

func WithBeforeRunBuilder added in v0.9.0

func WithBeforeRunBuilder(b BeforeRunBuilder) PoolOption

WithBeforeRunBuilder sets the per-run lifecycle hook builder used by the pool.

func WithCompaction

func WithCompaction(cfg CompactionConfig) PoolOption

WithCompaction sets the compaction configuration.

func WithDefaultModel

func WithDefaultModel(model string) PoolOption

WithDefaultModel sets the default model ID for new runners.

func WithFastModel

func WithFastModel(model string) PoolOption

WithFastModel sets the model ID used for compaction and other fast tasks.

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) PoolOption

WithIdleTimeout sets the idle timeout for reaping runners.

type PromptSectionsBuilder added in v0.9.0

type PromptSectionsBuilder func(ctx context.Context, build pkgplugins.SystemPromptContext) ([]pkgplugins.SystemPromptSection, error)

PromptToolsBuilder returns structured prompt inventory for the active plugin host.

type PromptToolsBuilder added in v0.9.0

type PromptToolsBuilder func(ctx context.Context) ([]pkgplugins.PromptToolInfo, error)

PromptToolsBuilder returns structured prompt inventory for the active plugin host.

type ProviderRegistryBuilder added in v0.9.0

type ProviderRegistryBuilder func(api, apiKey, baseURL string) (*providers.Registry, error)

PromptToolsBuilder returns structured prompt inventory for the active plugin host.

type Session

type Session struct {
	Info   SessionInfo
	Runner runner.Runner
	Model  string // model ID the current runner was created with
}

Session holds the state of a single conversation: metadata and the currently assigned runner. Message persistence is handled by the memory engine exclusively.

type SessionInfo

type SessionInfo = memory.SessionInfo

SessionInfo is an alias for memory.SessionInfo.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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