agent

package
v0.60.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	ToolOverrideScopeSystem      = "system"
	ToolOverrideScopeSystemAgent = "system_agent"
	ToolOverrideScopeUser        = "user"
	ToolOverrideScopeUserAgent   = "user_agent"

	ToolOverrideOriginDefault = "default"
)

Variables

View Source
var (
	// ErrProjectNotFound is the opaque "not found" for a missing project, a
	// project owned by another user, or one bound to a different route agent (a
	// route-agent mismatch never confirms the project exists).
	ErrProjectNotFound = errors.New("project not found")
	// ErrInvalidBaseDir reports a base_dir that escapes the agent workspace (400).
	ErrInvalidBaseDir = errors.New("invalid base_dir")
	// ErrWorkspaceSetup reports a failure to resolve/create the agent workspace (500).
	ErrWorkspaceSetup = errors.New("failed to resolve workspace")
)

Project use-case errors. Agent-gate denials propagate the agentaccess sentinels unchanged.

View Source
var ErrChatTimeout = agenterr.ErrChatTimeout

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

View Source
var ErrGroupCompactionUnsupported = errors.New("compaction is not supported for group sessions")

ErrGroupCompactionUnsupported is returned by CompactSession for a group session. Group history lives in the group event log, not the LCM conversation, so LCM compaction does not apply; callers surface this as a user-facing notice rather than silently compacting an event-log conversation.

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

func BuiltinToolAvailable(_ context.Context, params RunnerParams) bool

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

func FilterToolEnabled(defaultEnabled bool, toolName string, rows []ToolOverride) bool

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

func IsCoreToolName(name string) bool

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 runtime caches apart prevents DB Skills from being mistaken for shipped built-ins. 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.

Types

type AgentActivityStore added in v0.60.0

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

AgentActivityStore is the conversation-activity read model backing the Agent management service: it reports the last-active time per agent for one user's own conversations. It owns the sqlc row and nullable-time decoding so the transport receives only a domain map.

func NewAgentActivityStore added in v0.60.0

func NewAgentActivityStore(db *pgxpool.Pool) *AgentActivityStore

NewAgentActivityStore builds the read model over the given pool.

func (*AgentActivityStore) ListAgentLastActive added in v0.60.0

func (s *AgentActivityStore) ListAgentLastActive(ctx context.Context, userID string) (map[string]time.Time, error)

ListAgentLastActive returns agentID -> last-active UTC time for the user's conversations. Rows without a valid agent id or a zero/absent timestamp are omitted, so a caller can treat a missing key as "no activity".

type BuiltinTool added in v0.60.0

type BuiltinTool struct {
	Tool      tools.Tool
	Available func(context.Context, RunnerParams) bool
}

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
	// Authority is the trusted capability for resolving/using this session. It is
	// minted by the entry adapter from persisted identity, never from model text.
	Authority authz.Authority
}

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
	Authority     authz.Authority
}

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

type MCPToolProvider interface {
	ToolsForContext(ctx context.Context, userID, agentID string) []tools.Tool
}

MCPToolProvider surfaces external MCP-server tools into an agent's tool registry for a (user, agent) context. Implemented by *mcp.ToolProvider; kept as an interface here so the agent package need not depend on the MCP client internals and tests can stub it.

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(_ context.Context, tool tools.Tool) error

AddBuiltinTool appends a builtin tool before StartAll. It is a one-shot pre-start bind: it rejects a nil tool, a duplicate tool name, and any add after StartAll (post-start rejection), since the builtin-tool set is sealed once agents start. Runtime tool changes go through the plugin-tool path (pluginToolsBuilder / ReloadPluginTools), not here.

func (*PoolManager) BindMCPToolProvider added in v0.60.0

func (pm *PoolManager) BindMCPToolProvider(p MCPToolProvider) error

BindMCPToolProvider binds the MCP tool provider before StartAll. One-shot pre-start bind: rejects nil (missing), a second bind (duplicate), and any bind after StartAll (late). No runner rebuild is needed because agents have not yet started.

func (*PoolManager) BindOAuthRegistry added in v0.60.0

func (pm *PoolManager) BindOAuthRegistry(r *oauth.ProviderRegistry) error

BindOAuthRegistry binds the OAuth provider registry before StartAll. It is a one-shot pre-start bind: it rejects a nil registry (missing), a second bind (duplicate), and any bind after StartAll (late).

func (*PoolManager) BindSessionAccess added in v0.60.0

func (pm *PoolManager) BindSessionAccess(access SessionAccessService) error

BindSessionAccess binds the shared Session PEP before StartAll. All non-HTTP entry session lifecycle in Service goes through this port.

func (*PoolManager) BindVaultEnvLoader added in v0.60.0

func (pm *PoolManager) BindVaultEnvLoader(v sandbox.VaultEnvLoader) error

BindVaultEnvLoader binds the sandbox vault env loader (and the derived OAuth token manager) before StartAll. One-shot pre-start bind: rejects nil (missing), a second bind (duplicate), and any bind after StartAll (late). Because it runs before agents start, no runner rebuild is needed.

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) InvalidateUserAgent added in v0.60.0

func (pm *PoolManager) InvalidateUserAgent(userID, agentID string) error

InvalidateUserAgent closes live runners for one user on one agent.

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) 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.

func (*PoolManager) WaitInFlight added in v0.60.0

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

WaitInFlight blocks until no runtime has an in-flight chat turn or ctx expires, returning ctx's error on expiry. Graceful shutdown calls it after ingress has stopped and HTTP has drained, so accepted turns that hold no HTTP connection (channel messages, webhook runs, scheduler run-now) finish before the work contexts are cancelled (#744). It snapshots the service set once: ingress is already stopped, so no new agent service can be minted while it waits.

type PoolManagerOption

type PoolManagerOption func(*PoolManager)

PoolManagerOption configures a PoolManager.

func WithAssetStorePM added in v0.60.0

func WithAssetStorePM(a *asset.Store) PoolManagerOption

WithAssetStorePM injects the authoritative asset store used for cold-pod asset hydration. When unset (e.g. in tests), hydration is skipped.

func WithBeforeRunBuilderPM

func WithBeforeRunBuilderPM(b BeforeRunBuilder) PoolManagerOption

func WithBuiltinTools

func WithBuiltinTools(tools []BuiltinTool) 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 WithMCPToolProvider added in v0.60.0

func WithMCPToolProvider(p MCPToolProvider) PoolManagerOption

WithMCPToolProvider wires the provider that surfaces external MCP-server tools into each agent's tool registry. Optional: nil means no MCP tools.

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

func WithSkillReadAuthorizer(a skillstool.SkillReadAuthorizer) PoolManagerOption

WithSkillReadAuthorizer injects Skill domain read access into every runner's skills tool, so DB-backed reads (load/search_installed) are authorized.

func WithTokenManager

func WithTokenManager(tm *oauth.TokenManager) PoolManagerOption

func WithToolLifecyclePM

func WithToolLifecyclePM(tl *coreagent.ToolLifecycle) PoolManagerOption

func WithToolOverrideFetcher added in v0.60.0

func WithToolOverrideFetcher(f ToolOverrideFetcher) PoolManagerOption

type Project added in v0.60.0

type Project struct {
	ID          string
	AgentID     string
	UserID      string
	Name        string
	BaseDir     string
	Description string
	Archived    bool
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

Project is the transport-neutral view of a project row. Description is a plain string ("" when unset) and timestamps are UTC.

type ProjectAgentAuthorizer added in v0.60.0

type ProjectAgentAuthorizer interface {
	Authorize(ctx context.Context, authority authz.Authority, agentID string, action authz.Action) error
}

ProjectAgentAuthorizer is the narrow Agent PEP port the project use cases gate on: a project belongs to an agent, so every use case first authorizes the caller's read access to that agent. agentaccess.Service satisfies it.

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

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

ProjectStore owns the project application use cases (Authority-bound list/create/get/update/delete) plus the runtime workspace resolution the pool manager binds: Resolve satisfies ProjectResolverFunc and Ensure satisfies ProjectEnsurerFunc. A project is owned by (user, agent); the CRUD use cases enforce that ownership, the route-agent binding, and the workspace-containment invariant, and return the transport-neutral Project value.

func NewProjectStore added in v0.60.0

func NewProjectStore(db *pgxpool.Pool, store config.Store, assets *asset.Store, agents ProjectAgentAuthorizer) *ProjectStore

NewProjectStore builds a ProjectStore over the given pool and config store. assets is the authoritative asset store used to hydrate a cold pod's asset tree when a project is first created; it may be nil (hydration is skipped). agents is the Agent PEP the CRUD use cases gate on; it may be nil for the runtime-only Resolve/Ensure paths (which perform no authorization).

func (*ProjectStore) Create added in v0.60.0

func (s *ProjectStore) Create(ctx context.Context, authority authz.Authority, agentID, name, baseDir string, description *string) (Project, error)

Create persists a new project for the caller under the agent, after validating that base_dir is contained in the agent workspace. Gated on agent read access.

func (*ProjectStore) Delete added in v0.60.0

func (s *ProjectStore) Delete(ctx context.Context, authority authz.Authority, agentID, projectID string) error

Delete removes an owned project bound to the route agent.

func (*ProjectStore) Ensure added in v0.60.0

func (s *ProjectStore) Ensure(ctx context.Context, agentID, userID string) (string, error)

Ensure returns the default project ID for the agent+user pair, creating the project (and its workspace) when none exists yet.

func (*ProjectStore) Get added in v0.60.0

func (s *ProjectStore) Get(ctx context.Context, authority authz.Authority, agentID, projectID string) (Project, error)

Get returns one owned project bound to the route agent. A missing project, a foreign owner, or a route-agent mismatch all return ErrProjectNotFound.

func (*ProjectStore) List added in v0.60.0

func (s *ProjectStore) List(ctx context.Context, authority authz.Authority, agentID string, includeArchived bool) ([]Project, error)

List returns the agent's projects owned by the caller, optionally including archived ones. Gated on agent read access.

func (*ProjectStore) Resolve added in v0.60.0

func (s *ProjectStore) Resolve(ctx context.Context, projectID, userID string) (string, error)

Resolve returns the base directory for the given project owned by the user.

func (*ProjectStore) Update added in v0.60.0

func (s *ProjectStore) Update(ctx context.Context, authority authz.Authority, agentID, projectID string, in ProjectUpdate) (Project, error)

Update merges the provided fields into an owned project bound to the route agent and persists it. A supplied base_dir is re-validated for containment.

type ProjectUpdate added in v0.60.0

type ProjectUpdate struct {
	Name        *string
	BaseDir     *string
	Description *string
}

ProjectUpdate carries the optional fields of an update; a nil field leaves the stored value unchanged.

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
	Authority authz.Authority
}

SchedulerChatRequest describes a scheduler-initiated chat turn.

type Service added in v0.40.0

type Service struct {
	Sessions      *session.Registry // legacy fallback for tests only; production lifecycle goes through SessionAccess.
	Runtime       *agentruntime.Runtime
	SessionAccess SessionAccessService
	// AgentID is the executor this service belongs to.
	AgentID string
}

func (*Service) ArchiveSession added in v0.60.0

func (s *Service) ArchiveSession(ctx context.Context, authority authz.Authority, userID, agentID, sessionID string) error

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) 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) CompactAuthorizedSession added in v0.60.0

func (s *Service) CompactAuthorizedSession(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.

Group sessions are unsupported: their history is assembled from the group event log, not the LCM conversation, and NeedsCompaction already declines them. The manual path rejects a group session up front (before touching the compactor) with ErrGroupCompactionUnsupported rather than run a private-style compaction over an event-log conversation. CompactAuthorizedSession performs compaction after the caller has authorized ActionExecute for info under its current Session Access evaluation.

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

func (*Service) MintTaskSession added in v0.40.0

func (s *Service) MintTaskSession(ctx context.Context, authority authz.Authority, 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, authority authz.Authority, 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) ResolveGroupChannelSession added in v0.60.0

func (s *Service) ResolveGroupChannelSession(ctx context.Context, authority authz.Authority, sessionKey, groupID, agentID string, channel session.Channel) (session.Info, error)

ResolveGroupChannelSession resolves or creates a group chat session owned by the group. The caller passes the canonical group id once; the group-ownership invariant (a group session is owned by its group, so UserID == GroupID) is established here in one place rather than by callers repeating the id.

func (*Service) ResolveGroupChannelSessionForUse added in v0.60.0

func (s *Service) ResolveGroupChannelSessionForUse(ctx context.Context, authority authz.Authority, sessionKey, groupID, agentID string, channel session.Channel) (session.Info, error)

func (*Service) ResolveMainSession added in v0.40.0

func (s *Service) ResolveMainSession(ctx context.Context, authority authz.Authority, 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) ResolveMainSessionForUse added in v0.60.0

func (s *Service) ResolveMainSessionForUse(ctx context.Context, authority authz.Authority, userID, agentID string) (session.Info, error)

func (*Service) ResolvePrivateChannelSession added in v0.60.0

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

ResolvePrivateChannelSession resolves or creates a private channel chat session using a trusted system-derived session key. It returns the Info without executing a chat turn. Private callers do not know about groups.

func (*Service) ResolvePrivateChannelSessionForUse added in v0.60.0

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

func (*Service) RunDelegateSession added in v0.40.0

RunDelegateSession implements delegatetool.SessionRunner so that Service can be passed directly to delegate tool constructors. Its identity is the parent runtime's validated session identity: a delegate tool cannot choose an owner, executor, or project through its model arguments.

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

type SessionAccessService interface {
	Begin(context.Context, authz.Authority) (SessionAccess, error)
}

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.

Runtime owns execution; SessionAccess owns every lifecycle and policy decision. Sessions remains only as a legacy test fixture field and must not become a production entry point again.

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)
	ExcludedTools    []string
	OnSandboxSession func(sandbox.Session) error
	Authority        authz.Authority
}

TaskChatRequest describes one worker turn on a durable task session.

type ToolOverride added in v0.60.0

type ToolOverride struct {
	ToolName string
	Scope    string
	Enabled  bool
}

ToolOverride is the runner-facing view of a persisted tool visibility row.

type ToolOverrideDecision added in v0.60.0

type ToolOverrideDecision struct {
	Enabled bool
	Origin  string
}

func ResolveToolOverride added in v0.60.0

func ResolveToolOverride(defaultEnabled bool, toolName string, rows []ToolOverride) ToolOverrideDecision

type ToolOverrideFetcher added in v0.60.0

type ToolOverrideFetcher func(ctx context.Context, userID, agentID string) ([]ToolOverride, error)

type ToolOverrideKey added in v0.60.0

type ToolOverrideKey struct {
	ToolName string
	Scope    string
	UserID   string
	AgentID  string
}

ToolOverrideKey identifies one override row for clearing.

type ToolOverrideStore added in v0.60.0

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

ToolOverrideStore reads persisted tool-visibility overrides for an agent+user context. Its Fetch method satisfies ToolOverrideFetcher.

func NewToolOverrideStore added in v0.60.0

func NewToolOverrideStore(db *pgxpool.Pool) *ToolOverrideStore

NewToolOverrideStore builds a ToolOverrideStore over the given pool.

func (*ToolOverrideStore) Clear added in v0.60.0

Clear deletes a tool visibility override if present. The scope is validated for the same reason as Set.

func (*ToolOverrideStore) Fetch added in v0.60.0

func (s *ToolOverrideStore) Fetch(ctx context.Context, userID, agentID string) ([]ToolOverride, error)

Fetch returns the tool overrides that apply to the given user+agent pair.

func (*ToolOverrideStore) Set added in v0.60.0

Set upserts a tool visibility override. It validates the scope vocabulary so a caller can never persist an override under an unrecognized scope — the Agent domain owns that invariant rather than trusting the transport's request field.

type ToolOverrideWrite added in v0.60.0

type ToolOverrideWrite struct {
	ToolName string
	Scope    string
	UserID   string
	AgentID  string
	Enabled  bool
}

ToolOverrideWrite is the durable owner+scope key plus the desired enabled state for one tool visibility override.

type ToolUseEvent

type ToolUseEvent = agentruntime.ToolUseEvent

ToolUseEvent describes a tool invocation in progress or completed.

Directories

Path Synopsis
Package access is the policy-enforcement point for Agent resources.
Package access is the policy-enforcement point for Agent resources.
Package runtime executes agent conversations in already-resolved sessions.
Package runtime executes agent conversations in already-resolved sessions.
Package sandbox resolves an agent's sandbox config into a live session and provides that session's agent-facing tool projections (bash, read, write, edit).
Package sandbox resolves an agent's sandbox config into a live session and provides that session's agent-facing tool projections (bash, read, write, edit).
Package session owns agent-session lifecycle.
Package session owns agent-session lifecycle.
access
Package access is the authoritative Session and Workspace application service.
Package access is the authoritative Session and Workspace application service.

Jump to

Keyboard shortcuts

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