delegation

package
v0.0.0-...-8155ea7 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: GPL-2.0, GPL-3.0 Imports: 14 Imported by: 0

Documentation

Overview

Package delegation implements the sub-agent delegation system with intercom. It enables non-blocking task delegation, role template reuse, and adaptive timeouts.

Index

Constants

View Source
const (
	// Task lifecycle
	TopicTaskQueued    = "task:queued"
	TopicTaskCompleted = "task:completed"
	TopicTaskFailed    = "task:failed"

	// Agent lifecycle
	TopicAgentCreated   = "agent:created"
	TopicAgentDismissed = "agent:dismissed"
	TopicAgentSuspended = "agent:suspended"
	TopicAgentRevived   = "agent:revived"

	// Memory events
	TopicMemoryUpdated      = "memory:updated"
	TopicMemoryConsolidated = "memory:consolidated"

	// Blackboard collaboration
	TopicBlackboardProposal = "blackboard:proposal"
	TopicBlackboardResolved = "blackboard:resolved"

	// Nudge/reminder events
	TopicNudgeScheduled  = "nudge:scheduled"
	TopicNudgeDelivered  = "nudge:delivered"
	TopicNudgeSuppressed = "nudge:suppressed"
)

Topic constants for intercom events

Variables

View Source
var (
	ErrQueueFull    = &QueueError{Message: "queue is full"}
	ErrQueueCleared = &QueueError{Message: "queue was cleared"}
)

Error definitions

Functions

func ExtractKeywords

func ExtractKeywords(task string) []string

ExtractKeywords extracts keywords from a task for template matching

func FormatTaskResultForLLM

func FormatTaskResultForLLM(record *BackgroundTaskRecord) string

FormatTaskResultForLLM formats a task result for LLM context injection

func FormatTaskResultForUser

func FormatTaskResultForUser(record *BackgroundTaskRecord) string

FormatTaskResultForUser formats a task result for user display

func GetDBPath

func GetDBPath(workspace string) string

GetDBPath returns the default database path for a workspace

Types

type BackgroundRunner

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

BackgroundRunner manages background task execution

func NewBackgroundRunner

func NewBackgroundRunner(
	store DelegationStore,
	lifecycle *LifecycleManager,
	timeoutEstimator *TimeoutEstimator,
	intercom *Intercom,
	config DelegationConfig,
) *BackgroundRunner

NewBackgroundRunner creates a new background runner

func (*BackgroundRunner) GetRunningCount

func (r *BackgroundRunner) GetRunningCount() int

GetRunningCount returns the number of currently running tasks

func (*BackgroundRunner) GetUndeliveredResults

func (r *BackgroundRunner) GetUndeliveredResults(ctx context.Context, userID string) ([]*BackgroundTaskRecord, error)

GetUndeliveredResults gets completed tasks that haven't been delivered

func (*BackgroundRunner) MarkDelivered

func (r *BackgroundRunner) MarkDelivered(ctx context.Context, taskID string) error

MarkDelivered marks a task result as delivered

func (*BackgroundRunner) SetExecutor

func (r *BackgroundRunner) SetExecutor(executor SubAgentExecutor)

SetExecutor sets the task executor

func (*BackgroundRunner) Stats

func (r *BackgroundRunner) Stats() map[string]any

Stats returns statistics about the background runner

func (*BackgroundRunner) Submit

func (r *BackgroundRunner) Submit(ctx context.Context, agent *SubAgentRecord, task string, category TaskCategory, rolePrompt string, tools []string, originChannel, originChatID string) (*BackgroundTaskRecord, error)

Submit submits a background task for execution

type BackgroundTaskRecord

type BackgroundTaskRecord struct {
	ID            string       `json:"id"`
	SubAgentID    string       `json:"sub_agent_id"`
	UserID        string       `json:"user_id"`
	Task          string       `json:"task"`
	Category      TaskCategory `json:"category"`
	Status        string       `json:"status"` // pending, running, completed, failed
	Result        string       `json:"result"`
	CreatedAt     int64        `json:"created_at"`
	CompletedAt   int64        `json:"completed_at"`
	Delivered     bool         `json:"delivered"`
	OriginChannel string       `json:"origin_channel"`
	OriginChatID  string       `json:"origin_chat_id"`
}

BackgroundTaskRecord represents a background task execution

type Blackboard

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

Blackboard implements a simple blackboard pattern for collaboration

func NewBlackboard

func NewBlackboard(maxEntries int) *Blackboard

NewBlackboard creates a new blackboard for collaboration

func (*Blackboard) Clear

func (b *Blackboard) Clear()

Clear removes all proposals

func (*Blackboard) GetAll

GetAll returns all proposals

func (*Blackboard) GetByAgent

func (b *Blackboard) GetByAgent(subAgentID string) []BlackboardProposalWithStatus

GetByAgent returns proposals from a specific agent

func (*Blackboard) GetResolved

func (b *Blackboard) GetResolved() []BlackboardProposalWithStatus

GetResolved returns all resolved proposals

func (*Blackboard) GetUnresolved

func (b *Blackboard) GetUnresolved() []BlackboardProposalWithStatus

GetUnresolved returns all unresolved proposals

func (*Blackboard) Post

func (b *Blackboard) Post(userID, subAgentID, proposal string)

Post adds a proposal to the blackboard. userID is the delegation partition (IntercomEvent.UserID); subAgentID identifies the proposing sub-agent.

func (*Blackboard) Resolve

func (b *Blackboard) Resolve(userID, subAgentID, resolution string)

Resolve marks a proposal as resolved.

func (*Blackboard) SetIntercom

func (b *Blackboard) SetIntercom(intercom *Intercom)

SetIntercom sets the intercom instance for emitting events

type BlackboardProposal

type BlackboardProposal struct {
	SubAgentID string    `json:"sub_agent_id"`
	Proposal   string    `json:"proposal"`
	Timestamp  time.Time `json:"timestamp"`
}

BlackboardProposal represents a proposal in the blackboard collaboration mode

type BlackboardProposalWithStatus

type BlackboardProposalWithStatus struct {
	BlackboardProposal
	Resolved   bool
	Resolution string
	ResolvedAt time.Time
}

BlackboardProposalWithStatus extends BlackboardProposal with resolution status

type ConfirmTaskTool

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

ConfirmTaskTool confirms and retrieves background task results

func NewConfirmTaskTool

func NewConfirmTaskTool(ds *DelegationSystem) *ConfirmTaskTool

NewConfirmTaskTool creates a new confirm_task tool

func (*ConfirmTaskTool) Description

func (t *ConfirmTaskTool) Description() string

func (*ConfirmTaskTool) Execute

func (t *ConfirmTaskTool) Execute(ctx context.Context, args map[string]any) *tools.ToolResult

func (*ConfirmTaskTool) Name

func (t *ConfirmTaskTool) Name() string

func (*ConfirmTaskTool) Parameters

func (t *ConfirmTaskTool) Parameters() map[string]any

type DelegateBackgroundTool

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

DelegateBackgroundTool delegates a task to run in the background

func NewDelegateBackgroundTool

func NewDelegateBackgroundTool(ds *DelegationSystem) *DelegateBackgroundTool

NewDelegateBackgroundTool creates a new delegate_background tool

func (*DelegateBackgroundTool) Description

func (t *DelegateBackgroundTool) Description() string

func (*DelegateBackgroundTool) Execute

func (t *DelegateBackgroundTool) Execute(ctx context.Context, args map[string]any) *tools.ToolResult

func (*DelegateBackgroundTool) Name

func (t *DelegateBackgroundTool) Name() string

func (*DelegateBackgroundTool) Parameters

func (t *DelegateBackgroundTool) Parameters() map[string]any

type DelegateTaskRequest

type DelegateTaskRequest struct {
	Task          string       `json:"task"`
	Label         string       `json:"label"`
	Category      TaskCategory `json:"category"`
	Tools         []string     `json:"tools"`
	RolePrompt    string       `json:"role_prompt"`
	Background    bool         `json:"background"`
	TimeoutHint   int          `json:"timeout_hint"` // seconds, 0 for auto
	ReuseExisting bool         `json:"reuse_existing"`
}

DelegateTaskRequest represents a task delegation request

type DelegateTaskResult

type DelegateTaskResult struct {
	SubAgentID   string `json:"sub_agent_id"`
	TaskID       string `json:"task_id"`
	Status       string `json:"status"`
	Message      string `json:"message"`
	Result       string `json:"result,omitempty"`
	IsBackground bool   `json:"is_background"`
}

DelegateTaskResult represents the result of task delegation

type DelegateTaskTool

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

DelegateTaskTool delegates a single task to a sub-agent

func NewDelegateTaskTool

func NewDelegateTaskTool(ds *DelegationSystem) *DelegateTaskTool

NewDelegateTaskTool creates a new delegate_task tool

func (*DelegateTaskTool) Description

func (t *DelegateTaskTool) Description() string

func (*DelegateTaskTool) Execute

func (t *DelegateTaskTool) Execute(ctx context.Context, args map[string]any) *tools.ToolResult

func (*DelegateTaskTool) Name

func (t *DelegateTaskTool) Name() string

func (*DelegateTaskTool) Parameters

func (t *DelegateTaskTool) Parameters() map[string]any

type DelegateTasksTool

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

DelegateTasksTool delegates multiple tasks in batch

func NewDelegateTasksTool

func NewDelegateTasksTool(ds *DelegationSystem) *DelegateTasksTool

NewDelegateTasksTool creates a new delegate_tasks tool

func (*DelegateTasksTool) Description

func (t *DelegateTasksTool) Description() string

func (*DelegateTasksTool) Execute

func (t *DelegateTasksTool) Execute(ctx context.Context, args map[string]any) *tools.ToolResult

func (*DelegateTasksTool) Name

func (t *DelegateTasksTool) Name() string

func (*DelegateTasksTool) Parameters

func (t *DelegateTasksTool) Parameters() map[string]any

type DelegateToExistingTool

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

DelegateToExistingTool sends a task to an existing sub-agent

func NewDelegateToExistingTool

func NewDelegateToExistingTool(ds *DelegationSystem) *DelegateToExistingTool

NewDelegateToExistingTool creates a new delegate_to_existing tool

func (*DelegateToExistingTool) Description

func (t *DelegateToExistingTool) Description() string

func (*DelegateToExistingTool) Execute

func (t *DelegateToExistingTool) Execute(ctx context.Context, args map[string]any) *tools.ToolResult

func (*DelegateToExistingTool) Name

func (t *DelegateToExistingTool) Name() string

func (*DelegateToExistingTool) Parameters

func (t *DelegateToExistingTool) Parameters() map[string]any

type DelegationConfig

type DelegationConfig struct {
	Enabled              bool     `json:"enabled"`
	DefaultSubAgentTools []string `json:"default_sub_agent_tools"`
	MaxActivePerUser     int      `json:"max_active_per_user"`
	MaxConcurrentTasks   int      `json:"max_concurrent_tasks"`
	RetentionDays        int      `json:"retention_days"`
	ReuseThreshold       float64  `json:"reuse_threshold"` // Keyword overlap threshold for reuse
}

DelegationConfig holds configuration for the delegation system

func DefaultDelegationConfig

func DefaultDelegationConfig() DelegationConfig

DefaultDelegationConfig returns the default configuration

type DelegationStore

type DelegationStore interface {
	// Sub-agent operations
	SaveSubAgent(ctx context.Context, agent *SubAgentRecord) error
	GetSubAgent(ctx context.Context, id string) (*SubAgentRecord, error)
	GetActiveSubAgents(ctx context.Context, userID string) ([]*SubAgentRecord, error)
	UpdateSubAgent(ctx context.Context, id string, updates map[string]any) error
	DeleteSubAgent(ctx context.Context, id string) error

	// Role template operations
	SaveRoleTemplate(ctx context.Context, template *RoleTemplate) error
	GetRoleTemplates(ctx context.Context, userID string) ([]*RoleTemplate, error)
	FindBestMatchTemplate(ctx context.Context, userID string, keywords []string, threshold float64) (*RoleTemplate, error)
	DeleteRoleTemplate(ctx context.Context, id string) error

	// Background task operations
	SaveBackgroundTask(ctx context.Context, task *BackgroundTaskRecord) error
	UpdateBackgroundTask(ctx context.Context, id string, updates map[string]any) error
	GetUndeliveredTasks(ctx context.Context, userID string) ([]*BackgroundTaskRecord, error)
	MarkTaskDelivered(ctx context.Context, id string) error

	// Task metrics operations
	SaveTaskMetric(ctx context.Context, metric *TaskMetricRecord) error
	GetTaskMetrics(ctx context.Context, userID string, category TaskCategory, limit int) ([]*TaskMetricRecord, error)

	// Sub-agent message operations
	SaveSubAgentMessage(ctx context.Context, msg *SubAgentMessage) error
	GetSubAgentMessages(ctx context.Context, subAgentID string, limit int) ([]*SubAgentMessage, error)

	// Maintenance
	CleanupOldData(ctx context.Context, retentionDays int) error
	Close() error
}

DelegationStore defines the interface for delegation persistence.

type DelegationSystem

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

DelegationSystem is the main facade for the delegation system

func NewDelegationSystem

func NewDelegationSystem(dbPath string, config DelegationConfig, provider providers.LLMProvider, model, workspace string) (*DelegationSystem, error)

NewDelegationSystem creates a new delegation system

func (*DelegationSystem) BlackboardPost

func (ds *DelegationSystem) BlackboardPost(userID, subAgentID, proposal string)

BlackboardPost records a proposal and emits blackboard:proposal when intercom is wired.

func (*DelegationSystem) BlackboardResolve

func (ds *DelegationSystem) BlackboardResolve(userID, subAgentID, resolution string)

BlackboardResolve resolves a proposal and emits blackboard:resolved.

func (*DelegationSystem) CleanupOldData

func (ds *DelegationSystem) CleanupOldData(ctx context.Context) error

CleanupOldData removes old data based on retention policy

func (*DelegationSystem) Close

func (ds *DelegationSystem) Close() error

Close closes the delegation system

func (*DelegationSystem) EmitMemoryConsolidated

func (ds *DelegationSystem) EmitMemoryConsolidated(ctx context.Context, userID string, data map[string]any)

EmitMemoryConsolidated emits a memory consolidated event

func (*DelegationSystem) EmitMemoryUpdated

func (ds *DelegationSystem) EmitMemoryUpdated(ctx context.Context, userID string, data map[string]any)

EmitMemoryUpdated emits a memory updated event

func (*DelegationSystem) EmitNudgeDelivered

func (ds *DelegationSystem) EmitNudgeDelivered(ctx context.Context, userID string, data map[string]any)

EmitNudgeDelivered emits a nudge delivered event

func (*DelegationSystem) EmitNudgeScheduled

func (ds *DelegationSystem) EmitNudgeScheduled(ctx context.Context, userID string, data map[string]any)

EmitNudgeScheduled emits a nudge scheduled event

func (*DelegationSystem) EmitNudgeSuppressed

func (ds *DelegationSystem) EmitNudgeSuppressed(ctx context.Context, userID string, data map[string]any)

EmitNudgeSuppressed emits a nudge suppressed event

func (*DelegationSystem) EmitTaskQueued

func (ds *DelegationSystem) EmitTaskQueued(ctx context.Context, userID, taskID string, data map[string]any)

EmitTaskQueued emits a task queued event

func (*DelegationSystem) GetUndeliveredResults

func (ds *DelegationSystem) GetUndeliveredResults(ctx context.Context, userID string) ([]*BackgroundTaskRecord, error)

GetUndeliveredResults gets undelivered background task results

func (*DelegationSystem) MarkDelivered

func (ds *DelegationSystem) MarkDelivered(ctx context.Context, taskID string) error

MarkDelivered marks a task as delivered

func (*DelegationSystem) OnAgentCreated

func (ds *DelegationSystem) OnAgentCreated(handler EventHandler) UnsubscribeFunc

OnAgentCreated subscribes to agent creation events

func (*DelegationSystem) OnAgentDismissed

func (ds *DelegationSystem) OnAgentDismissed(handler EventHandler) UnsubscribeFunc

OnAgentDismissed subscribes to agent dismissal events

func (*DelegationSystem) OnAgentRevived

func (ds *DelegationSystem) OnAgentRevived(handler EventHandler) UnsubscribeFunc

OnAgentRevived subscribes to agent revival events

func (*DelegationSystem) OnAgentSuspended

func (ds *DelegationSystem) OnAgentSuspended(handler EventHandler) UnsubscribeFunc

OnAgentSuspended subscribes to agent suspension events

func (*DelegationSystem) OnBlackboardProposal

func (ds *DelegationSystem) OnBlackboardProposal(handler EventHandler) UnsubscribeFunc

OnBlackboardProposal subscribes to blackboard proposal events

func (*DelegationSystem) OnBlackboardResolved

func (ds *DelegationSystem) OnBlackboardResolved(handler EventHandler) UnsubscribeFunc

OnBlackboardResolved subscribes to blackboard resolution events

func (*DelegationSystem) OnMemoryConsolidated

func (ds *DelegationSystem) OnMemoryConsolidated(handler EventHandler) UnsubscribeFunc

OnMemoryConsolidated subscribes to memory consolidation events

func (*DelegationSystem) OnMemoryUpdated

func (ds *DelegationSystem) OnMemoryUpdated(handler EventHandler) UnsubscribeFunc

OnMemoryUpdated subscribes to memory update events

func (*DelegationSystem) OnNudgeDelivered

func (ds *DelegationSystem) OnNudgeDelivered(handler EventHandler) UnsubscribeFunc

OnNudgeDelivered subscribes to nudge delivered events

func (*DelegationSystem) OnNudgeScheduled

func (ds *DelegationSystem) OnNudgeScheduled(handler EventHandler) UnsubscribeFunc

OnNudgeScheduled subscribes to nudge scheduled events

func (*DelegationSystem) OnNudgeSuppressed

func (ds *DelegationSystem) OnNudgeSuppressed(handler EventHandler) UnsubscribeFunc

OnNudgeSuppressed subscribes to nudge suppressed events

func (*DelegationSystem) OnTaskCompleted

func (ds *DelegationSystem) OnTaskCompleted(handler EventHandler) UnsubscribeFunc

OnTaskCompleted subscribes to task completion events

func (*DelegationSystem) OnTaskFailed

func (ds *DelegationSystem) OnTaskFailed(handler EventHandler) UnsubscribeFunc

OnTaskFailed subscribes to task failure events

func (*DelegationSystem) OnTaskQueued

func (ds *DelegationSystem) OnTaskQueued(handler EventHandler) UnsubscribeFunc

OnTaskQueued subscribes to task queued events

func (*DelegationSystem) RegisterTools

func (ds *DelegationSystem) RegisterTools(registry *tools.ToolRegistry)

RegisterTools registers all delegation tools to the tool registry

func (*DelegationSystem) Stats

func (ds *DelegationSystem) Stats() map[string]any

Stats returns statistics about the delegation system

type EventHandler

type EventHandler func(ctx context.Context, event IntercomEvent)

EventHandler is a function that handles an intercom event

type Intercom

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

Intercom is a pub/sub event system for delegation communication

func NewIntercom

func NewIntercom(maxRecentEvents int) *Intercom

NewIntercom creates a new intercom event system

func (*Intercom) Clear

func (i *Intercom) Clear()

Clear removes all handlers and recent events

func (*Intercom) Emit

func (i *Intercom) Emit(ctx context.Context, topic, userID string, data map[string]any)

Emit publishes an event to all subscribers

func (*Intercom) On

func (i *Intercom) On(topic string, handler EventHandler) UnsubscribeFunc

On subscribes to events on a specific topic Returns an unsubscribe function

func (*Intercom) OnAny

func (i *Intercom) OnAny(handler EventHandler) UnsubscribeFunc

OnAny subscribes to all events Returns an unsubscribe function

func (*Intercom) Recent

func (i *Intercom) Recent(topic string, limit int) []IntercomEvent

Recent returns the most recent events for a topic

func (*Intercom) RecentAll

func (i *Intercom) RecentAll(limit int) []IntercomEvent

RecentAll returns recent events across all topics

func (*Intercom) Stats

func (i *Intercom) Stats() map[string]any

Stats returns statistics about the intercom

type IntercomEvent

type IntercomEvent struct {
	Topic     string         `json:"topic"`
	UserID    string         `json:"user_id"`
	Data      map[string]any `json:"data"`
	Timestamp int64          `json:"timestamp"`
}

IntercomEvent represents an event in the intercom system

type LLMExecutor

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

LLMExecutor executes tasks using the LLM

func NewLLMExecutor

func NewLLMExecutor(
	store DelegationStore,
	provider providers.LLMProvider,
	model string,
	workspace string,
	defaultTools []string,
) *LLMExecutor

NewLLMExecutor creates a new LLM executor

func (*LLMExecutor) Execute

func (e *LLMExecutor) Execute(ctx context.Context, sessionKey, rolePrompt, task string, toolNames []string) (string, error)

Execute executes a task with the given role prompt

type LifecycleManager

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

LifecycleManager manages the lifecycle of sub-agents

func NewLifecycleManager

func NewLifecycleManager(store DelegationStore, config DelegationConfig, intercom *Intercom) *LifecycleManager

NewLifecycleManager creates a new lifecycle manager

func (*LifecycleManager) CleanupOldData

func (m *LifecycleManager) CleanupOldData(ctx context.Context) error

CleanupOldData removes old data based on retention policy

func (*LifecycleManager) Create

func (m *LifecycleManager) Create(ctx context.Context, userID, label, rolePrompt string, keywords, tools []string) (*SubAgentRecord, error)

Create creates a new sub-agent

func (*LifecycleManager) Dismiss

func (m *LifecycleManager) Dismiss(ctx context.Context, id string) error

Dismiss dismisses a sub-agent (cannot be revived)

func (*LifecycleManager) FindReusable

func (m *LifecycleManager) FindReusable(ctx context.Context, userID string, keywords []string) (*SubAgentRecord, error)

FindReusable finds a sub-agent that can be reused for the given keywords

func (*LifecycleManager) Get

Get retrieves a sub-agent by ID

func (*LifecycleManager) GetMessages

func (m *LifecycleManager) GetMessages(ctx context.Context, subAgentID string, limit int) ([]*SubAgentMessage, error)

GetMessages retrieves messages for a sub-agent

func (*LifecycleManager) GetSummary

func (m *LifecycleManager) GetSummary(agent *SubAgentRecord) SubAgentSummary

GetSummary creates a summary of a sub-agent

func (*LifecycleManager) Kill

func (m *LifecycleManager) Kill(ctx context.Context, id string) error

Kill immediately kills a sub-agent and removes it

func (*LifecycleManager) ListActive

func (m *LifecycleManager) ListActive(ctx context.Context, userID string) ([]*SubAgentRecord, error)

ListActive lists all active sub-agents for a user

func (*LifecycleManager) RecordTaskResult

func (m *LifecycleManager) RecordTaskResult(ctx context.Context, id string, success bool, durationMs int64) error

RecordTaskResult records the result of a task execution

func (*LifecycleManager) Revive

func (m *LifecycleManager) Revive(ctx context.Context, id string) error

Revive revives a suspended sub-agent

func (*LifecycleManager) SaveMessage

func (m *LifecycleManager) SaveMessage(ctx context.Context, subAgentID, role, content string) error

SaveMessage saves a message to a sub-agent's history

func (*LifecycleManager) Suspend

func (m *LifecycleManager) Suspend(ctx context.Context, id string) error

Suspend suspends a sub-agent (can be revived later)

type ListSubAgentsTool

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

ListSubAgentsTool lists all sub-agents for the user

func NewListSubAgentsTool

func NewListSubAgentsTool(ds *DelegationSystem) *ListSubAgentsTool

NewListSubAgentsTool creates a new list_sub_agents tool

func (*ListSubAgentsTool) Description

func (t *ListSubAgentsTool) Description() string

func (*ListSubAgentsTool) Execute

func (t *ListSubAgentsTool) Execute(ctx context.Context, args map[string]any) *tools.ToolResult

func (*ListSubAgentsTool) Name

func (t *ListSubAgentsTool) Name() string

func (*ListSubAgentsTool) Parameters

func (t *ListSubAgentsTool) Parameters() map[string]any

type ManageSubAgentTool

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

ManageSubAgentTool manages sub-agent lifecycle

func NewManageSubAgentTool

func NewManageSubAgentTool(ds *DelegationSystem) *ManageSubAgentTool

NewManageSubAgentTool creates a new manage_sub_agent tool

func (*ManageSubAgentTool) Description

func (t *ManageSubAgentTool) Description() string

func (*ManageSubAgentTool) Execute

func (t *ManageSubAgentTool) Execute(ctx context.Context, args map[string]any) *tools.ToolResult

func (*ManageSubAgentTool) Name

func (t *ManageSubAgentTool) Name() string

func (*ManageSubAgentTool) Parameters

func (t *ManageSubAgentTool) Parameters() map[string]any

type ManageTemplateTool

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

ManageTemplateTool manages role templates

func NewManageTemplateTool

func NewManageTemplateTool(ds *DelegationSystem) *ManageTemplateTool

NewManageTemplateTool creates a new manage_template tool

func (*ManageTemplateTool) Description

func (t *ManageTemplateTool) Description() string

func (*ManageTemplateTool) Execute

func (t *ManageTemplateTool) Execute(ctx context.Context, args map[string]any) *tools.ToolResult

func (*ManageTemplateTool) Name

func (t *ManageTemplateTool) Name() string

func (*ManageTemplateTool) Parameters

func (t *ManageTemplateTool) Parameters() map[string]any

type OrientationContext

type OrientationContext struct {
	SessionSummary  string   `json:"session_summary"`
	RecentTasks     []string `json:"recent_tasks"`
	UserPreferences []string `json:"user_preferences"`
}

OrientationContext provides context for sub-agent orientation

type PrioritySessionQueue

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

PrioritySessionQueue extends SessionQueue with priority support

func NewPrioritySessionQueue

func NewPrioritySessionQueue() *PrioritySessionQueue

NewPrioritySessionQueue creates a new priority session queue

func (*PrioritySessionQueue) Submit

func (q *PrioritySessionQueue) Submit(ctx context.Context, agentID string, taskID string, task func(ctx context.Context) error) <-chan error

Submit submits a task with normal priority

func (*PrioritySessionQueue) SubmitWithPriority

func (q *PrioritySessionQueue) SubmitWithPriority(ctx context.Context, agentID string, taskID string, task func(ctx context.Context) error, highPriority bool) <-chan error

SubmitWithPriority submits a task with specified priority

type QueueError

type QueueError struct {
	Message string
}

QueueError represents a queue error

func (*QueueError) Error

func (e *QueueError) Error() string

type RoleTemplate

type RoleTemplate struct {
	ID            string       `json:"id"`
	UserID        string       `json:"user_id"`
	Name          string       `json:"name"`
	RolePrompt    string       `json:"role_prompt"`
	TaskKeywords  []string     `json:"task_keywords"`
	Tools         []string     `json:"tools"`
	Category      TaskCategory `json:"category"`
	SuccessCount  int          `json:"success_count"`
	FailureCount  int          `json:"failure_count"`
	AvgDurationMs int64        `json:"avg_duration_ms"`
	CreatedAt     int64        `json:"created_at"`
	LastUsedAt    int64        `json:"last_used_at"`
}

RoleTemplate represents a reusable role configuration

type SQLiteStore

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

SQLiteStore implements DelegationStore using SQLite

func NewSQLiteStore

func NewSQLiteStore(dbPath string) (*SQLiteStore, error)

NewSQLiteStore creates a new SQLite delegation store

func (*SQLiteStore) CleanupOldData

func (s *SQLiteStore) CleanupOldData(ctx context.Context, retentionDays int) error

CleanupOldData removes old records based on retention period

func (*SQLiteStore) Close

func (s *SQLiteStore) Close() error

Close closes the database connection

func (*SQLiteStore) DeleteRoleTemplate

func (s *SQLiteStore) DeleteRoleTemplate(ctx context.Context, id string) error

DeleteRoleTemplate deletes a role template

func (*SQLiteStore) DeleteSubAgent

func (s *SQLiteStore) DeleteSubAgent(ctx context.Context, id string) error

DeleteSubAgent deletes a sub-agent

func (*SQLiteStore) FindBestMatchTemplate

func (s *SQLiteStore) FindBestMatchTemplate(ctx context.Context, userID string, keywords []string, threshold float64) (*RoleTemplate, error)

FindBestMatchTemplate finds the best matching template based on keyword overlap

func (*SQLiteStore) GetActiveSubAgents

func (s *SQLiteStore) GetActiveSubAgents(ctx context.Context, userID string) ([]*SubAgentRecord, error)

GetActiveSubAgents retrieves all active sub-agents for a user.

func (*SQLiteStore) GetRoleTemplates

func (s *SQLiteStore) GetRoleTemplates(ctx context.Context, userID string) ([]*RoleTemplate, error)

GetRoleTemplates retrieves all role templates for a user.

func (*SQLiteStore) GetSubAgent

func (s *SQLiteStore) GetSubAgent(ctx context.Context, id string) (*SubAgentRecord, error)

GetSubAgent retrieves a sub-agent by ID

func (*SQLiteStore) GetSubAgentMessages

func (s *SQLiteStore) GetSubAgentMessages(ctx context.Context, subAgentID string, limit int) ([]*SubAgentMessage, error)

GetSubAgentMessages retrieves messages for a sub-agent

func (*SQLiteStore) GetTaskMetrics

func (s *SQLiteStore) GetTaskMetrics(ctx context.Context, userID string, category TaskCategory, limit int) ([]*TaskMetricRecord, error)

GetTaskMetrics retrieves recent task metrics for a user and category

func (*SQLiteStore) GetUndeliveredTasks

func (s *SQLiteStore) GetUndeliveredTasks(ctx context.Context, userID string) ([]*BackgroundTaskRecord, error)

GetUndeliveredTasks retrieves all undelivered completed tasks for a user

func (*SQLiteStore) MarkTaskDelivered

func (s *SQLiteStore) MarkTaskDelivered(ctx context.Context, id string) error

MarkTaskDelivered marks a task as delivered

func (*SQLiteStore) SaveBackgroundTask

func (s *SQLiteStore) SaveBackgroundTask(ctx context.Context, task *BackgroundTaskRecord) error

SaveBackgroundTask saves a background task

func (*SQLiteStore) SaveRoleTemplate

func (s *SQLiteStore) SaveRoleTemplate(ctx context.Context, template *RoleTemplate) error

SaveRoleTemplate saves a role template

func (*SQLiteStore) SaveSubAgent

func (s *SQLiteStore) SaveSubAgent(ctx context.Context, agent *SubAgentRecord) error

SaveSubAgent saves a sub-agent record

func (*SQLiteStore) SaveSubAgentMessage

func (s *SQLiteStore) SaveSubAgentMessage(ctx context.Context, msg *SubAgentMessage) error

SaveSubAgentMessage saves a message to a sub-agent's history

func (*SQLiteStore) SaveTaskMetric

func (s *SQLiteStore) SaveTaskMetric(ctx context.Context, metric *TaskMetricRecord) error

SaveTaskMetric saves a task metric

func (*SQLiteStore) UpdateBackgroundTask

func (s *SQLiteStore) UpdateBackgroundTask(ctx context.Context, id string, updates map[string]any) error

UpdateBackgroundTask updates specific fields of a background task

func (*SQLiteStore) UpdateSubAgent

func (s *SQLiteStore) UpdateSubAgent(ctx context.Context, id string, updates map[string]any) error

UpdateSubAgent updates specific fields of a sub-agent

type SessionQueue

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

SessionQueue manages per-agent serial execution of tasks

func NewSessionQueue

func NewSessionQueue() *SessionQueue

NewSessionQueue creates a new session queue

func (*SessionQueue) Clear

func (q *SessionQueue) Clear()

Clear clears all queues

func (*SessionQueue) GetActiveAgents

func (q *SessionQueue) GetActiveAgents() int

GetActiveAgents returns the number of agents with active queues

func (*SessionQueue) GetQueueLength

func (q *SessionQueue) GetQueueLength(agentID string) int

GetQueueLength returns the number of pending tasks for an agent

func (*SessionQueue) GetTotalQueueLength

func (q *SessionQueue) GetTotalQueueLength() int

GetTotalQueueLength returns total pending tasks across all agents

func (*SessionQueue) Stats

func (q *SessionQueue) Stats() map[string]any

Stats returns statistics about the session queue

func (*SessionQueue) Submit

func (q *SessionQueue) Submit(ctx context.Context, agentID string, taskID string, task func(ctx context.Context) error) <-chan error

Submit submits a task to an agent's queue Tasks for the same agent are executed serially Returns a channel that receives the error when complete

type SimpleSubAgentExecutor

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

SimpleSubAgentExecutor is a basic implementation of SubAgentExecutor

func NewSimpleSubAgentExecutor

func NewSimpleSubAgentExecutor(provider providers.LLMProvider, model string) *SimpleSubAgentExecutor

NewSimpleSubAgentExecutor creates a simple executor using the LLM provider

func (*SimpleSubAgentExecutor) Execute

func (e *SimpleSubAgentExecutor) Execute(ctx context.Context, sessionKey, rolePrompt, task string, tools []string) (string, error)

Execute executes a task using the LLM

type SubAgentExecutor

type SubAgentExecutor interface {
	Execute(ctx context.Context, sessionKey, rolePrompt, task string, tools []string) (string, error)
}

SubAgentExecutor defines the interface for executing sub-agent tasks

type SubAgentMessage

type SubAgentMessage struct {
	ID         string `json:"id"`
	SubAgentID string `json:"sub_agent_id"`
	Role       string `json:"role"`
	Content    string `json:"content"`
	CreatedAt  int64  `json:"created_at"`
}

SubAgentMessage represents a message in a sub-agent's history

type SubAgentRecord

type SubAgentRecord struct {
	ID             string         `json:"id"`
	UserID         string         `json:"user_id"`
	Label          string         `json:"label"`
	RolePrompt     string         `json:"role_prompt"`
	TaskKeywords   []string       `json:"task_keywords"`
	Tools          []string       `json:"tools"`
	Status         SubAgentStatus `json:"status"`
	CreatedAt      int64          `json:"created_at"`
	LastActiveAt   int64          `json:"last_active_at"`
	CompletedTasks int            `json:"completed_tasks"`
	SuccessRate    float64        `json:"success_rate"`
	SessionKey     string         `json:"session_key"`
}

SubAgentRecord represents a persistent sub-agent instance

type SubAgentStatus

type SubAgentStatus string

SubAgentStatus represents the current state of a sub-agent

const (
	StatusActive    SubAgentStatus = "active"
	StatusSuspended SubAgentStatus = "suspended"
	StatusDismissed SubAgentStatus = "dismissed"
)

type SubAgentSummary

type SubAgentSummary struct {
	ID             string         `json:"id"`
	Label          string         `json:"label"`
	Status         SubAgentStatus `json:"status"`
	CompletedTasks int            `json:"completed_tasks"`
	SuccessRate    float64        `json:"success_rate"`
	LastActiveAt   int64          `json:"last_active_at"`
	CreatedAt      int64          `json:"created_at"`
}

SubAgentSummary represents a summary of a sub-agent for listing

type TaskCategory

type TaskCategory string

TaskCategory represents the type of task for timeout estimation

const (
	CategoryResearch TaskCategory = "research"
	CategoryCode     TaskCategory = "code"
	CategoryAnalysis TaskCategory = "analysis"
	CategoryWriting  TaskCategory = "writing"
	CategoryGeneral  TaskCategory = "general"
	CategoryCustom   TaskCategory = "custom"
)

func ClassifyTask

func ClassifyTask(task string) TaskCategory

ClassifyTask determines the category of a task based on its content

type TaskMetricRecord

type TaskMetricRecord struct {
	ID           string       `json:"id"`
	UserID       string       `json:"user_id"`
	TaskCategory TaskCategory `json:"task_category"`
	TaskHint     string       `json:"task_hint"` // First 100 chars of task
	DurationMs   int64        `json:"duration_ms"`
	Success      bool         `json:"success"`
	CreatedAt    int64        `json:"created_at"`
}

TaskMetricRecord represents timing metrics for adaptive timeouts

type TemplateManager

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

TemplateManager manages role templates for sub-agents

func NewTemplateManager

func NewTemplateManager(store DelegationStore, defaultTools []string) *TemplateManager

NewTemplateManager creates a new template manager

func (*TemplateManager) DeleteTemplate

func (m *TemplateManager) DeleteTemplate(ctx context.Context, templateID string) error

DeleteTemplate deletes a template

func (*TemplateManager) FindOrCreate

func (m *TemplateManager) FindOrCreate(ctx context.Context, userID string, task string, customPrompt string, customTools []string) (*RoleTemplate, bool, error)

FindOrCreate finds a matching template or creates a new sub-agent config

func (*TemplateManager) GetTemplateStats

func (m *TemplateManager) GetTemplateStats(ctx context.Context, userID string) (map[string]any, error)

GetTemplateStats returns statistics about templates

func (*TemplateManager) ListTemplates

func (m *TemplateManager) ListTemplates(ctx context.Context, userID string) ([]*RoleTemplate, error)

ListTemplates lists all templates for a user

func (*TemplateManager) RecordFailure

func (m *TemplateManager) RecordFailure(ctx context.Context, templateID string) error

RecordFailure records a failed task for a template

func (*TemplateManager) RecordSuccess

func (m *TemplateManager) RecordSuccess(ctx context.Context, templateID string, durationMs int64) error

RecordSuccess records a successful task completion for a template

func (*TemplateManager) SaveTemplate

func (m *TemplateManager) SaveTemplate(ctx context.Context, template *RoleTemplate) error

SaveTemplate saves a template after successful task completion

type TimeoutEstimate

type TimeoutEstimate struct {
	Duration   time.Duration `json:"duration"`
	Category   TaskCategory  `json:"category"`
	Confidence float64       `json:"confidence"` // 0-1, based on sample size
}

TimeoutEstimate represents an estimated timeout for a task

type TimeoutEstimator

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

TimeoutEstimator provides adaptive timeout estimation based on historical data

func NewTimeoutEstimator

func NewTimeoutEstimator(store DelegationStore) *TimeoutEstimator

NewTimeoutEstimator creates a new timeout estimator

func (*TimeoutEstimator) Estimate

func (e *TimeoutEstimator) Estimate(ctx context.Context, userID string, task string, category TaskCategory) TimeoutEstimate

Estimate calculates an appropriate timeout for a task

func (*TimeoutEstimator) EstimateWithHint

func (e *TimeoutEstimator) EstimateWithHint(ctx context.Context, userID, task string, category TaskCategory, hintSeconds int) TimeoutEstimate

EstimateWithHint estimates timeout considering a user-provided hint

func (*TimeoutEstimator) RecordMetric

func (e *TimeoutEstimator) RecordMetric(ctx context.Context, userID string, task string, duration time.Duration, success bool) error

RecordMetric records a task execution metric for future estimates

func (*TimeoutEstimator) SetDefaultTimeout

func (e *TimeoutEstimator) SetDefaultTimeout(category TaskCategory, duration time.Duration)

SetDefaultTimeout sets the default timeout for a category

func (*TimeoutEstimator) SetLimits

func (e *TimeoutEstimator) SetLimits(min, max time.Duration)

SetLimits sets the min and max timeout limits

type UnsubscribeFunc

type UnsubscribeFunc func()

UnsubscribeFunc is returned when subscribing to events

Jump to

Keyboard shortcuts

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