Documentation
¶
Overview ¶
Package chatagent orchestrates the Flowbot chat assistant: session lifecycle, harness pooling, SSE streaming, tool confirmations, permissions, and scheduled tasks.
HTTP routes are registered in internal/server (chatagent_http*.go); this package holds the service layer consumed by REST handlers and platform chat sinks.
Index ¶
- Constants
- Variables
- func AbilityToolNames() []string
- func AbortSessionHarness(sessionID string)
- func ActiveToolNames() []string
- func AppendPlanLinkFooter(reply, planID, title string) string
- func ApplyToolScope(in ToolScopeInput) []string
- func BaseToolNamesForRun(kind RunKind, explicitTools []string) []string
- func BeginEphemeralSession(ctx context.Context, uid types.Uid) (sessionID string, err error)
- func BindRunCancel(sessionID string, cancel context.CancelFunc)
- func BuildSystemPrompt(options BuildSystemPromptOptions) string
- func CachedSystemPrompt(ctx context.Context, ws coding.Workspace) string
- func CancelScheduledTaskForUID(ctx context.Context, uid types.Uid, taskID string) error
- func CancelSessionRun(sessionID string)
- func ClearAPIRunState(sessionID string, expected *APIRunState)
- func ClearSessionPermissionGrants(ctx context.Context, sessionID string)
- func CloseEphemeralSession(ctx context.Context, sessionID string)
- func CloseSession(ctx context.Context, sessionID string) error
- func CreateSession(ctx context.Context, uid types.Uid, sessionID string) error
- func DefaultToolSnippets() map[string]string
- func DeleteUserPermissions(ctx context.Context, uid types.Uid) error
- func DisableSessionTitleLLMForTest() (restore func())
- func DrainPublisherSSE(w SSEWriter, publisher *ChannelPublisher)
- func EditableScheduledTaskState(state string) bool
- func EstimateTextTokens(text string) int
- func EvictHarnessPool(sessionID string)
- func ExecuteScheduledTaskForTest(ctx context.Context, task *gen.ChatScheduledTask)
- func ExtractResourceURIs(text string) []string
- func FormatProgressMarkdown(p ProgressArtifact) string
- func FormatSSEData(event StreamEvent) (string, error)
- func FormatSkillsForPrompt(skills []Skill) string
- func FormatSubagentsForPrompt(subagents []Subagent) string
- func GetSubagentDefinition(ctx context.Context, name string) (subagent.Definition, error)
- func HasPersistedToolResults(messages []HistoryMessage) bool
- func InvalidatePromptCache()
- func IsAutonomousRunKind(kind RunKind) bool
- func IsChatControlCommand(text string) bool
- func IsReadOnlyTool(name string) bool
- func IsScheduleWriteTool(name string) bool
- func LoadSessionMode(ctx context.Context, sessionID string) string
- func LoadSessionTitle(ctx context.Context, sessionID string) string
- func LoadUserPermissions(ctx context.Context, uid types.Uid) (permission.Config, error)
- func LockAppConfigForTest(t *testing.T)
- func MarshalStreamEvent(event StreamEvent) (string, error)
- func MemoryOperation(args map[string]any) string
- func MemoryScopeFromContext(ctx context.Context) string
- func NewRegistry(ws coding.Workspace, taskDeps *TaskToolDeps, scheduleDeps *ScheduleToolDeps) (*tool.Registry, error)
- func NewSubagentRegistry(ws coding.Workspace, skillAllowlist []string) (*tool.Registry, error)
- func NotifySessionModeChange(sessionID, mode string)
- func ParseCreateScheduledTaskRequest(req CreateScheduledTaskRequest) error
- func ParsePermissionsBody(raw []byte) (permission.Config, error)
- func ParseResourceURI(uri string) (scheme, ref string, err error)
- func ParseRunAt(raw string) (time.Time, error)
- func PersistSessionGrants(ctx context.Context, sessionID string, state *permission.SessionState)
- func ProgressFilePath(workspaceRoot string) string
- func PromptCacheVersion() uint64
- func PublishSessionEvent(sessionID string, event StreamEvent)
- func PublishUsageEvent(publisher EventPublisher, prompt, completion, total, window int, ...)
- func ReadOnlyToolNames() []string
- func RecordLLMUsageMessages(ctx context.Context, uid types.Uid, sessionID, source string, ...)
- func RegisterAbilityTools(registry *tool.Registry, entries []config.AbilityToolConfig, ...) ([]string, error)
- func RegisterHooks(reg *hooks.Registry, deps ChatHookDeps)
- func ResetHarnessPoolForTest()
- func ResetPermissionCacheForTest()
- func ResetPermissionSessionsForTest()
- func ResetPromptCacheForTest()
- func ResetSessionEventHubsForTest()
- func ResetSessionTitleGenerationForTest()
- func ResolveConfirm(sessionID, confirmID string, approved bool, mode ConfirmMode, pattern string, ...) (bool, error)
- func ResolveMemoryScope(req RunRequest) string
- func RunAutonomousPrompt(ctx context.Context, svc *Service, sessionID, prompt string, kind RunKind, ...) (string, error)
- func RunPipelineAgent(ctx context.Context, params abilityagent.RunParams) (*abilityagent.RunResult, error)
- func RunTimeout() time.Duration
- func SaveProgress(workspaceRoot string, p ProgressArtifact) error
- func SaveUserPermissions(ctx context.Context, uid types.Uid, cfg permission.Config) error
- func SeedDefaultSubagents(ctx context.Context) error
- func SelectableSubagentTools() []string
- func SessionOwnerUID(ctx context.Context, sessionID string) (types.Uid, error)
- func SessionSystemPrompt(ctx context.Context, ws coding.Workspace, mode string) string
- func SetGlobalScheduler(s *TaskScheduler)
- func SetSessionMode(ctx context.Context, sessionID, mode string) error
- func SetSessionModeAndNotify(ctx context.Context, sessionID, mode string) error
- func StreamAPIRun(ctx context.Context, svc *Service, sessionID, text string, w SSEWriter)
- func SumSessionRunDurationMs(ctx context.Context, sessionID string) (int64, error)
- func SystemPrompt(ctx context.Context, ws coding.Workspace) string
- func TokenUsageSourceFromRunKind(kind RunKind) string
- func ToolGroupOf(name string) string
- func TruncateProgressSummary(text string, maxTokens int) string
- func TrySetAPIRunState(sessionID string, state *APIRunState) error
- func UnbindRunCancel(sessionID string)
- func ValidScheduleKind(kind string) bool
- func ValidScheduledTaskState(state string) bool
- func ValidSessionMode(mode string) bool
- func ValidateAbilityToolConfig(cfg config.AbilityToolConfig) error
- func ValidateScheduleInput(kind, cronExpr string, runAt *time.Time) error
- func WaitForSessionTitleGenerationForTest()
- func WithMemoryScope(ctx context.Context, scope string) context.Context
- func WorkspaceFromConfig() (coding.Workspace, error)
- type APIRunOptions
- type APIRunState
- type AbilityInvoker
- type AbilityTool
- type AgentInfo
- type BufioSSEWriter
- type BuildSystemPromptOptions
- type CancelScheduledTaskTool
- func (CancelScheduledTaskTool) Description() string
- func (t CancelScheduledTaskTool) Execute(ctx context.Context, id string, args map[string]any, _ tool.UpdateHandler) (msg.ToolResultMessage, error)
- func (CancelScheduledTaskTool) Name() string
- func (CancelScheduledTaskTool) Parameters() map[string]any
- type ChannelPublisher
- type ChatHookDeps
- type ConfirmGate
- type ConfirmMode
- type ConfirmReason
- type ConfirmResponse
- type ContextCategoryInfo
- type ContextFile
- type ContextSkillTokenInfo
- type ContextUsageReport
- type CreateScheduledTaskRequest
- type DBStorage
- func (s *DBStorage) Append(ctx context.Context, entry session.TreeEntry) error
- func (s *DBStorage) GetBranch(ctx context.Context, leafID string) ([]session.TreeEntry, error)
- func (s *DBStorage) GetLeafID(ctx context.Context) (string, error)
- func (s *DBStorage) ListEntries(ctx context.Context) ([]session.TreeEntry, error)
- func (s *DBStorage) SetLeafID(ctx context.Context, id string) error
- type EphemeralRunParams
- type EphemeralRunResult
- type EventPublisher
- type HistoryMessage
- type ListScheduledTasksTool
- type ManualCompactionResult
- type PermissionSessionManager
- type PermissionsView
- type PipelineAgentRunner
- type PlanSummary
- type ProgressArtifact
- type ReadSkillTool
- type ResourceContent
- type ResourceRef
- type RunKind
- type RunRequest
- type SSEWriter
- type ScheduleTaskTool
- type ScheduleToolDeps
- type ScheduleTools
- type ScheduledDelivery
- type ScheduledTaskRunView
- type ScheduledTaskView
- func CreateScheduledTaskForUID(ctx context.Context, uid types.Uid, sourceSessionID string, ...) (*ScheduledTaskView, error)
- func GetScheduledTaskForUID(ctx context.Context, uid types.Uid, taskID string) (*ScheduledTaskView, error)
- func ListScheduledTasksForUID(ctx context.Context, uid types.Uid, states []string) ([]ScheduledTaskView, error)
- func PatchScheduledTaskForUID(ctx context.Context, uid types.Uid, taskID string, ...) (*ScheduledTaskView, error)
- func SetScheduledTaskStateForUID(ctx context.Context, uid types.Uid, taskID string, state string) (*ScheduledTaskView, error)
- type Service
- type SessionEventHub
- type SessionExport
- type SessionSummary
- type Skill
- type SkillContent
- type SkillInfo
- type StreamEvent
- type StreamSink
- type Subagent
- type SubagentInfo
- type TaskScheduler
- func (s *TaskScheduler) RegisterTask(task *gen.ChatScheduledTask) error
- func (s *TaskScheduler) Start(_ context.Context) error
- func (s *TaskScheduler) Stop(_ context.Context) error
- func (s *TaskScheduler) UnregisterTask(taskID string)
- func (s *TaskScheduler) UpdateTask(task *gen.ChatScheduledTask) error
- type TaskTool
- type TaskToolDeps
- type ToolInfo
- type ToolScopeInput
- type UpdateMemoryTool
- type UpdateScheduledTaskRequest
- type UpdateScheduledTaskTool
- func (UpdateScheduledTaskTool) Description() string
- func (t UpdateScheduledTaskTool) Execute(ctx context.Context, id string, args map[string]any, _ tool.UpdateHandler) (msg.ToolResultMessage, error)
- func (UpdateScheduledTaskTool) Name() string
- func (UpdateScheduledTaskTool) Parameters() map[string]any
Constants ¶
const ( // ModeNormal allows full tool access according to user permissions. ModeNormal = string(schema.ChatSessionModeNormal) // ModePlan restricts the agent to read-only research tools. ModePlan = string(schema.ChatSessionModePlan) )
const ( // PermissionTopic is the ConfigData topic for chat agent permissions. PermissionTopic = "chatagent" // PermissionKey is the ConfigData key for chat agent permissions. PermissionKey = "permission" )
const ( // ProgressRelPath is the workspace-relative progress artifact path. ProgressRelPath = ".flowbot/progress.md" // ProgressTokenCap is the hard token limit for progress injected into context. ProgressTokenCap = 500 )
const ( EventTypeDelta = "delta" EventTypeThinking = "thinking" EventTypeTool = "tool" EventTypeTurn = "turn" EventTypeUsage = "usage" EventTypeConfirm = "confirm" EventTypeConfirmResolved = "confirm_resolved" EventTypeModeChange = "mode_change" EventTypeCanceled = "canceled" EventTypeDone = "done" EventTypeError = "error" )
Stream event type constants for Chat Agent SSE clients.
const ( // PlanLocationPrefix is the URI scheme for persisted plan documents. PlanLocationPrefix = "plan://" // FileLocationPrefix is the URI scheme for workspace-relative files. FileLocationPrefix = "file://" )
const ( ToolGroupCore = "core" ToolGroupFS = "fs" ToolGroupShell = "shell" ToolGroupSearch = "search" ToolGroupSchedule = "schedule" ToolGroupSubagent = "subagent" ToolGroupMemory = "memory" )
Tool group name constants for dynamic activation.
const DefaultRunTimeout = 10 * time.Minute
DefaultRunTimeout is the maximum duration for one assistant turn when not configured.
const ReasonConfirmRequiredPlatform = "This action requires approval. " +
"Use the Web UI or configure permissions via PUT /chatagent/permissions."
ReasonConfirmRequiredPlatform is returned when ActionAsk cannot be resolved without a ConfirmGate.
Variables ¶
var ( // ErrConfirmNotFound means no pending confirmation exists for the session. ErrConfirmNotFound = errors.New("confirm not found") // ErrConfirmResolved means the confirmation was already resolved. ErrConfirmResolved = errors.New("confirm already resolved") // ErrChatAgentDisabled means chat agent is not configured. ErrChatAgentDisabled = errors.New("chat agent disabled") // ErrRunInFlight means the session already has an active SSE run. ErrRunInFlight = errors.New("run already in progress") )
API error sentinels for Chat Agent HTTP handlers.
var NewModelForTest = agentllm.GetOrCreateModel
NewModelForTest overrides model creation in unit tests.
Functions ¶
func AbilityToolNames ¶ added in v0.95.0
func AbilityToolNames() []string
AbilityToolNames returns configured ability tool names.
func AbortSessionHarness ¶
func AbortSessionHarness(sessionID string)
AbortSessionHarness cooperatively cancels the agent loop for a pooled session harness.
func ActiveToolNames ¶
func ActiveToolNames() []string
ActiveToolNames returns the default active tool names for the chat assistant, including configured readonly ability tools.
func AppendPlanLinkFooter ¶ added in v0.94.0
AppendPlanLinkFooter appends a markdown plan link to the assistant reply.
func ApplyToolScope ¶ added in v0.95.0
func ApplyToolScope(in ToolScopeInput) []string
ApplyToolScope selects the active tool set for one Prompt. Plan mode uses the read-only set. Normal mode excludes schedule tools unless the run is a cron scheduled task or the user message matches schedule intent.
func BaseToolNamesForRun ¶ added in v0.95.0
BaseToolNamesForRun returns the active tool set for one run. Autonomous runs omit update_memory unless it appears in explicitTools.
func BeginEphemeralSession ¶ added in v0.95.0
BeginEphemeralSession creates a temporary chat session for one autonomous run.
func BindRunCancel ¶
func BindRunCancel(sessionID string, cancel context.CancelFunc)
BindRunCancel ties an agent run cancel function to a session for cooperative cancellation.
func BuildSystemPrompt ¶
func BuildSystemPrompt(options BuildSystemPromptOptions) string
BuildSystemPrompt constructs the chat assistant system prompt.
func CachedSystemPrompt ¶
CachedSystemPrompt returns the chat assistant system prompt, reusing a process cache when inputs are unchanged.
func CancelScheduledTaskForUID ¶ added in v0.94.0
CancelScheduledTaskForUID cancels one owned task.
func CancelSessionRun ¶
func CancelSessionRun(sessionID string)
CancelSessionRun aborts the in-flight agent run for a session.
func ClearAPIRunState ¶
func ClearAPIRunState(sessionID string, expected *APIRunState)
ClearAPIRunState removes run state only when it matches the active connection.
func ClearSessionPermissionGrants ¶
ClearSessionPermissionGrants resets always grants and doom-loop counters for one session.
func CloseEphemeralSession ¶ added in v0.95.0
CloseEphemeralSession closes a temporary session. Failures are logged and not returned.
func CloseSession ¶
CloseSession marks a chat session as closed, cancels in-flight runs, and releases locks. The ordering (cancel -> close DB -> release lock) ensures no new run can start on a closing session.
func CreateSession ¶
CreateSession persists a new chat session row for the user.
func DefaultToolSnippets ¶
DefaultToolSnippets returns one-line tool descriptions for the chat assistant.
func DeleteUserPermissions ¶
DeleteUserPermissions removes user permission overrides.
func DisableSessionTitleLLMForTest ¶ added in v0.94.0
func DisableSessionTitleLLMForTest() (restore func())
DisableSessionTitleLLMForTest skips outbound title LLM calls until restore runs.
func DrainPublisherSSE ¶ added in v0.95.0
func DrainPublisherSSE(w SSEWriter, publisher *ChannelPublisher)
DrainPublisherSSE drains buffered publisher events to w until empty or terminal.
func EditableScheduledTaskState ¶ added in v0.94.0
EditableScheduledTaskState reports whether schedule fields may be changed.
func EstimateTextTokens ¶
EstimateTextTokens conservatively estimates token count for raw text.
func EvictHarnessPool ¶
func EvictHarnessPool(sessionID string)
EvictHarnessPool removes a cached harness for the given session.
func ExecuteScheduledTaskForTest ¶ added in v0.94.0
func ExecuteScheduledTaskForTest(ctx context.Context, task *gen.ChatScheduledTask)
ExecuteScheduledTaskForTest runs one scheduled task; exposed for integration specs.
func ExtractResourceURIs ¶ added in v0.94.0
ExtractResourceURIs returns plan:// and file:// URIs referenced in markdown links.
func FormatProgressMarkdown ¶ added in v0.95.0
func FormatProgressMarkdown(p ProgressArtifact) string
FormatProgressMarkdown renders a progress artifact as markdown.
func FormatSSEData ¶
func FormatSSEData(event StreamEvent) (string, error)
FormatSSEData returns a complete SSE data line payload for writing to the stream.
func FormatSkillsForPrompt ¶
FormatSkillsForPrompt renders skills in XML for the system prompt.
func FormatSubagentsForPrompt ¶
FormatSubagentsForPrompt renders the available subagents in XML for the system prompt.
func GetSubagentDefinition ¶
GetSubagentDefinition loads one enabled subagent by name as a runnable definition.
func HasPersistedToolResults ¶ added in v0.95.0
func HasPersistedToolResults(messages []HistoryMessage) bool
HasPersistedToolResults reports whether history rows include persisted tool result messages.
func InvalidatePromptCache ¶
func InvalidatePromptCache()
InvalidatePromptCache clears the cached system prompt so the next request rebuilds it.
func IsAutonomousRunKind ¶ added in v0.95.0
IsAutonomousRunKind reports whether the run uses scheduled-style permissions.
func IsChatControlCommand ¶
IsChatControlCommand reports whether the message is a chat session control command.
func IsReadOnlyTool ¶ added in v0.94.0
IsReadOnlyTool reports whether name is allowed in plan mode.
func IsScheduleWriteTool ¶ added in v0.94.0
IsScheduleWriteTool reports tools blocked in plan mode.
func LoadSessionMode ¶ added in v0.94.0
LoadSessionMode reads the persisted mode for one session, defaulting to normal.
func LoadSessionTitle ¶ added in v0.94.0
LoadSessionTitle returns the persisted title for one chat session.
func LoadUserPermissions ¶
LoadUserPermissions reads merged effective permission config for one user.
func LockAppConfigForTest ¶ added in v0.95.0
LockAppConfigForTest serializes reads and writes of config.App during parallel tests.
func MarshalStreamEvent ¶
func MarshalStreamEvent(event StreamEvent) (string, error)
MarshalStreamEvent serializes one SSE data frame body.
func MemoryOperation ¶ added in v0.95.0
MemoryOperation extracts the operation argument from update_memory tool args.
func MemoryScopeFromContext ¶ added in v0.95.0
MemoryScopeFromContext returns the memory scope stored on ctx, or empty when unset.
func NewRegistry ¶
func NewRegistry(ws coding.Workspace, taskDeps *TaskToolDeps, scheduleDeps *ScheduleToolDeps) (*tool.Registry, error)
NewRegistry registers assistant tools including DB-backed skills support. When taskDeps is non-nil, the subagent delegation task tool is registered and activated. When scheduleDeps is non-nil, scheduled task tools are registered and activated.
func NewSubagentRegistry ¶ added in v0.94.0
NewSubagentRegistry registers coding tools and an optional allowlisted read_skill tool for subagent runs.
func NotifySessionModeChange ¶ added in v0.94.0
func NotifySessionModeChange(sessionID, mode string)
NotifySessionModeChange publishes a mode_change event to session SSE subscribers.
func ParseCreateScheduledTaskRequest ¶ added in v0.94.0
func ParseCreateScheduledTaskRequest(req CreateScheduledTaskRequest) error
ParseCreateScheduledTaskRequest validates create request fields.
func ParsePermissionsBody ¶
func ParsePermissionsBody(raw []byte) (permission.Config, error)
ParsePermissionsBody unmarshals a PUT /chatagent/permissions request body.
func ParseResourceURI ¶ added in v0.94.0
ParseResourceURI splits a resource URI into scheme and reference.
func ParseRunAt ¶ added in v0.94.0
ParseRunAt parses an ISO8601 UTC timestamp for one-shot tasks.
func PersistSessionGrants ¶ added in v0.94.0
func PersistSessionGrants(ctx context.Context, sessionID string, state *permission.SessionState)
PersistSessionGrants writes the current session grants to storage.
func ProgressFilePath ¶ added in v0.95.0
ProgressFilePath returns the absolute path to the progress artifact.
func PromptCacheVersion ¶
func PromptCacheVersion() uint64
PromptCacheVersion returns a monotonic version token for prompt cache invalidation.
func PublishSessionEvent ¶ added in v0.94.0
func PublishSessionEvent(sessionID string, event StreamEvent)
PublishSessionEvent delivers one event to all SSE subscribers for a session.
func PublishUsageEvent ¶
func PublishUsageEvent(publisher EventPublisher, prompt, completion, total, window int, percent float64)
PublishUsageEvent emits a context usage snapshot to the client.
func ReadOnlyToolNames ¶ added in v0.94.0
func ReadOnlyToolNames() []string
ReadOnlyToolNames returns the active tool set for plan mode.
func RecordLLMUsageMessages ¶ added in v0.95.0
func RecordLLMUsageMessages(ctx context.Context, uid types.Uid, sessionID, source string, messages []agent.AgentMessage)
RecordLLMUsageMessages persists token usage from assistant messages.
func RegisterAbilityTools ¶ added in v0.95.0
func RegisterAbilityTools(registry *tool.Registry, entries []config.AbilityToolConfig, invoke AbilityInvoker) ([]string, error)
RegisterAbilityTools validates and registers configured ability tools.
func RegisterHooks ¶
func RegisterHooks(reg *hooks.Registry, deps ChatHookDeps)
RegisterHooks wires observational and API hooks for one chat agent harness run.
func ResetHarnessPoolForTest ¶
func ResetHarnessPoolForTest()
ResetHarnessPoolForTest clears all pooled harnesses.
func ResetPermissionCacheForTest ¶
func ResetPermissionCacheForTest()
ResetPermissionCacheForTest clears the in-memory permission cache.
func ResetPermissionSessionsForTest ¶
func ResetPermissionSessionsForTest()
ResetPermissionSessionsForTest clears all in-memory permission session state.
func ResetPromptCacheForTest ¶
func ResetPromptCacheForTest()
ResetPromptCacheForTest clears the in-process system prompt cache.
func ResetSessionEventHubsForTest ¶
func ResetSessionEventHubsForTest()
ResetSessionEventHubsForTest clears all session event hubs.
func ResetSessionTitleGenerationForTest ¶ added in v0.94.0
func ResetSessionTitleGenerationForTest()
ResetSessionTitleGenerationForTest clears per-session title generation tracking.
func ResolveConfirm ¶
func ResolveConfirm(sessionID, confirmID string, approved bool, mode ConfirmMode, pattern string, reason ConfirmReason) (bool, error)
ResolveConfirm applies a client confirmation for the active gate on a session.
func ResolveMemoryScope ¶ added in v0.95.0
func ResolveMemoryScope(req RunRequest) string
ResolveMemoryScope picks the memory scope for one run request.
func RunAutonomousPrompt ¶ added in v0.95.0
func RunAutonomousPrompt(ctx context.Context, svc *Service, sessionID, prompt string, kind RunKind, tools, skills []string, memoryScope string) (string, error)
RunAutonomousPrompt executes one prompt in an existing session with RunTimeout.
func RunPipelineAgent ¶ added in v0.95.0
func RunPipelineAgent(ctx context.Context, params abilityagent.RunParams) (*abilityagent.RunResult, error)
RunPipelineAgent executes one pipeline agent step via an ephemeral session.
func RunTimeout ¶
RunTimeout returns the configured per-turn timeout for the chat assistant.
func SaveProgress ¶ added in v0.95.0
func SaveProgress(workspaceRoot string, p ProgressArtifact) error
SaveProgress writes the progress artifact under the workspace.
func SaveUserPermissions ¶
SaveUserPermissions persists one user's permission overrides.
func SeedDefaultSubagents ¶
SeedDefaultSubagents inserts built-in subagent definitions when none exist yet. It is a best-effort startup helper and never overwrites user-managed rows.
func SelectableSubagentTools ¶ added in v0.94.0
func SelectableSubagentTools() []string
SelectableSubagentTools returns tool names available for subagent allowlist configuration.
func SessionOwnerUID ¶
SessionOwnerUID resolves the owning user for one chat session.
func SessionSystemPrompt ¶ added in v0.94.0
SessionSystemPrompt builds the system prompt for one session mode.
func SetGlobalScheduler ¶ added in v0.94.0
func SetGlobalScheduler(s *TaskScheduler)
SetGlobalScheduler wires the process-wide scheduler used by schedule tools.
func SetSessionMode ¶ added in v0.94.0
SetSessionMode persists a session mode toggle.
func SetSessionModeAndNotify ¶ added in v0.94.0
SetSessionModeAndNotify persists mode and notifies connected SSE clients.
func StreamAPIRun ¶ added in v0.95.0
StreamAPIRun executes one agent turn and streams SSE events to w.
func SumSessionRunDurationMs ¶ added in v0.95.0
SumSessionRunDurationMs returns cumulative run milliseconds across all completed user turns in the session's active branch. Each run stores RunDurationMs on one assistant message.
func SystemPrompt ¶
SystemPrompt builds the default chat assistant prompt from workspace, config, and DB skills.
func TokenUsageSourceFromRunKind ¶ added in v0.95.0
TokenUsageSourceFromRunKind maps a chat agent run kind to a persisted usage source.
func ToolGroupOf ¶ added in v0.95.0
ToolGroupOf returns the group for a known tool name.
func TruncateProgressSummary ¶ added in v0.95.0
TruncateProgressSummary caps text to approximately maxTokens using EstimateTextTokens.
func TrySetAPIRunState ¶
func TrySetAPIRunState(sessionID string, state *APIRunState) error
TrySetAPIRunState registers run state when no other run is active for the session.
func UnbindRunCancel ¶
func UnbindRunCancel(sessionID string)
UnbindRunCancel removes the run cancel function for a session.
func ValidScheduleKind ¶ added in v0.94.0
ValidScheduleKind reports whether kind is supported.
func ValidScheduledTaskState ¶ added in v0.94.0
ValidScheduledTaskState reports whether state is a known task lifecycle value.
func ValidSessionMode ¶ added in v0.94.0
ValidSessionMode reports whether mode is a supported session mode value.
func ValidateAbilityToolConfig ¶ added in v0.95.0
func ValidateAbilityToolConfig(cfg config.AbilityToolConfig) error
ValidateAbilityToolConfig rejects non-readonly or incomplete ability tool entries.
func ValidateScheduleInput ¶ added in v0.94.0
ValidateScheduleInput validates create/update schedule fields.
func WaitForSessionTitleGenerationForTest ¶ added in v0.94.0
func WaitForSessionTitleGenerationForTest()
WaitForSessionTitleGenerationForTest blocks until all in-flight async title generations finish.
func WithMemoryScope ¶ added in v0.95.0
WithMemoryScope stores the active memory scope on ctx for update_memory tool calls.
func WorkspaceFromConfig ¶
WorkspaceFromConfig resolves workspace settings from application config.
Types ¶
type APIRunOptions ¶
type APIRunOptions struct {
Publisher EventPublisher
Confirm *ConfirmGate
}
APIRunOptions configures an HTTP Chat Agent run with SSE publishing and confirmations.
type APIRunState ¶
type APIRunState struct {
// contains filtered or unexported fields
}
APIRunState tracks one in-flight HTTP run for cancel and confirm routing.
func GetAPIRunState ¶
func GetAPIRunState(sessionID string) (*APIRunState, bool)
GetAPIRunState returns the active HTTP run state when present.
func NewAPIRunState ¶
func NewAPIRunState(publisher *ChannelPublisher, gate *ConfirmGate) *APIRunState
NewAPIRunState builds run state for an active SSE connection.
func (*APIRunState) Publisher ¶
func (s *APIRunState) Publisher() EventPublisher
Publisher returns the SSE publisher when present.
type AbilityInvoker ¶ added in v0.95.0
type AbilityInvoker func(ctx context.Context, capability hub.CapabilityType, operation string, params map[string]any) (*ability.InvokeResult, error)
AbilityInvoker invokes a capability operation; defaults to ability.Invoke.
type AbilityTool ¶ added in v0.95.0
type AbilityTool struct {
// contains filtered or unexported fields
}
AbilityTool exposes a readonly ability operation as an agent tool.
func NewAbilityTool ¶ added in v0.95.0
func NewAbilityTool(cfg config.AbilityToolConfig, invoke AbilityInvoker) (*AbilityTool, error)
NewAbilityTool builds an AbilityTool from config. Readonly must be true.
func (AbilityTool) Description ¶ added in v0.95.0
func (t AbilityTool) Description() string
Description explains the tool to the model.
func (AbilityTool) Execute ¶ added in v0.95.0
func (t AbilityTool) Execute(ctx context.Context, id string, args map[string]any, _ tool.UpdateHandler) (msg.ToolResultMessage, error)
Execute invokes the configured ability operation.
func (AbilityTool) Name ¶ added in v0.95.0
func (t AbilityTool) Name() string
Name returns the tool identifier.
func (AbilityTool) Parameters ¶ added in v0.95.0
func (AbilityTool) Parameters() map[string]any
Parameters returns a generic object schema for ability params.
type AgentInfo ¶
type AgentInfo struct {
Version string `json:"version"`
ChatModel string `json:"chat_model"`
ToolModel string `json:"tool_model"`
Provider string `json:"provider"`
Workspace string `json:"workspace"`
Tools []ToolInfo `json:"tools"`
Skills []SkillInfo `json:"skills"`
Subagents []SubagentInfo `json:"subagents"`
ToolCount int `json:"tool_count"`
SkillCount int `json:"skill_count"`
SubagentCount int `json:"subagent_count"`
}
AgentInfo is startup metadata for the Chat Agent HTTP client.
type BufioSSEWriter ¶ added in v0.95.0
BufioSSEWriter writes SSE frames to a buffered writer.
func (*BufioSSEWriter) WriteEvent ¶ added in v0.95.0
func (b *BufioSSEWriter) WriteEvent(event StreamEvent) bool
WriteEvent serializes one event and flushes it to the stream.
type BuildSystemPromptOptions ¶
type BuildSystemPromptOptions struct {
// CustomPrompt replaces the default prompt body when non-empty.
CustomPrompt string
// SelectedTools limits which tools appear in the Available tools section.
SelectedTools []string
// ToolSnippets provides one-line descriptions keyed by tool name.
ToolSnippets map[string]string
// PromptGuidelines adds extra guideline bullets after tool-specific defaults.
PromptGuidelines []string
// AppendSystemPrompt is appended after the main body and before project context.
AppendSystemPrompt string
// CWD is the sandbox workspace root shown to the model.
CWD string
// ContextFiles are pre-loaded project instruction files.
ContextFiles []ContextFile
// Skills are agent skills injected into the prompt; nil loads from the database.
Skills []Skill
// Subagents are delegation targets injected into the prompt for the task tool.
Subagents []Subagent
// Mode selects plan vs normal prompt behavior; empty means normal.
Mode string
}
BuildSystemPromptOptions configures system prompt construction.
type CancelScheduledTaskTool ¶ added in v0.94.0
type CancelScheduledTaskTool struct {
// contains filtered or unexported fields
}
CancelScheduledTaskTool cancels a scheduled task.
func (CancelScheduledTaskTool) Description ¶ added in v0.94.0
func (CancelScheduledTaskTool) Description() string
func (CancelScheduledTaskTool) Execute ¶ added in v0.94.0
func (t CancelScheduledTaskTool) Execute(ctx context.Context, id string, args map[string]any, _ tool.UpdateHandler) (msg.ToolResultMessage, error)
func (CancelScheduledTaskTool) Name ¶ added in v0.94.0
func (CancelScheduledTaskTool) Name() string
func (CancelScheduledTaskTool) Parameters ¶ added in v0.94.0
func (CancelScheduledTaskTool) Parameters() map[string]any
type ChannelPublisher ¶
type ChannelPublisher struct {
// contains filtered or unexported fields
}
ChannelPublisher sends stream events to a buffered channel for SSE writers.
func NewChannelPublisher ¶
func NewChannelPublisher(buffer int) *ChannelPublisher
NewChannelPublisher creates a publisher backed by a buffered event channel.
func (*ChannelPublisher) Close ¶
func (p *ChannelPublisher) Close()
Close marks the publisher done and closes the channel.
func (*ChannelPublisher) Events ¶
func (p *ChannelPublisher) Events() <-chan StreamEvent
Events returns the readable event channel.
func (*ChannelPublisher) Publish ¶
func (p *ChannelPublisher) Publish(event StreamEvent) error
Publish enqueues one stream event for the SSE writer goroutine.
type ChatHookDeps ¶
ChatHookDeps carries per-run metadata for chat agent hook handlers.
type ConfirmGate ¶
type ConfirmGate struct {
// contains filtered or unexported fields
}
ConfirmGate blocks tool execution until the client approves or denies.
func NewConfirmGate ¶
func NewConfirmGate(sessionID string, publisher EventPublisher) *ConfirmGate
NewConfirmGate creates a gate that publishes confirm events to session subscribers.
func (*ConfirmGate) Cancel ¶
func (g *ConfirmGate) Cancel()
Cancel closes the gate without approving, used when the run is aborted.
func (*ConfirmGate) ID ¶
func (g *ConfirmGate) ID() string
ID returns the confirmation request identifier shared with the client.
func (*ConfirmGate) Resolve ¶
func (g *ConfirmGate) Resolve(resp ConfirmResponse) bool
Resolve applies the client decision. Returns false when the gate is already resolved.
func (*ConfirmGate) Wait ¶
func (g *ConfirmGate) Wait(ctx context.Context, event hooks.ToolCallEvent, eval permission.Result) (ConfirmResponse, error)
Wait publishes a confirm event and blocks until the client responds or times out.
type ConfirmMode ¶
type ConfirmMode string
ConfirmMode is how the user resolved an approval prompt.
const ( ConfirmModeOnce ConfirmMode = "once" ConfirmModeAlways ConfirmMode = "always" ConfirmModeReject ConfirmMode = "reject" )
type ConfirmReason ¶
type ConfirmReason string
ConfirmReason describes how a tool confirmation was resolved.
const ( ConfirmReasonApproved ConfirmReason = "approved" ConfirmReasonDenied ConfirmReason = "denied" ConfirmReasonTimeout ConfirmReason = "timeout" )
type ConfirmResponse ¶
type ConfirmResponse struct {
Approved bool
Reason ConfirmReason
Mode ConfirmMode
Pattern string
}
ConfirmResponse is the user's answer to a pending tool confirmation.
type ContextCategoryInfo ¶
type ContextCategoryInfo struct {
ID string `json:"id"`
Label string `json:"label"`
Tokens int `json:"tokens"`
Percent float64 `json:"percent"`
}
ContextCategoryInfo is one row in the context usage breakdown.
type ContextFile ¶
ContextFile holds project-specific instructions injected into the system prompt.
func LoadDefaultContextFiles ¶
func LoadDefaultContextFiles(cwd string) []ContextFile
LoadDefaultContextFiles discovers common project instruction files under cwd.
type ContextSkillTokenInfo ¶
ContextSkillTokenInfo reports estimated prompt tokens for one skill entry.
type ContextUsageReport ¶
type ContextUsageReport struct {
Model string `json:"model"`
ToolModel string `json:"tool_model,omitempty"`
ContextWindow int `json:"context_window"`
TotalTokens int `json:"total_tokens"`
TotalPercent float64 `json:"total_percent"`
CompactionEnabled bool `json:"compaction_enabled"`
Categories []ContextCategoryInfo `json:"categories"`
Skills []ContextSkillTokenInfo `json:"skills"`
}
ContextUsageReport is the full context budget snapshot for a chat session.
func BuildContextUsageReport ¶
func BuildContextUsageReport(ctx context.Context, sessionID string) (ContextUsageReport, error)
BuildContextUsageReport assembles a context budget breakdown for Chat Agent clients.
type CreateScheduledTaskRequest ¶ added in v0.94.0
type CreateScheduledTaskRequest struct {
Name string `json:"name"`
Prompt string `json:"prompt"`
Cron string `json:"cron,omitempty"`
RunAt string `json:"run_at,omitempty"`
}
CreateScheduledTaskRequest carries HTTP POST fields for a new scheduled task.
type DBStorage ¶
type DBStorage struct {
// contains filtered or unexported fields
}
DBStorage persists agent session trees in PostgreSQL.
func NewDBStorage ¶
NewDBStorage creates a session storage adapter for the given session flag, owner uid, and usage source.
func (*DBStorage) ListEntries ¶
ListEntries returns all entries for the session in storage order.
type EphemeralRunParams ¶ added in v0.95.0
type EphemeralRunParams struct {
UID types.Uid
Prompt string
Kind RunKind
Tools []string
Skills []string
MemoryScope string
}
EphemeralRunParams describes one isolated autonomous agent turn.
type EphemeralRunResult ¶ added in v0.95.0
EphemeralRunResult holds the outcome of one ephemeral run.
func RunEphemeral ¶ added in v0.95.0
func RunEphemeral(ctx context.Context, svc *Service, params EphemeralRunParams) (EphemeralRunResult, error)
RunEphemeral creates a temporary session, runs one prompt, and closes the session.
type EventPublisher ¶
type EventPublisher interface {
Publish(event StreamEvent) error
}
EventPublisher delivers stream events to an active HTTP SSE connection.
type HistoryMessage ¶
type HistoryMessage struct {
Role string `json:"role"`
Kind string `json:"kind"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
ToolName string `json:"tool_name,omitempty"`
ToolStatus string `json:"tool_status,omitempty"`
DurationMs int64 `json:"duration_ms,omitempty"`
TurnDurationMs int64 `json:"turn_duration_ms,omitempty"`
ThinkingDurationMs int64 `json:"thinking_duration_ms,omitempty"`
RunDurationMs int64 `json:"run_duration_ms,omitempty"`
ThinkingText string `json:"thinking_text,omitempty"`
}
HistoryMessage is one persisted chat row exposed to HTTP clients.
func ListSessionMessages ¶
func ListSessionMessages(ctx context.Context, sessionID string) ([]HistoryMessage, error)
ListSessionMessages returns user and assistant messages for a session branch.
type ListScheduledTasksTool ¶ added in v0.94.0
type ListScheduledTasksTool struct {
// contains filtered or unexported fields
}
ListScheduledTasksTool lists active and paused tasks for the user.
func (ListScheduledTasksTool) Description ¶ added in v0.94.0
func (ListScheduledTasksTool) Description() string
func (ListScheduledTasksTool) Execute ¶ added in v0.94.0
func (t ListScheduledTasksTool) Execute(ctx context.Context, id string, _ map[string]any, _ tool.UpdateHandler) (msg.ToolResultMessage, error)
func (ListScheduledTasksTool) Name ¶ added in v0.94.0
func (ListScheduledTasksTool) Name() string
func (ListScheduledTasksTool) Parameters ¶ added in v0.94.0
func (ListScheduledTasksTool) Parameters() map[string]any
type ManualCompactionResult ¶
ManualCompactionResult reports the outcome of a user-triggered compaction run.
type PermissionSessionManager ¶
type PermissionSessionManager struct {
// contains filtered or unexported fields
}
PermissionSessionManager keeps permission session state across runs for one chat session.
func (*PermissionSessionManager) ClearPermissionSession ¶
func (m *PermissionSessionManager) ClearPermissionSession(ctx context.Context, sessionID string)
ClearPermissionSession removes session permission state and persisted grants.
func (*PermissionSessionManager) GetPermissionSession ¶
func (m *PermissionSessionManager) GetPermissionSession(ctx context.Context, sessionID string) *permission.SessionState
GetPermissionSession returns or creates session-scoped permission state.
type PermissionsView ¶
type PermissionsView struct {
Defaults permission.Config `json:"defaults"`
User permission.Config `json:"user"`
Effective permission.Config `json:"effective"`
SessionGrants map[string][]string `json:"session_grants,omitempty"`
}
PermissionsView is the API payload for permission configuration.
func BuildPermissionsView ¶
func BuildPermissionsView(ctx context.Context, uid types.Uid, sessionID string) (PermissionsView, error)
BuildPermissionsView assembles permission state for one user and optional session.
type PipelineAgentRunner ¶ added in v0.95.0
type PipelineAgentRunner struct{}
PipelineAgentRunner implements abilityagent.Runner for pipeline steps.
func (PipelineAgentRunner) Run ¶ added in v0.95.0
func (PipelineAgentRunner) Run(ctx context.Context, params abilityagent.RunParams) (*abilityagent.RunResult, error)
Run executes one pipeline agent step.
type PlanSummary ¶ added in v0.94.0
type PlanSummary struct {
PlanID string `json:"plan_id"`
URI string `json:"uri"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
}
PlanSummary is a lightweight plan listing item for HTTP clients.
func ListPlanSummaries ¶ added in v0.94.0
func ListPlanSummaries(ctx context.Context, sessionID string) ([]PlanSummary, error)
ListPlanSummaries returns plan metadata for one session.
type ProgressArtifact ¶ added in v0.95.0
type ProgressArtifact struct {
// Goal is the primary user objective.
Goal string
// Done lists completed steps.
Done []string
// Next lists remaining steps.
Next []string
}
ProgressArtifact holds the durable goal/done/next summary for a workspace run.
func DeriveProgressFromMessages ¶ added in v0.95.0
func DeriveProgressFromMessages(messages []msg.AgentMessage) ProgressArtifact
DeriveProgressFromMessages builds a progress artifact from the working message list.
func LoadProgress ¶ added in v0.95.0
func LoadProgress(workspaceRoot string) (ProgressArtifact, error)
LoadProgress reads the progress artifact from the workspace when present.
func ParseProgressMarkdown ¶ added in v0.95.0
func ParseProgressMarkdown(text string) ProgressArtifact
ParseProgressMarkdown parses a progress.md document into an artifact.
type ReadSkillTool ¶
type ReadSkillTool struct {
// contains filtered or unexported fields
}
ReadSkillTool loads skill instructions from the database by name.
func NewReadSkillTool ¶ added in v0.94.0
func NewReadSkillTool(allowed []string) ReadSkillTool
NewReadSkillTool creates a read_skill tool optionally restricted to allowed skill names.
func (ReadSkillTool) Description ¶
func (ReadSkillTool) Description() string
Description explains the tool to the model.
func (ReadSkillTool) Execute ¶
func (t ReadSkillTool) Execute(ctx context.Context, id string, args map[string]any, _ tool.UpdateHandler) (msg.ToolResultMessage, error)
Execute returns the stored skill content.
func (ReadSkillTool) Parameters ¶
func (ReadSkillTool) Parameters() map[string]any
Parameters returns the JSON schema for tool arguments.
type ResourceContent ¶ added in v0.94.0
type ResourceContent struct {
URI string
Kind string
Title string
Content string
ContentType string
Truncated bool
}
ResourceContent is the resolved body of a chat agent resource URI.
func ResolveResource ¶ added in v0.94.0
func ResolveResource(ctx context.Context, sessionID, uri string) (ResourceContent, error)
ResolveResource loads one plan:// or file:// resource for a session.
type ResourceRef ¶ added in v0.94.0
type ResourceRef struct {
URI string `json:"uri"`
Kind string `json:"kind"`
Title string `json:"title"`
}
ResourceRef identifies one loadable resource emitted with a done event.
func FormatPlanResourceRef ¶ added in v0.94.0
func FormatPlanResourceRef(planID, title string) ResourceRef
FormatPlanResourceRef builds a plan resource reference for SSE and clients.
type RunKind ¶ added in v0.94.0
type RunKind string
RunKind distinguishes interactive runs from autonomous scheduled task runs.
const ( // RunKindInteractive is the default chat agent run initiated by a user message. RunKindInteractive RunKind = "interactive" // RunKindScheduled is an autonomous run triggered by a scheduled task. RunKindScheduled RunKind = "scheduled" // RunKindPipeline is an autonomous run triggered by a pipeline agent step. RunKindPipeline RunKind = "pipeline" )
type RunRequest ¶
type RunRequest struct {
SessionID string
Text string
API *APIRunOptions
Kind RunKind
RunStartedAt time.Time
Tools []string
Skills []string
MemoryScope string
}
RunRequest carries one user turn for the chat assistant.
type SSEWriter ¶ added in v0.95.0
type SSEWriter interface {
WriteEvent(event StreamEvent) (terminal bool)
}
SSEWriter writes chat agent stream events to an HTTP response body.
type ScheduleTaskTool ¶ added in v0.94.0
type ScheduleTaskTool struct {
// contains filtered or unexported fields
}
ScheduleTaskTool creates cron or one-shot scheduled tasks.
func (ScheduleTaskTool) Description ¶ added in v0.94.0
func (ScheduleTaskTool) Description() string
func (ScheduleTaskTool) Execute ¶ added in v0.94.0
func (t ScheduleTaskTool) Execute(ctx context.Context, id string, args map[string]any, _ tool.UpdateHandler) (msg.ToolResultMessage, error)
func (ScheduleTaskTool) Name ¶ added in v0.94.0
func (ScheduleTaskTool) Name() string
func (ScheduleTaskTool) Parameters ¶ added in v0.94.0
func (ScheduleTaskTool) Parameters() map[string]any
type ScheduleToolDeps ¶ added in v0.94.0
ScheduleToolDeps carries per-run metadata for scheduled task tools.
type ScheduleTools ¶ added in v0.94.0
type ScheduleTools struct {
// contains filtered or unexported fields
}
ScheduleTools registers create/list/update/cancel scheduled task tools.
func NewScheduleTools ¶ added in v0.94.0
func NewScheduleTools(deps ScheduleToolDeps) ScheduleTools
NewScheduleTools binds scheduled task tools to one chat run.
type ScheduledDelivery ¶ added in v0.94.0
type ScheduledDelivery struct {
Platform string `json:"platform,omitempty"`
Topic string `json:"topic,omitempty"`
PlatformID int64 `json:"platform_id,omitempty"`
}
ScheduledDelivery captures where to push task results.
func ResolveDeliveryContext ¶ added in v0.94.0
func ResolveDeliveryContext(ctx context.Context, sessionID string) ScheduledDelivery
ResolveDeliveryContext loads platform delivery info from the latest session message.
type ScheduledTaskRunView ¶ added in v0.94.0
type ScheduledTaskRunView struct {
RunID string `json:"run_id"`
TaskID string `json:"task_id"`
RunSessionID string `json:"run_session_id"`
State string `json:"state"`
Reply string `json:"reply,omitempty"`
Error string `json:"error,omitempty"`
StartedAt time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
ScheduledTaskRunView is the API representation of one task execution.
func ListScheduledTaskRuns ¶ added in v0.94.0
func ListScheduledTaskRuns(ctx context.Context, uid types.Uid, taskID string, limit int) ([]ScheduledTaskRunView, error)
ListScheduledTaskRuns returns recent runs for one owned task.
type ScheduledTaskView ¶ added in v0.94.0
type ScheduledTaskView struct {
TaskID string `json:"task_id"`
Name string `json:"name"`
ScheduleKind string `json:"schedule_kind"`
Cron string `json:"cron,omitempty"`
RunAt *time.Time `json:"run_at,omitempty"`
Prompt string `json:"prompt"`
State string `json:"state"`
SourceSessionID string `json:"source_session_id,omitempty"`
LastRunAt *time.Time `json:"last_run_at,omitempty"`
NextRunAt *time.Time `json:"next_run_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
ScheduledTaskView is the API representation of one scheduled task.
func CreateScheduledTaskForUID ¶ added in v0.94.0
func CreateScheduledTaskForUID(ctx context.Context, uid types.Uid, sourceSessionID string, req CreateScheduledTaskRequest) (*ScheduledTaskView, error)
CreateScheduledTaskForUID creates one owned scheduled task.
func GetScheduledTaskForUID ¶ added in v0.94.0
func GetScheduledTaskForUID(ctx context.Context, uid types.Uid, taskID string) (*ScheduledTaskView, error)
GetScheduledTaskForUID loads one task when owned by uid.
func ListScheduledTasksForUID ¶ added in v0.94.0
func ListScheduledTasksForUID(ctx context.Context, uid types.Uid, states []string) ([]ScheduledTaskView, error)
ListScheduledTasksForUID returns scheduled tasks owned by uid.
func PatchScheduledTaskForUID ¶ added in v0.94.0
func PatchScheduledTaskForUID(ctx context.Context, uid types.Uid, taskID string, req UpdateScheduledTaskRequest) (*ScheduledTaskView, error)
PatchScheduledTaskForUID updates owned task fields from an HTTP request.
func SetScheduledTaskStateForUID ¶ added in v0.95.0
func SetScheduledTaskStateForUID(ctx context.Context, uid types.Uid, taskID string, state string) (*ScheduledTaskView, error)
SetScheduledTaskStateForUID sets the lifecycle state of one owned task.
type Service ¶
type Service struct{}
Service orchestrates chat assistant agent runs for direct chat sessions.
func NewService ¶
func NewService() *Service
NewService creates a chat agent service using current application config.
func (*Service) CompactSession ¶
func (*Service) CompactSession(ctx context.Context, sessionID string) (*ManualCompactionResult, error)
CompactSession force-compacts the current session branch without sending a user turn.
func (*Service) Run ¶
func (*Service) Run(ctx context.Context, req RunRequest, sink StreamSink) (string, error)
Run executes one agent turn and returns the assistant reply text.
func (*Service) RunAPI ¶
func (s *Service) RunAPI(ctx context.Context, req RunRequest, opts *APIRunOptions) error
RunAPI executes one agent turn for HTTP clients with SSE event publishing.
type SessionEventHub ¶
type SessionEventHub struct {
// contains filtered or unexported fields
}
SessionEventHub fans out stream events to multiple SSE subscribers for one session.
func GetSessionEventHub ¶
func GetSessionEventHub(sessionID string) *SessionEventHub
GetSessionEventHub returns the event hub for one session.
func (*SessionEventHub) Subscribe ¶
func (h *SessionEventHub) Subscribe(id string, buffer int) *ChannelPublisher
Subscribe registers one SSE consumer on the session hub.
func (*SessionEventHub) Unsubscribe ¶
func (h *SessionEventHub) Unsubscribe(id string)
Unsubscribe removes one SSE consumer from the session hub.
type SessionExport ¶
type SessionExport struct {
SessionID string `json:"session_id"`
UID string `json:"uid"`
LeafID string `json:"leaf_id"`
State string `json:"state"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ExportedAt time.Time `json:"exported_at"`
EntryCount int `json:"entry_count"`
Entries []map[string]any `json:"entries"`
}
SessionExport is the full session snapshot returned by the export API.
func ExportSession ¶
func ExportSession(ctx context.Context, sessionID string) (*SessionExport, error)
ExportSession loads session metadata and all persisted tree entries.
type SessionSummary ¶
type SessionSummary struct {
SessionID string `json:"session_id"`
Title string `json:"title"`
State string `json:"state"`
Mode string `json:"mode"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
SessionSummary is a lightweight view of one chat session for list APIs.
type Skill ¶
type Skill struct {
Name string
Description string
Location string
BaseDir string
Files []string
DisableModelInvocation bool
}
Skill is a prompt-visible agent skill loaded from storage.
func FilterSkillsByNames ¶ added in v0.94.0
FilterSkillsByNames returns enabled skills whose names appear in allowlist. An empty allowlist returns no skills.
type SkillContent ¶
SkillContent is the full skill body returned by read_skill.
func GetSkillContent ¶
func GetSkillContent(ctx context.Context, name string) (SkillContent, error)
GetSkillContent loads one enabled skill body by name.
func GetSkillFile ¶ added in v0.94.0
func GetSkillFile(ctx context.Context, name, filePath string) (SkillContent, error)
GetSkillFile loads one enabled skill auxiliary file by skill name and relative path.
type StreamEvent ¶
type StreamEvent struct {
Type string `json:"type"`
// delta / done / thinking
Text string `json:"text,omitempty"`
Title string `json:"title,omitempty"`
// tool
Name string `json:"name,omitempty"`
Subagent string `json:"subagent,omitempty"`
Status string `json:"status,omitempty"`
Stdout string `json:"stdout,omitempty"`
Stderr string `json:"stderr,omitempty"`
// tool / turn timing
DurationMs int64 `json:"duration_ms,omitempty"`
Step int `json:"step,omitempty"`
// usage
PromptTokens int `json:"prompt_tokens,omitempty"`
CompletionTokens int `json:"completion_tokens,omitempty"`
TotalTokens int `json:"total_tokens,omitempty"`
ContextPercent float64 `json:"context_percent,omitempty"`
ContextWindow int `json:"context_window,omitempty"`
// confirm / confirm_resolved
ID string `json:"id,omitempty"`
Tool string `json:"tool,omitempty"`
Summary string `json:"summary,omitempty"`
Permission string `json:"permission,omitempty"`
Pattern string `json:"pattern,omitempty"`
SuggestedPattern string `json:"suggested_pattern,omitempty"`
SuggestAlways bool `json:"suggest_always,omitempty"`
Approved bool `json:"approved,omitempty"`
Reason string `json:"reason,omitempty"`
Mode string `json:"mode,omitempty"`
Message string `json:"message,omitempty"`
// done
Resources []ResourceRef `json:"resources,omitempty"`
}
StreamEvent is one SSE payload emitted to Chat Agent HTTP clients.
type StreamSink ¶
type StreamSink interface {
// OnDelta delivers throttled snapshot text for in-progress updates.
OnDelta(ctx context.Context, text string) error
// Flush writes the final reply text to the platform message.
Flush(ctx context.Context, final string) error
}
StreamSink receives incremental assistant text during a streaming platform reply.
func NewSlackStreamSink ¶
func NewSlackStreamSink(caller *platforms.Caller, topic, messageID string) StreamSink
NewSlackStreamSink creates a sink that edits an existing Slack message.
type Subagent ¶
type Subagent struct {
Flag string
Name string
Description string
SystemPrompt string
Tools []string
Skills []string
Model string
}
Subagent is a prompt-visible subagent definition loaded from storage.
type SubagentInfo ¶
SubagentInfo describes one enabled subagent for the splash panel.
type TaskScheduler ¶ added in v0.94.0
type TaskScheduler struct {
// contains filtered or unexported fields
}
TaskScheduler registers chat scheduled tasks with cron and one-shot timers.
func GlobalScheduler ¶ added in v0.94.0
func GlobalScheduler() *TaskScheduler
GlobalScheduler returns the process-wide scheduler, if started.
func NewTaskScheduler ¶ added in v0.94.0
func NewTaskScheduler() *TaskScheduler
NewTaskScheduler creates a scheduler that uses wall-clock time.
func NewTaskSchedulerWithClock ¶ added in v0.94.0
func NewTaskSchedulerWithClock(now func() time.Time) *TaskScheduler
NewTaskSchedulerWithClock creates a scheduler with an injectable clock for tests.
func (*TaskScheduler) RegisterTask ¶ added in v0.94.0
func (s *TaskScheduler) RegisterTask(task *gen.ChatScheduledTask) error
RegisterTask schedules one active task.
func (*TaskScheduler) Start ¶ added in v0.94.0
func (s *TaskScheduler) Start(_ context.Context) error
Start loads active tasks from the database and begins scheduling.
func (*TaskScheduler) Stop ¶ added in v0.94.0
func (s *TaskScheduler) Stop(_ context.Context) error
Stop shuts down cron jobs and one-shot timers.
func (*TaskScheduler) UnregisterTask ¶ added in v0.94.0
func (s *TaskScheduler) UnregisterTask(taskID string)
UnregisterTask removes scheduling hooks for one task id.
func (*TaskScheduler) UpdateTask ¶ added in v0.94.0
func (s *TaskScheduler) UpdateTask(task *gen.ChatScheduledTask) error
UpdateTask re-registers a task after schedule changes under one lock.
type TaskTool ¶
type TaskTool struct {
// contains filtered or unexported fields
}
TaskTool delegates a self-contained task to an isolated subagent loop.
func NewTaskTool ¶
func NewTaskTool(ws coding.Workspace, deps TaskToolDeps) TaskTool
NewTaskTool creates a task tool bound to a workspace and per-run delegation metadata.
func (TaskTool) Description ¶
Description explains the tool to the model.
func (TaskTool) Execute ¶
func (t TaskTool) Execute(ctx context.Context, id string, args map[string]any, onUpdate tool.UpdateHandler) (msg.ToolResultMessage, error)
Execute resolves the subagent definition, runs it in isolation, and returns the final result.
func (TaskTool) Parameters ¶
Parameters returns the JSON schema for tool arguments.
type TaskToolDeps ¶
type TaskToolDeps struct {
// SessionID is the owning chat session, used to reuse permission gates.
SessionID string
// UID is the session owner, used to evaluate tool permissions in the subagent.
UID types.Uid
// Depth is the delegation depth of the caller (0 for the primary agent).
Depth int
// Kind is the parent run kind propagated to subagent permission hooks.
Kind RunKind
}
TaskToolDeps carries the per-run metadata needed to delegate to a subagent.
type ToolScopeInput ¶ added in v0.95.0
ToolScopeInput configures applyToolScope.
type UpdateMemoryTool ¶ added in v0.95.0
UpdateMemoryTool reads and writes persistent memory markdown files outside the workspace.
func NewUpdateMemoryTool ¶ added in v0.95.0
func NewUpdateMemoryTool() (UpdateMemoryTool, error)
NewUpdateMemoryTool builds a tool backed by the configured memory directory.
func (UpdateMemoryTool) Description ¶ added in v0.95.0
func (UpdateMemoryTool) Description() string
Description explains the tool to the model.
func (UpdateMemoryTool) Execute ¶ added in v0.95.0
func (t UpdateMemoryTool) Execute(ctx context.Context, id string, args map[string]any, _ tool.UpdateHandler) (msg.ToolResultMessage, error)
Execute runs one memory operation.
func (UpdateMemoryTool) Name ¶ added in v0.95.0
func (UpdateMemoryTool) Name() string
Name returns the tool identifier.
func (UpdateMemoryTool) Parameters ¶ added in v0.95.0
func (UpdateMemoryTool) Parameters() map[string]any
Parameters returns the JSON schema for tool arguments.
type UpdateScheduledTaskRequest ¶ added in v0.94.0
type UpdateScheduledTaskRequest struct {
Name *string `json:"name,omitempty"`
Prompt *string `json:"prompt,omitempty"`
Cron *string `json:"cron,omitempty"`
RunAt *string `json:"run_at,omitempty"`
State *string `json:"state,omitempty"`
}
UpdateScheduledTaskRequest carries HTTP PATCH fields.
type UpdateScheduledTaskTool ¶ added in v0.94.0
type UpdateScheduledTaskTool struct {
// contains filtered or unexported fields
}
UpdateScheduledTaskTool modifies cron, run_at, prompt, or name.
func (UpdateScheduledTaskTool) Description ¶ added in v0.94.0
func (UpdateScheduledTaskTool) Description() string
func (UpdateScheduledTaskTool) Execute ¶ added in v0.94.0
func (t UpdateScheduledTaskTool) Execute(ctx context.Context, id string, args map[string]any, _ tool.UpdateHandler) (msg.ToolResultMessage, error)
func (UpdateScheduledTaskTool) Name ¶ added in v0.94.0
func (UpdateScheduledTaskTool) Name() string
func (UpdateScheduledTaskTool) Parameters ¶ added in v0.94.0
func (UpdateScheduledTaskTool) Parameters() map[string]any
Source Files
¶
- ability_tools.go
- api_errors.go
- api_run.go
- api_stream.go
- confirm.go
- context_usage.go
- doc.go
- ephemeral_run.go
- event_sink.go
- event_stream.go
- export.go
- harness_pool.go
- history.go
- hooks.go
- info.go
- memory_scope.go
- memory_scope_resolve.go
- memory_tool.go
- mode.go
- models.go
- permission_api.go
- permission_session.go
- permission_store.go
- pipeline_run.go
- plans.go
- progress.go
- prompt_cache.go
- protocol.go
- registry.go
- resources.go
- run_control.go
- run_timeout.go
- schedule.go
- schedule_errors.go
- schedule_helpers.go
- schedule_tool.go
- scheduled_api.go
- scheduled_delivery.go
- scheduled_run.go
- scheduler.go
- sensors.go
- service.go
- session.go
- session_duration.go
- session_events.go
- sink.go
- skill_tool.go
- skills.go
- slack_sink.go
- storage.go
- stream_coalescer.go
- subagent_progress.go
- subagent_tasks.go
- subagent_tool.go
- subagents.go
- system_prompt.go
- testing_config_lock.go
- title.go
- tool_scope.go
- usage_record.go