diff --git a/agent/autonomous/DESIGN.md b/agent/autonomous/DESIGN.md
index 7c4569cb..c41d61eb 100644
--- a/agent/autonomous/DESIGN.md
+++ b/agent/autonomous/DESIGN.md
@@ -1,1273 +1,353 @@
# Autonomous Agent Design Document
-## Overview
+## 1. Overview
-An Autonomous Agent is an **AI member** within a team, belonging to a Team just like human members. From the user's perspective, it's simply a team member with clearly defined job responsibilities (such as Sales Manager, Data Analyst, Customer Service Representative, etc.). It can operate independently, make autonomous decisions, and execute tasks. Unlike Assistants that passively respond to user requests, Autonomous Agents are proactive, capable of running periodically based on job responsibilities and rules to complete complex multi-step tasks.
+An **Autonomous Agent** is an AI team member that operates independently, makes decisions, and executes tasks proactively. Unlike Assistants that respond to user requests, Autonomous Agents run periodically based on job responsibilities.
-**Core Features:**
+**Key Characteristics:**
-- **Team Member**: From the user's perspective, it's an AI member managed like human members
-- **Job Responsibilities**: Each AI member has clearly defined duties and knows what to do
-- **Dynamic Lifecycle**: Dynamically created/destroyed based on team needs
-- **Autonomous Operation**: Triggered by the World Clock, periodically executing job responsibilities
+- **Team Member**: Managed like human members, belongs to a Team
+- **Job Responsibilities**: Has defined duties (e.g., "Sales Manager tracks KPIs")
+- **Dynamic Lifecycle**: Created/destroyed via Team API
+- **Multi-Trigger**: Activated by schedule, human intervention, or events
+- **Self-Learning**: Maintains private knowledge base, learns from execution
-## Relationship with Team
+---
-From the user's perspective, an Autonomous Agent is an **AI member** within the team. Each AI member has clearly defined job responsibilities, and a Team can have multiple AI members.
+## 2. Architecture
+
+### 2.1 System Overview
+
+```mermaid
+flowchart TB
+ subgraph Triggers["Trigger Sources"]
+ WC[/"β° World Clock
(Schedule)"/]
+ HI[/"π€ Human
(Intervene)"/]
+ EV[/"π‘ Events
(Webhook/DB)"/]
+ end
+
+ subgraph Manager["Agent Manager"]
+ TC{"Trigger
Enabled?"}
+ Cache[("Agent Cache")]
+ Dedup{"Dedup
Check"}
+ Queue["Priority Queue"]
+ end
+
+ subgraph Pool["Worker Pool"]
+ W1["Worker"]
+ W2["Worker"]
+ W3["Worker"]
+ end
+
+ subgraph Executor["Executor"]
+ P0["P0: Inspiration"]
+ P1["P1: Goals"]
+ P2["P2: Tasks"]
+ P3["P3: Execute"]
+ P4["P4: Deliver"]
+ P5["P5: Learn"]
+ end
+
+ subgraph Storage["Storage"]
+ KB[("Private KB")]
+ DB[("Executions")]
+ Job[("Job System")]
+ end
+
+ WC & HI & EV --> TC
+ TC -->|Yes| Cache
+ TC -->|No| X[/Ignored/]
+ Cache --> Dedup
+ Dedup -->|Pass| Queue
+ Dedup -->|Skip| Cache
+ Queue --> W1 & W2 & W3
+ W1 & W2 & W3 --> P0
+ P0 --> P1 --> P2 --> P3 --> P4 --> P5
+ P5 --> KB & DB & Job
+ KB -.->|Experience| P0
+```
+
+### 2.2 Team Integration
+
+AI members are stored in `team_members` table with `member_type = "ai"`:
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Team β
-β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β AI Members β β
+β β AI Members β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β βSales Managerβ βData Analyst β βCS Specialistβ β β
-β β β (AI Member) β β (AI Member) β β (AI Member) β β β
-β β β β β β β β β β
β β β Duties: β β Duties: β β Duties: β β β
-β β β β’ Track KPIsβ β β’ Analyze β β β’ Handle β β β
-β β β β’ Generate β β data β β tickets β β β
-β β β reports β β β’ Generate β β β’ Reply to β β β
-β β β β β reports β β inquiries β β β
+β β β β’ Track KPIsβ β β’ Analyze β β β’ Tickets β β β
+β β β β’ Reports β β β’ Reports β β β’ Inquiries β β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Human Members β β
+β β Human Members β β
β β βββββββββββββββ βββββββββββββββ β β
-β β β John β β Jane β β β
-β β β (Owner) β β (Admin) β β β
+β β β John (Owner)β β Jane (Admin)β β β
β β βββββββββββββββ βββββββββββββββ β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
-### Team Member Table Extension
-
-AI members reuse the `team_members` table, distinguished by `member_type`:
-
```sql
--- team_members table
CREATE TABLE team_members (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
team_id VARCHAR(64) NOT NULL,
- user_id VARCHAR(64), -- user_id for human members
+ user_id VARCHAR(64), -- Human members
member_type VARCHAR(32) NOT NULL, -- "user" | "ai"
- role_id VARCHAR(64),
-
- -- AI member specific fields
- agent_id VARCHAR(64), -- Autonomous Agent ID (AI members only)
- agent_config JSON, -- Agent configuration (identity, resources, delivery, etc.)
-
- is_owner BOOLEAN DEFAULT FALSE,
+ agent_id VARCHAR(64), -- AI members only
+ agent_config JSON, -- AI config
status VARCHAR(32) DEFAULT 'active',
- joined_at DATETIME,
- created_at DATETIME,
- updated_at DATETIME,
-
INDEX idx_team_id (team_id),
- INDEX idx_member_type (member_type),
INDEX idx_agent_id (agent_id)
);
```
-## System Architecture
+---
-```
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β World Clock β
-β (Global timer, e.g., every minute) β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β Tick
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Autonomous Agent Manager β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β β’ Get active AI members from memory cache β β
-β β (loaded at startup, refreshed on changes) β β
-β β β’ Check scheduling conditions β β
-β β β’ Execution-level deduplication (prevent duplicate β β
-β β submissions) β β
-β β β’ Dispatch execution requests to eligible members β β
-β β β’ Monitor execution status, handle failures and retries β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Team A β
-β βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ β
-β β AI: Sales Mgr β β AI: Analyst β β AI: Editor β β
-β β (sales-manager) β β (data-analyst) β β (content-editor)β β
-β β β β β β β β
-β β Duties: β β Duties: β β Duties: β β
-β β β’ Track sales β β β’ Analyze data β β β’ Generate β β
-β β performance β β β’ Generate β β marketing β β
-β β β’ Generate β β analysis β β content β β
-β β sales reports β β reports β β β’ Maintain KB β β
-β βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ β
-β β
-β βββββββββββββββββββ βββββββββββββββββββ β
-β β Human: John β β Human: Jane β β
-β β (owner) β β (admin) β β
-β βββββββββββββββββββ βββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-```
+## 3. How It Works
-## Core Design Philosophy
-
-### 1. AI Member = Team Member with Job Responsibilities
-
-Each Autonomous Agent is simply an **AI member** to the user, but internally has clearly defined job responsibilities:
-
-- **Job Responsibilities**: Clearly knows what to do (e.g., "Sales Manager tracks performance and generates reports")
-- **Resource Permissions**: Accessible resources and callable tools are defined by configuration
-- **Private Knowledge Base**: Dedicated KB for accumulating work experience and expertise
-- **Goal-Driven**: Autonomously generates work goals based on job responsibilities
-- **Task Execution**: Breaks down goals into specific tasks, calls Assistants/MCP Tools to execute
-- **Result Delivery**: Generates deliverables (reports, emails, notifications, etc.)
-- **Continuous Learning**: Learns from execution to continuously improve capabilities
-
-### 2. Multi-Trigger Source Concurrent Execution
-
-The same AI member can be triggered in multiple ways, supporting concurrent execution:
-
-- **World Clock**: Scheduled triggers (cron/interval)
-- **Human Intervention**: Manually add tasks, adjust goals
-- **Event Triggers**: webhooks, database changes, etc.
-
-> **Note**: Agent-to-agent collaboration (one Agent calling another Agent) is implemented at the Assistant layer, not part of the scheduling layer's responsibility.
-
-### 3. Concurrency Control and Resource Quotas
-
-To prevent resources from being monopolized by a single member, the system implements two-level control:
-
-```
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Global Worker Pool β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Total Workers: 10 (configurable) β β
-β β Currently Used: 6 β β
-β β Queued Tasks: 3 β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βββββββββββββββββββββΌββββββββββββββββββββ
- βΌ βΌ βΌ
-βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
-β Sales Manager β β Data Analyst β β CS Specialist β
-β Quota: 3 β β Quota: 2 β β Quota: 3 β
-β Current: 2 β β β Current: 2(full)β β Current: 2 β β
-β Queued: 1 β β Queued: 2 β β Queued: 0 β
-βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
-```
-
-**Two-Level Control:**
-
-1. **Global Worker Pool**: Limits total system concurrency, shared by all members
-2. **Member Quota**: Maximum concurrent executions per member, prevents single member from monopolizing resources
-
-### 4. Member Cache (Avoiding Frequent DB Queries)
-
-Manager loads all active members into memory at startup, refreshes via events:
-
-```go
-// AgentCache member cache
-type AgentCache struct {
- agents map[string]*AutonomousAgent // agent_id -> agent
- byTeam map[string][]string // team_id -> []agent_id
- mutex sync.RWMutex
- lastLoad time.Time
-}
-
-// Cache refresh timing
-// 1. Full load at Manager startup
-// 2. Incremental refresh on member create/update/delete (via event notification)
-// 3. Periodic full refresh (e.g., hourly, as fallback)
-
-func (c *AgentCache) Refresh(agentID string) {
- // Load single member from database, update cache
-}
-
-func (c *AgentCache) RefreshAll() {
- // Full refresh
-}
-
-func (c *AgentCache) GetActive() []*AutonomousAgent {
- // Return all active members (from memory, no database query)
-}
-```
-
-### 5. Deduplication
-
-Uses **Agent semantic understanding** for deduplication, determining duplicates based on historical task data:
-
-```
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Deduplication Service β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Core idea: Let Agent determine "has this task been done β β
-β β before" β β
-β β β β
-β β Input: β β
-β β β’ Goal/task to be evaluated β β
-β β β’ Historical execution records (retrieved from DB) β β
-β β β β
-β β Output: β β
-β β β’ is_duplicate: whether it's a duplicate β β
-β β β’ reason: reasoning for the judgment β β
-β β β’ similar_task_id: ID of similar historical task β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-```
-
-**Deduplication Approach:**
-
-```go
-// DeduplicationService deduplication service
-type DeduplicationService struct {
- dedupAgent string // Dedup Agent ID (e.g., __yao.dedup-checker)
-}
-
-// DedupRequest deduplication request
-type DedupRequest struct {
- AgentID string `json:"agent_id"`
- Type string `json:"type"` // goal | task
- Content string `json:"content"` // goal/task description
- Context interface{} `json:"context"` // context information
-}
-
-// DedupResult deduplication result
-type DedupResult struct {
- IsDuplicate bool `json:"is_duplicate"`
- Confidence float64 `json:"confidence"` // confidence 0-1
- Reason string `json:"reason"` // reasoning
- SimilarID string `json:"similar_id"` // similar historical record ID
- SimilarDesc string `json:"similar_desc"` // similar record description
- Suggestion string `json:"suggestion"` // suggestion (skip | merge | proceed)
-}
-```
-
-**Agent Semantic Deduplication Flow:**
-
-```
-Goal/Task to be checked
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Step 1: Retrieve Historical Records β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Query from database for this member's recent: β β
-β β β’ Goal records (last 7 days) β β
-β β β’ Task records (last 24 hours) β β
-β β β’ Execution results (success/failure/in-progress) β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Step 2: Agent Semantic Judgment β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Call Dedup Agent with Prompt: β β
-β β β β
-β β "Please determine if the following goal duplicates β β
-β β historical records: β β
-β β β β
-β β Goal to check: {content} β β
-β β β β
-β β Historical records: β β
-β β 1. [2024-01-09] Analyze weekly sales data - Completed β β
-β β 2. [2024-01-08] Generate customer analysis - Completed β β
-β β 3. [2024-01-10] Track key customers - In progress β β
-β β β β
-β β Please determine: β β
-β β - Is it essentially the same as any historical record? β β
-β β - If so, suggest how to handle (skip/merge/proceed)?" β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Step 3: Decision Based on Result β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β β’ skip: Skip, don't execute β β
-β β β’ merge: Merge into existing task β β
-β β β’ proceed: Continue execution (not duplicate, or needs β β
-β β re-execution) β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-```
-
-**Dedup Agent Implementation:**
-
-```go
-// Call Dedup Agent for semantic judgment
-func (s *DeduplicationService) CheckDuplicate(ctx *context.Context, req *DedupRequest) (*DedupResult, error) {
-
- // 1. Retrieve historical records
- var history []HistoryRecord
- switch req.Type {
- case "goal":
- history = s.getRecentGoals(req.AgentID, 7*24*time.Hour)
- case "task":
- history = s.getRecentTasks(req.AgentID, 24*time.Hour)
- }
-
- // If no historical records, return not duplicate
- if len(history) == 0 {
- return &DedupResult{IsDuplicate: false, Suggestion: "proceed"}, nil
- }
-
- // 2. Build dedup prompt
- prompt := buildDedupPrompt(req.Content, history)
-
- // 3. Call Dedup Agent
- messages := []context.Message{
- {Role: "system", Content: dedupSystemPrompt},
- {Role: "user", Content: prompt},
- }
-
- response, err := s.callAgent(ctx, s.dedupAgent, messages)
- if err != nil {
- // On dedup failure, default to not blocking execution
- return &DedupResult{IsDuplicate: false, Suggestion: "proceed"}, nil
- }
-
- // 4. Parse Agent's structured response
- return parseDedupResponse(response)
-}
-
-// Dedup Agent system prompt
-var dedupSystemPrompt = `You are a task deduplication assistant. Your job is to determine if a new task duplicates historical tasks.
-
-Judgment criteria:
-1. Essentially the same: The core intent of the goal/task is the same, even if worded differently
-2. Time sensitivity: Consider if the task is time-sensitive (e.g., "today's report" vs "yesterday's report" are not duplicates)
-3. Execution status: If a historical task failed, it may need re-execution
-
-Output format (JSON):
-{
- "is_duplicate": true/false,
- "confidence": 0.0-1.0,
- "reason": "reasoning",
- "similar_id": "similar historical record ID, if any",
- "suggestion": "skip | merge | proceed"
-}
-
-Suggestion meanings:
-- skip: Complete duplicate, suggest skipping
-- merge: Partial duplicate, suggest merging into existing task
-- proceed: Not duplicate, or similar but needs re-execution`
-```
-
-**Deduplication Timing:**
-
-| Phase | Dedup Type | Description |
-| ---------------- | --------------- | ------------------------------------------------------------------- |
-| After Phase 1 | Goal dedup | Compare generated goals with historical goals |
-| After Phase 2 | Task dedup | Compare decomposed tasks with historical tasks |
-| Before execution | Execution dedup | Prevent same trigger from duplicate submission (memory-level, fast) |
-
-**Execution-Level Deduplication (Fast, Memory):**
-
-```go
-// Execution-level dedup (no Agent needed, pure memory check)
-type ExecutionDedup struct {
- runningSet map[string]bool // agent_id + trigger_type + trigger_id
- queuedSet map[string]bool
- mutex sync.RWMutex
-}
-
-func (d *ExecutionDedup) IsDuplicate(agentID, triggerType, triggerID string) bool {
- key := fmt.Sprintf("%s:%s:%s", agentID, triggerType, triggerID)
- d.mutex.RLock()
- defer d.mutex.RUnlock()
- return d.runningSet[key] || d.queuedSet[key]
-}
-```
-
-### 6. Inspiration Factor
-
-The Inspiration Factor is input on the executing Agent side, collected in **Phase 0** by calling a dedicated **Inspiration Agent**.
-
-```
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Execution Start (Executor Side) β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Phase 0: Inspiration Collection β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Call: Inspiration Agent (dedicated inspiration collector)β β
-β β β β
-β β Input: β β
-β β β’ Member identity info (job responsibilities) β β
-β β β’ List of accessible data sources β β
-β β β’ Last execution time β β
-β β β’ Private knowledge base ID β β
-β β β β
-β β Inspiration Agent Responsibilities: β β
-β β β’ Query data sources, discover changes β β
-β β β’ Check time factors (periodic tasks, deadlines) β β
-β β β’ Retrieve historical experience (success/failure β β
-β β patterns) β β
-β β β’ Get pending items β β
-β β β’ Web Search: Perceive external world changes related β β
-β β to job responsibilities β β
-β β β’ Comprehensive analysis, generate inspiration report β β
-β β β β
-β β Output: InspirationReport β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
- Phase 1: Goal Generation
- (Use inspiration report to generate high-value goals)
-```
-
-**Inspiration Agent Configuration:**
-
-```go
-// Configured in AgentConfig.Resources
-type Resources struct {
- // Phase assistants
- Inspiration string `json:"inspiration"` // Inspiration Agent (Phase 0)
- GoalGenerator string `json:"goal_generator"` // Goal Generator Agent (Phase 1)
- TaskPlanner string `json:"task_planner"` // Task Planner Agent (Phase 2)
- Validator string `json:"validator"` // Validator Agent (Phase 3)
- Delivery string `json:"delivery"` // Delivery Agent (Phase 4)
- Learning string `json:"learning"` // Learning Agent (Phase 5)
-
- // ...
-}
-```
-
-**Inspiration Report Structure:**
-
-```go
-// InspirationReport (generated by Inspiration Agent)
-type InspirationReport struct {
- // Structured output from Agent analysis
- Summary string `json:"summary"` // Overall situation summary
- Highlights []Highlight `json:"highlights"` // Key findings
- Opportunities []Opportunity `json:"opportunities"` // Discovered opportunities
- Risks []Risk `json:"risks"` // Potential risks
- WorldInsights []WorldInsight `json:"world_insights"` // External world insights
- Suggestions []string `json:"suggestions"` // Suggested focus areas
-
- // Raw data (for Goal Generator reference)
- RawData *InspirationData `json:"raw_data"`
-}
-
-// Highlight key finding
-type Highlight struct {
- Type string `json:"type"` // data_change | event | feedback | deadline | world_news
- Title string `json:"title"` // Title
- Description string `json:"description"` // Description
- Importance string `json:"importance"` // high | medium | low
- Source string `json:"source"` // internal | external
-}
-
-// Opportunity
-type Opportunity struct {
- Description string `json:"description"`
- Reason string `json:"reason"` // Why it's an opportunity
- TimeWindow string `json:"time_window"` // Time window
- Source string `json:"source"` // internal | external
-}
-
-// Risk
-type Risk struct {
- Description string `json:"description"`
- Impact string `json:"impact"` // Impact
- Mitigation string `json:"mitigation"` // Suggested mitigation
- Source string `json:"source"` // internal | external
-}
-
-// WorldInsight external world insight
-type WorldInsight struct {
- Topic string `json:"topic"` // Topic
- Insight string `json:"insight"` // Insight
- ActionSuggestion string `json:"action_suggestion"` // Suggested action
-}
-
-// InspirationData raw inspiration data
-type InspirationData struct {
- // Internal changes (system data)
- DataChanges []DataChange `json:"data_changes"`
- Events []Event `json:"events"`
- Feedbacks []Feedback `json:"feedbacks"`
-
- // External world changes (Web Search)
- WorldNews []WorldNews `json:"world_news"`
-
- // Time factors
- TimeContext *TimeContext `json:"time_context"`
- Deadlines []Deadline `json:"deadlines"`
-
- // Historical experience
- RecentGoals []GoalRecord `json:"recent_goals"`
-
- // Pending items
- PendingItems []PendingItem `json:"pending_items"`
-}
-
-// WorldNews external world news
-type WorldNews struct {
- Topic string `json:"topic"` // Search topic (based on job responsibilities)
- Title string `json:"title"` // News/update title
- Summary string `json:"summary"` // Summary
- Source string `json:"source"` // Source
- URL string `json:"url"` // Link
- PublishedAt time.Time `json:"published_at"` // Published time
- Relevance float64 `json:"relevance"` // Relevance to job (0-1)
-}
-
-// DataChange data change
-type DataChange struct {
- Source string `json:"source"` // Data source
- ChangeType string `json:"change_type"` // insert | update | threshold
- Description string `json:"description"` // Change description
- Timestamp time.Time `json:"timestamp"`
-}
-
-// TimeContext time context
-type TimeContext struct {
- Now time.Time `json:"now"`
- DayOfWeek string `json:"day_of_week"` // Monday, Tuesday...
- IsWeekend bool `json:"is_weekend"`
- IsMonthStart bool `json:"is_month_start"`
- IsMonthEnd bool `json:"is_month_end"`
- IsQuarterEnd bool `json:"is_quarter_end"`
- // Extensible: holidays, special dates, etc.
-}
-```
-
-**Inspiration Agent Call:**
-
-```go
-// Phase 0: Call Inspiration Agent to collect inspiration
-func (e *Executor) collectInspiration(ctx *context.Context, agent *AutonomousAgent) (*InspirationReport, error) {
-
- // 1. Prepare raw data (collected by system, provided to Agent)
- rawData := &InspirationData{
- // Internal data changes
- DataChanges: e.dataMonitor.GetChanges(agent.AgentID, agent.LastExecutionTime),
- Events: e.eventQueue.GetPending(agent.AgentID),
- Feedbacks: e.feedbackStore.GetRecent(agent.AgentID),
-
- // External world news (Web Search)
- WorldNews: e.searchWorldNews(agent.Config.Identity),
-
- // Time and history
- TimeContext: buildTimeContext(time.Now()),
- Deadlines: e.getUpcomingDeadlines(agent.AgentID),
- RecentGoals: e.getRecentGoals(agent.AgentID),
- PendingItems: e.getPendingItems(agent.AgentID),
- }
-
-// searchWorldNews searches for external world news related to job responsibilities
-func (e *Executor) searchWorldNews(identity *Identity) []WorldNews {
- // 1. Generate search keywords based on job responsibilities
- keywords := e.generateSearchKeywords(identity)
-
- // 2. Call Web Search MCP Tool
- var news []WorldNews
- for _, keyword := range keywords {
- results, err := e.mcpClient.Call("web_search", map[string]interface{}{
- "query": keyword,
- "limit": 5,
- "recent": "24h", // Only search last 24 hours
- })
- if err != nil {
- continue
- }
-
- // 3. Filter and evaluate relevance
- for _, r := range results {
- news = append(news, WorldNews{
- Topic: keyword,
- Title: r.Title,
- Summary: r.Snippet,
- Source: r.Source,
- URL: r.URL,
- PublishedAt: r.PublishedAt,
- Relevance: e.evaluateRelevance(r, identity),
- })
- }
- }
-
- // 4. Sort by relevance, take Top N
- sort.Slice(news, func(i, j int) bool {
- return news[i].Relevance > news[j].Relevance
- })
- if len(news) > 10 {
- news = news[:10]
- }
-
- return news
-}
-
- // 2. Build prompt for Inspiration Agent to analyze
- prompt := buildInspirationPrompt(agent.Config.Identity, rawData)
-
- messages := []context.Message{
- {Role: "system", Content: inspirationSystemPrompt},
- {Role: "user", Content: prompt},
- }
-
- // 3. Call Inspiration Agent
- response, err := e.callAssistant(ctx, agent.Config.Resources.Inspiration, messages)
- if err != nil {
- return nil, err
- }
-
- // 4. Parse returned inspiration report
- report := parseInspirationReport(response)
- report.RawData = rawData
-
- return report, nil
-}
-
-// Inspiration Agent system prompt
-var inspirationSystemPrompt = `You are an inspiration collection assistant. Your job is to analyze the current situation and discover valuable work directions for AI members.
-
-You will receive:
-1. The member's job responsibilities
-2. Recent data changes, events, feedback
-3. External world news (industry news, market changes related to the job)
-4. Time context (day of week, end of month, etc.)
-5. Historical goal execution status
-6. Pending items
-
-Please analyze this information and output a structured inspiration report (JSON):
-{
- "summary": "One-sentence summary of the overall situation",
- "highlights": [
- {"type": "data_change|event|feedback|deadline|world_news", "title": "Title", "description": "Description", "importance": "high|medium|low"}
- ],
- "opportunities": [
- {"description": "Opportunity description", "reason": "Why it's an opportunity", "time_window": "Time window", "source": "internal|external"}
- ],
- "risks": [
- {"description": "Risk description", "impact": "Impact", "mitigation": "Suggested measures", "source": "internal|external"}
- ],
- "world_insights": [
- {"topic": "Topic", "insight": "Insight", "action_suggestion": "Suggested action"}
- ],
- "suggestions": ["Suggested focus area 1", "Suggested focus area 2"]
-}
-
-Key points:
-- Identify important changes and anomalies (internal data + external world)
-- Discover potential opportunities (combined with industry trends)
-- Alert potential risks (including risks from external environment changes)
-- Extract job-relevant insights from external world news
-- Give suggestions based on time factors`
-```
-
-**Injecting Inspiration Report into Goal Generation:**
-
-```go
-// Phase 1: Generate goals using inspiration report
-func (e *Executor) generateGoals(ctx *context.Context, agent *AutonomousAgent, report *InspirationReport) ([]Goal, error) {
-
- // Build goal generation prompt, inject inspiration report
- prompt := buildGoalPrompt(agent.Config.Identity, report)
-
- /*
- Prompt example:
-
- You are [Sales Manager], responsible for [tracking sales performance, generating reports].
-
- ## Inspiration Report
-
- ### Summary
- This week's sales data shows significant changes, and there are new industry developments to focus on.
-
- ### Key Findings
- - [High] Data change: 15 new sales records yesterday, 50% increase
- - [High] Deadline: Today is Friday, need to prepare weekly report
- - [Medium] Customer feedback: Customer A submitted product feedback
- - [High] External news: Competitor released new product, may affect market landscape
-
- ### Opportunities
- - [Internal] This week's sales exceeded last week by 20%, can analyze growth reasons
- - [Internal] TOP3 customers contributed 60% of sales, worth deep analysis
- - [External] Industry report shows market demand growth, opportunity to expand
-
- ### Risks
- - [Internal] 3 days until month end, monthly target only 80% complete
- - [External] Competitor price promotion, need to watch for customer churn risk
-
- ### External World Insights
- - Topic: Industry Trends
- Insight: AI adoption in sales accelerating, automation tool demand growing
- Suggestion: Evaluate automation opportunities in current sales process
- - Topic: Competitors
- Insight: XX company released new product line, focusing on value
- Suggestion: Prepare differentiation strategy, emphasize service advantages
-
- ### Suggested Directions
- - Analyze this week's sales growth reasons
- - Prepare weekly report
- - Follow up on monthly target progress
- - Monitor competitor developments, prepare response strategy
-
- Please generate today's most valuable work goals based on the above inspiration report.
- */
-
- messages := []context.Message{
- {Role: "system", Content: goalGeneratorSystemPrompt},
- {Role: "user", Content: prompt},
- }
-
- return e.callAssistant(ctx, agent.Config.Resources.GoalGenerator, messages)
-}
-```
-
-**Manager-Side Tick Processing Flow:**
-
-```go
-func (m *Manager) onTick() {
- // Get active members from cache (no database query)
- agents := m.cache.GetActive()
-
- for _, agent := range agents {
- // 1. Check scheduling time
- if !agent.ShouldRun(time.Now()) {
- continue
- }
-
- // 2. Execution-level deduplication (fast, memory)
- dedupKey := fmt.Sprintf("%s:schedule:%s", agent.AgentID, getScheduleWindow(time.Now()))
- if m.executionDedup.IsDuplicate(dedupKey) {
- continue
- }
-
- // 3. Build execution request (no inspiration factor, collected on Executor side)
- req := &ExecutionRequest{
- AgentID: agent.AgentID,
- TriggerType: "schedule",
- TriggerTime: time.Now(),
- }
-
- // 4. Submit to scheduler
- m.scheduler.Submit(req)
- }
-}
-```
-
-**Executor-Side Execution Flow:**
-
-```go
-func (e *Executor) Execute(ctx *context.Context, req *ExecutionRequest, agent *AutonomousAgent) (*ExecutionState, error) {
- state := &ExecutionState{
- AgentID: agent.AgentID,
- StartTime: time.Now(),
- Status: StatusRunning,
- }
-
- // Phase 0: Inspiration collection (call Inspiration Agent)
- state.Phase = PhaseInspiration
- report, err := e.collectInspiration(ctx, agent)
- if err != nil {
- // Inspiration collection failure doesn't block execution, use empty report
- report = &InspirationReport{Summary: "Inspiration collection failed, using default mode"}
- }
-
- // Phase 1: Goal generation (using inspiration report)
- state.Phase = PhaseGoalGeneration
- goals, err := e.generateGoals(ctx, agent, report)
- if err != nil {
- return state.Failed(err)
- }
-
- // Phase 1.5: Goal deduplication (call Dedup Agent)
- goals, err = e.deduplicateGoals(ctx, agent, goals)
- if err != nil {
- return state.Failed(err)
- }
- state.Goals = goals
-
- // Phase 2: Task decomposition
- state.Phase = PhaseTaskDecomposition
- tasks, err := e.decomposeTasks(ctx, agent, goals)
- if err != nil {
- return state.Failed(err)
- }
-
- // Phase 2.5: Task deduplication (call Dedup Agent)
- tasks, err = e.deduplicateTasks(ctx, agent, tasks)
- if err != nil {
- return state.Failed(err)
- }
- state.Tasks = tasks
-
- // Phase 3: Task execution
- state.Phase = PhaseTaskExecution
- for i := range tasks {
- if err := e.executeTask(ctx, agent, &tasks[i]); err != nil {
- tasks[i].Status = TaskStatusFailed
- tasks[i].Error = err.Error()
- }
- }
-
- // Phase 4: Result delivery
- state.Phase = PhaseDelivery
- if err := e.deliver(ctx, agent, state); err != nil {
- // Delivery failure is recorded but doesn't interrupt
- state.DeliveryError = err.Error()
- }
-
- // Phase 5: Learning
- state.Phase = PhaseLearning
- if err := e.learn(ctx, agent, state); err != nil {
- // Learning failure is recorded but doesn't interrupt
- }
-
- state.Status = StatusCompleted
- state.EndTime = time.Now()
- return state, nil
-}
-```
-
-### Scheduling Flow
-
-```
-Trigger Source (World Clock/Human Intervention/Event)
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Scheduler β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β 1. Check member quota: current concurrent < max? β β
-β β β’ Yes β Enter global queue β β
-β β β’ No β Enter member wait queue β β
-β β β β
-β β 2. Global queue sorted by priority β β
-β β β’ Member priority β β
-β β β’ Trigger time (FIFO) β β
-β β β’ Trigger type weight (intervention > event > schedule)β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Global Worker Pool β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Worker gets task: β β
-β β 1. Take highest priority task from global queue β β
-β β 2. Double check member quota β β
-β β 3. Execute task, update member concurrent count β β
-β β 4. On completion, release and check member wait queue β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-```
-
-### Global Configuration
-
-```go
-// ManagerConfig global manager configuration
-type ManagerConfig struct {
- // Worker pool configuration
- GlobalWorkerCount int `json:"global_worker_count"` // Global worker count (default: 10)
- GlobalQueueSize int `json:"global_queue_size"` // Global queue size (default: 100)
-
- // Default member quota (can be overridden by member config)
- DefaultMaxConcurrent int `json:"default_max_concurrent"` // Default max concurrent (default: 2)
- DefaultQueueSize int `json:"default_queue_size"` // Default queue size (default: 10)
-
- // Trigger type weights (for priority sorting)
- TriggerWeights map[string]int `json:"trigger_weights"` // intervene: 100, event: 50, schedule: 10
-}
-```
-
-### Execution Request
-
-```go
-// ExecutionRequest execution request
-type ExecutionRequest struct {
- ID string `json:"id"`
- AgentID string `json:"agent_id"`
- TeamID string `json:"team_id"`
- TriggerType string `json:"trigger_type"` // schedule | intervene | event
- TriggerData interface{} `json:"trigger_data"` // Trigger-related data
- Priority int `json:"priority"` // Calculated priority
- CreatedAt time.Time `json:"created_at"`
- Status string `json:"status"` // queued | running | completed | failed
-}
-
-// Priority calculation
-func (r *ExecutionRequest) CalculatePriority(config *ManagerConfig, agentConfig *AgentConfig) int {
- // Base priority = member priority
- priority := agentConfig.Concurrency.Priority * 10
-
- // + trigger type weight
- if weight, ok := config.TriggerWeights[r.TriggerType]; ok {
- priority += weight
- }
-
- // + wait time bonus (every minute waiting +1)
- waitMinutes := int(time.Since(r.CreatedAt).Minutes())
- priority += waitMinutes
-
- return priority
-}
-```
-
-## Execution Flow
-
-### Trigger Sources Configuration
-
-Trigger sources can be configured per AI member. All triggers are **enabled by default**.
-
-| Trigger Type | Config Field | Description | Default |
-| ------------ | ---------------------------- | -------------------------------------- | ------- |
-| Schedule | `triggers.schedule.enabled` | World Clock trigger (cron/interval) | `true` |
-| Intervene | `triggers.intervene.enabled` | Human intervention trigger | `true` |
-| Event | `triggers.event.enabled` | External event trigger (webhook, etc.) | `true` |
-
-**Configuration Example:**
-
-```yaml
-agent_config:
- triggers:
- schedule: { enabled: true }
- intervene: { enabled: true, actions: ["add_task", "pause"] }
- event: { enabled: false }
-
- schedule:
- type: cron
- expr: "0 9 * * 1-5"
- tz: Asia/Shanghai
- timeout: 30m
-```
-
-### Execution Flow Diagram (Mermaid)
-
-```mermaid
-flowchart TB
- subgraph Trigger["Trigger Sources (Configurable)"]
- WC[/"World Clock
(Schedule)
triggers.schedule"/]
- HI[/"Human Intervention
(Intervene)
triggers.intervene"/]
- EV[/"External Events
(Event)
triggers.event"/]
- end
-
- subgraph Manager["Autonomous Agent Manager"]
- TriggerCheck{"Trigger
Enabled?"}
- Cache[("Agent Cache
(Memory)")]
- Check{Schedule Check
& Dedup}
- Queue["Global Queue
(Priority Sorted)"]
- end
-
- subgraph WorkerPool["Global Worker Pool"]
- W1["Worker 1"]
- W2["Worker 2"]
- W3["Worker N..."]
- end
-
- subgraph Executor["Agent Executor"]
- subgraph Phase0["Phase 0: Inspiration"]
- P0_1["Collect Internal Data Changes"]
- P0_2["Web Search: External World"]
- P0_3["Call Inspiration Agent"]
- P0_4[/"Inspiration Report"/]
- end
-
- subgraph Phase1["Phase 1: Goal Generation"]
- P1_1["Inject Inspiration Report"]
- P1_2["Call Goal Generator Agent"]
- P1_3["Goal Deduplication"]
- P1_4[/"Goals List"/]
- end
-
- subgraph Phase2["Phase 2: Task Decomposition"]
- P2_1["Analyze Goals"]
- P2_2["Call Task Planner Agent"]
- P2_3["Task Deduplication"]
- P2_4[/"Tasks List"/]
- end
-
- subgraph Phase3["Phase 3: Task Execution"]
- P3_1["Execute Task via Assistant/MCP"]
- P3_2["Call Validator Agent"]
- P3_3{All Tasks
Complete?}
- P3_4[/"Task Results"/]
- end
-
- subgraph Phase4["Phase 4: Delivery"]
- P4_1["Aggregate Results"]
- P4_2["Call Delivery Agent"]
- P4_3[/"Deliverables
(Email/Report/File)"/]
- end
-
- subgraph Phase5["Phase 5: Learning"]
- P5_1["Analyze Execution"]
- P5_2["Call Learning Agent"]
- P5_3["Write to Private KB"]
- end
- end
-
- subgraph Storage["Persistence"]
- KB[("Private KB")]
- DB[("autonomous_executions")]
- Job[("Job System
(Activity Monitor)")]
- end
-
- %% Trigger to Manager (with trigger enabled check)
- WC --> TriggerCheck
- HI --> TriggerCheck
- EV --> TriggerCheck
- TriggerCheck -->|Enabled| Cache
- TriggerCheck -->|Disabled| X[/"Ignored"/]
- Cache --> Check
- Check -->|Pass| Queue
- Check -->|Duplicate/Skip| Cache
-
- %% Manager to Worker
- Queue --> W1
- Queue --> W2
- Queue --> W3
-
- %% Worker to Executor
- W1 --> Phase0
- W2 --> Phase0
- W3 --> Phase0
-
- %% Phase 0 Flow
- P0_1 --> P0_3
- P0_2 --> P0_3
- P0_3 --> P0_4
-
- %% Phase 1 Flow
- P0_4 --> P1_1
- P1_1 --> P1_2
- P1_2 --> P1_3
- P1_3 --> P1_4
-
- %% Phase 2 Flow
- P1_4 --> P2_1
- P2_1 --> P2_2
- P2_2 --> P2_3
- P2_3 --> P2_4
-
- %% Phase 3 Flow
- P2_4 --> P3_1
- P3_1 --> P3_2
- P3_2 --> P3_3
- P3_3 -->|No| P3_1
- P3_3 -->|Yes| P3_4
-
- %% Phase 4 Flow
- P3_4 --> P4_1
- P4_1 --> P4_2
- P4_2 --> P4_3
-
- %% Phase 5 Flow
- P4_3 --> P5_1
- P5_1 --> P5_2
- P5_2 --> P5_3
-
- %% Storage connections
- P5_3 --> KB
- P5_3 --> DB
- P5_3 --> Job
-
- %% KB feedback to Phase 0
- KB -.->|Historical Experience| P0_1
-```
-
-### Execution Sequence Diagram (Mermaid)
+### 3.1 Trigger β Schedule β Execute
```mermaid
sequenceDiagram
autonumber
- participant WC as World Clock
+ participant T as Trigger
participant M as Manager
participant S as Scheduler
participant W as Worker
participant E as Executor
- participant IA as Inspiration Agent
- participant GA as Goal Agent
- participant TA as Task Planner
- participant VA as Validator
- participant DA as Delivery Agent
- participant LA as Learning Agent
+ participant A as Agents (P0-P5)
participant KB as Private KB
- participant Job as Job System
- WC->>M: Tick Event
- M->>M: Get active agents from cache
- M->>M: Check schedule & dedup
- M->>S: Submit ExecutionRequest
+ T->>M: Trigger Event
+ M->>M: Check trigger enabled
+ M->>M: Get agent from cache
+ M->>M: Dedup check
+ M->>S: Submit request
- S->>S: Check member quota
- S->>S: Priority queue sorting
- S->>W: Dispatch to worker
+ S->>S: Check quota
+ S->>S: Priority sort
+ S->>W: Dispatch
- W->>E: Execute(agent)
- E->>Job: Create Execution record
+ W->>E: Execute
- rect rgb(240, 248, 255)
- Note over E,IA: Phase 0: Inspiration Collection
- E->>E: Collect data changes
- E->>E: Web search for world news
- E->>IA: Analyze & generate report
- IA-->>E: InspirationReport
+ loop Phase 0-5
+ E->>A: Call phase agent
+ A-->>E: Result
end
- rect rgb(255, 250, 240)
- Note over E,GA: Phase 1: Goal Generation
- E->>KB: Retrieve historical experience
- KB-->>E: Past goals & insights
- E->>GA: Generate goals (with inspiration)
- GA-->>E: Goals[]
- E->>E: Deduplicate goals
- end
-
- rect rgb(240, 255, 240)
- Note over E,TA: Phase 2: Task Decomposition
- E->>TA: Decompose goals into tasks
- TA-->>E: Tasks[]
- E->>E: Deduplicate tasks
- end
-
- rect rgb(255, 240, 245)
- Note over E,VA: Phase 3: Task Execution
- loop For each task
- E->>E: Execute via Assistant/MCP
- E->>VA: Validate result
- VA-->>E: Validation result
- E->>Job: Update progress
- end
- end
-
- rect rgb(245, 245, 255)
- Note over E,DA: Phase 4: Delivery
- E->>DA: Generate deliverables
- DA-->>E: Email/Report/File
- end
-
- rect rgb(255, 255, 240)
- Note over E,LA: Phase 5: Learning
- E->>LA: Analyze execution
- LA-->>E: Knowledge entries
- E->>KB: Store learned knowledge
- end
-
- E->>Job: Complete Execution
- E-->>W: ExecutionState
- W-->>S: Release worker
- S-->>M: Execution complete
+ E->>KB: Store learning
+ E-->>W: Complete
```
-### Phase Details
+### 3.2 Trigger Sources
-Each Autonomous Agent executes the following standard flow when scheduling conditions are met:
+| Trigger | Description | Config |
+| ------------- | --------------------------- | -------------------- |
+| **Schedule** | World Clock (cron/interval) | `triggers.schedule` |
+| **Intervene** | Human intervention | `triggers.intervene` |
+| **Event** | Webhook, DB changes | `triggers.event` |
+
+All triggers enabled by default. Configure per-agent:
+
+```yaml
+triggers:
+ schedule: { enabled: true }
+ intervene: { enabled: true, actions: ["add_task", "pause"] }
+ event: { enabled: false }
+```
+
+### 3.3 Concurrency Control
+
+Two-level control prevents resource monopolization:
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Autonomous Agent Execution β
-β β
-β Input: Identity + Private KB + Current State β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Phase 1: Goal Generation β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Call: Goal Generator Assistant β β
-β β Input: Identity + Private KB + Historical Context β β
-β β Output: Goal list (with priorities) β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Phase 2: Task Decomposition β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Call: Task Planner Assistant β β
-β β Input: Goal list + Available resources (Agents/MCP Tools)β β
-β β Output: Task list (with dependencies and executor β β
-β β assignments) β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Phase 3: Task Execution β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Loop through each task: β β
-β β 1. Call specified Agent or MCP Tool to execute task β β
-β β 2. Collect execution results β β
-β β 3. Call Validator Assistant to verify results β β
-β β 4. Update task status β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Phase 4: Delivery β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Call: Delivery Assistant β β
-β β Input: All task results + Delivery config β β
-β β Output: Final deliverables (email/report/file/ β β
-β β notification, etc.) β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Phase 5: Learning (Self-Learning) β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Call: Learning Assistant β β
-β β Input: Execution process + Results + Feedback β β
-β β Output: Experience summary β Write to Private KB β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
+β Global Worker Pool (10 workers) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+ β β β
+ βΌ βΌ βΌ
+βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
+β Sales Manager β β Data Analyst β β CS Specialist β
+β Quota: 3 β β Quota: 2 β β Quota: 3 β
+β Current: 2 β β β Current: 2 (full)β β Current: 1 β β
+βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
```
-## Data Structures
+### 3.4 Deduplication
-### Agent Configuration (stored in team_members.agent_config)
+**Execution-level** (fast, memory):
+
+```go
+key := fmt.Sprintf("%s:%s:%s", agentID, triggerType, window)
+if cache.Has(key) { skip }
+```
+
+**Semantic-level** (Agent-based, for goals/tasks):
+
+- Dedup Agent analyzes historical records
+- Returns: `skip` | `merge` | `proceed`
+
+### 3.5 Agent Cache
+
+Avoids frequent DB queries:
+
+```go
+type AgentCache struct {
+ agents map[string]*Agent // agent_id -> agent
+ byTeam map[string][]string // team_id -> []agent_id
+}
+
+// Refresh: startup, on change, periodic (hourly)
+```
+
+---
+
+## 4. Execution Phases
+
+### 4.1 Phase Overview
+
+```
+P0: Inspiration β P1: Goals β P2: Tasks β P3: Execute β P4: Deliver β P5: Learn
+```
+
+| Phase | Agent | Input | Output |
+| ----- | -------------- | -------------------------------------- | ----------------- |
+| P0 | Inspiration | Data changes, world news, time context | InspirationReport |
+| P1 | Goal Generator | Inspiration + KB experience | Goals[] |
+| P2 | Task Planner | Goals + available resources | Tasks[] |
+| P3 | Validator | Task results | Validated results |
+| P4 | Delivery | All results | Email/Report/File |
+| P5 | Learning | Execution summary | KB entries |
+
+### 4.2 Phase 0: Inspiration
+
+Collects context to generate high-value goals:
+
+```go
+type InspirationReport struct {
+ Summary string // Overall situation
+ Highlights []Highlight // Key findings (data_change|event|deadline|world_news)
+ Opportunities []Opportunity // Discovered opportunities
+ Risks []Risk // Potential risks
+ WorldInsights []WorldInsight // External world insights
+ Suggestions []string // Focus areas
+}
+```
+
+**Data sources:**
+
+- Internal: Data changes, events, feedback, pending items
+- External: Web search (industry news, competitors)
+- Time: Day of week, month end, deadlines
+
+### 4.3 Phase 1: Goal Generation
+
+Uses inspiration report to generate goals:
+
+```
+Prompt:
+You are [Sales Manager], responsible for [tracking KPIs, generating reports].
+
+## Inspiration Report
+### Key Findings
+- [High] Data: 15 new sales records (+50%)
+- [High] Deadline: Friday, prepare weekly report
+- [High] External: Competitor launched new product
+
+### Opportunities
+- Sales exceeded last week by 20%
+- Industry report shows market growth
+
+Please generate today's most valuable work goals.
+```
+
+### 4.4 Phase 2: Task Decomposition
+
+Breaks goals into executable tasks:
+
+```go
+type Task struct {
+ ID string
+ GoalID string
+ Description string
+ ExecutorType string // "assistant" | "mcp"
+ ExecutorID string // Assistant ID or MCP tool
+}
+```
+
+### 4.5 Phase 3: Execution
+
+For each task:
+
+1. Call specified Assistant or MCP Tool
+2. Collect result
+3. Call Validator to verify
+4. Update status
+
+### 4.6 Phase 4: Delivery
+
+Generates deliverables based on config:
+
+```yaml
+delivery:
+ type: email # email | file | webhook | notify
+ opts:
+ to: ["manager@company.com"]
+```
+
+### 4.7 Phase 5: Learning
+
+Analyzes execution, writes to private KB:
+
+| Category | Examples |
+| ----------- | ----------------------------------- |
+| `execution` | Task process, success/failure cases |
+| `feedback` | Validation results, error analysis |
+| `insight` | Patterns, optimization suggestions |
+
+---
+
+## 5. Configuration
+
+### 5.1 Config Structure
```go
-// Config AI member configuration (stored in team_members.agent_config JSON field)
type Config struct {
- Triggers *Triggers `json:"triggers,omitempty"` // Trigger sources (all enabled by default)
- Schedule *Schedule `json:"schedule,omitempty"` // Schedule config (for cron/interval)
- Identity *Identity `json:"identity"` // Role & responsibilities
- Quota *Quota `json:"quota"` // Concurrency quota
- PrivateKB *KB `json:"private_kb"` // Private knowledge base
- SharedKB *KB `json:"shared_kb,omitempty"` // Shared knowledge base
- Resources *Resources `json:"resources"` // Available assistants & tools
- Delivery *Delivery `json:"delivery"` // Output delivery config
+ Triggers *Triggers `json:"triggers,omitempty"` // Trigger sources
+ Schedule *Schedule `json:"schedule,omitempty"` // Timing
+ Identity *Identity `json:"identity"` // Role & duties
+ Quota *Quota `json:"quota"` // Concurrency
+ PrivateKB *KB `json:"private_kb"` // Private KB
+ SharedKB *KB `json:"shared_kb,omitempty"` // Shared KB refs
+ Resources *Resources `json:"resources"` // Agents & tools
+ Delivery *Delivery `json:"delivery"` // Output
+ Input *Input `json:"input,omitempty"` // Input isolation
+ Events []Event `json:"events,omitempty"` // Event sources
+ Monitor *Monitor `json:"monitor,omitempty"` // Monitoring
}
+```
-// Triggers trigger sources configuration (all enabled by default)
+### 5.2 Type Definitions
+
+```go
+// Triggers (all enabled by default)
type Triggers struct {
- Schedule *Trigger `json:"schedule,omitempty"` // World Clock
- Intervene *Trigger `json:"intervene,omitempty"` // Human Intervention
- Event *Trigger `json:"event,omitempty"` // External Events
+ Schedule *Trigger `json:"schedule,omitempty"`
+ Intervene *Trigger `json:"intervene,omitempty"`
+ Event *Trigger `json:"event,omitempty"`
}
-// Trigger single trigger configuration
type Trigger struct {
- Enabled bool `json:"enabled"` // default: true
- Actions []string `json:"actions,omitempty"` // Allowed actions (for intervene only)
+ Enabled bool `json:"enabled"`
+ Actions []string `json:"actions,omitempty"` // For intervene only
}
-// Quota concurrency quota
-type Quota struct {
- Max int `json:"max"` // Max concurrent (default: 2)
- Queue int `json:"queue"` // Queue size (default: 10)
- Priority int `json:"priority"` // Priority 1-10 (default: 5)
-}
-
-// Schedule timing configuration
+// Schedule
type Schedule struct {
Type string `json:"type"` // cron | interval
Expr string `json:"expr"` // "0 9 * * 1-5" or "1h"
@@ -1275,443 +355,307 @@ type Schedule struct {
Timeout string `json:"timeout"` // Max execution time
}
-// Identity role settings
+// Identity
type Identity struct {
- Role string `json:"role"` // Role name
+ Role string `json:"role"` // Role name
Duties []string `json:"duties"` // Responsibilities
- Rules []string `json:"rules"` // Constraints
+ Rules []string `json:"rules"` // Constraints
}
-// KB knowledge base configuration
+// Quota
+type Quota struct {
+ Max int `json:"max"` // Max concurrent (default: 2)
+ Queue int `json:"queue"` // Queue size (default: 10)
+ Priority int `json:"priority"` // 1-10 (default: 5)
+}
+
+// KB
type KB struct {
- ID string `json:"id,omitempty"` // Collection ID (auto-gen for private)
- Refs []string `json:"refs,omitempty"` // Referenced collections (for shared)
- Learning *Learn `json:"learn,omitempty"` // Learning config (for private)
+ ID string `json:"id,omitempty"` // Collection ID
+ Refs []string `json:"refs,omitempty"` // Shared refs
+ Learn *Learn `json:"learn,omitempty"` // Learning config
}
-// Learn self-learning configuration
type Learn struct {
- On bool `json:"on"` // Enable learning
- Types []string `json:"types"` // ["execution", "feedback", "insight"]
- Keep int `json:"keep"` // Retention days, 0 = forever
+ On bool `json:"on"` // Enable
+ Types []string `json:"types"` // ["execution", "feedback", "insight"]
+ Keep int `json:"keep"` // Retention days, 0 = forever
}
-// Resources available assistants & tools
+// Resources
type Resources struct {
- // Phase agents (P0-P5)
- P0 string `json:"p0"` // Inspiration
- P1 string `json:"p1"` // Goal Generator
- P2 string `json:"p2"` // Task Planner
- P3 string `json:"p3"` // Validator
- P4 string `json:"p4"` // Delivery
- P5 string `json:"p5"` // Learning
-
- // Execution resources
+ P0 string `json:"p0"` // Inspiration
+ P1 string `json:"p1"` // Goal Generator
+ P2 string `json:"p2"` // Task Planner
+ P3 string `json:"p3"` // Validator
+ P4 string `json:"p4"` // Delivery
+ P5 string `json:"p5"` // Learning
Agents []string `json:"agents"` // Callable assistants
MCP []MCP `json:"mcp"` // MCP services
}
-// MCP server configuration
type MCP struct {
ID string `json:"id"`
Tools []string `json:"tools,omitempty"` // empty = all
}
-// Delivery output configuration
+// Delivery
type Delivery struct {
Type string `json:"type"` // email | file | webhook | notify
- Opts map[string]interface{} `json:"opts"` // Type-specific options
+ Opts map[string]interface{} `json:"opts"`
+}
+
+// Monitor
+type Monitor struct {
+ On bool `json:"on"`
+ Alerts []Alert `json:"alerts,omitempty"`
+}
+
+type Alert struct {
+ Name string `json:"name"`
+ When string `json:"when"` // failed | timeout | error_rate
+ Value float64 `json:"value"` // Threshold
+ Window string `json:"window"` // 1h | 24h
+ Do []Action `json:"do"`
+ Cooldown string `json:"cooldown"`
+}
+
+type Action struct {
+ Type string `json:"type"` // email | webhook | notify
+ Opts map[string]interface{} `json:"opts"`
}
```
-### Execution State
+### 5.3 Full Example
-```go
-// ExecutionState execution state (persisted to database)
-type ExecutionState struct {
- ID string `json:"id"`
- TeamID string `json:"team_id"`
- AgentID string `json:"agent_id"`
- StartTime time.Time `json:"start_time"`
- EndTime *time.Time `json:"end_time,omitempty"`
- Status ExecutionStatus `json:"status"`
- Phase ExecutionPhase `json:"phase"`
- Goals []Goal `json:"goals,omitempty"`
- Tasks []Task `json:"tasks,omitempty"`
- Error string `json:"error,omitempty"`
- DeliveryResult interface{} `json:"delivery_result,omitempty"`
-}
-
-type ExecutionStatus string
-
-const (
- StatusPending ExecutionStatus = "pending"
- StatusRunning ExecutionStatus = "running"
- StatusCompleted ExecutionStatus = "completed"
- StatusFailed ExecutionStatus = "failed"
-)
-
-type ExecutionPhase string
-
-const (
- PhaseInspiration ExecutionPhase = "inspiration" // Phase 0
- PhaseGoalGeneration ExecutionPhase = "goal_generation" // Phase 1
- PhaseTaskDecomposition ExecutionPhase = "task_decomposition" // Phase 2
- PhaseTaskExecution ExecutionPhase = "task_execution" // Phase 3
- PhaseDelivery ExecutionPhase = "delivery" // Phase 4
- PhaseLearning ExecutionPhase = "learning" // Phase 5
-)
-
-// Goal
-type Goal struct {
- ID string `json:"id"`
- Description string `json:"description"`
- Priority int `json:"priority"`
- Status string `json:"status"`
-}
-
-// Task
-type Task struct {
- ID string `json:"id"`
- GoalID string `json:"goal_id"`
- Description string `json:"description"`
- ExecutorType string `json:"executor_type"` // assistant | mcp
- ExecutorID string `json:"executor_id"`
- Status string `json:"status"`
- Result interface{} `json:"result,omitempty"`
- Error string `json:"error,omitempty"`
+```json
+{
+ "member_type": "ai",
+ "agent_id": "sales-bot",
+ "agent_config": {
+ "triggers": {
+ "schedule": { "enabled": true },
+ "intervene": { "enabled": true },
+ "event": { "enabled": false }
+ },
+ "schedule": {
+ "type": "cron",
+ "expr": "0 9 * * 1-5",
+ "tz": "Asia/Shanghai",
+ "timeout": "30m"
+ },
+ "identity": {
+ "role": "Sales Analyst",
+ "duties": ["Analyze sales data", "Generate weekly reports"],
+ "rules": ["Only access sales-related data"]
+ },
+ "quota": { "max": 2, "queue": 10, "priority": 5 },
+ "private_kb": {
+ "learn": {
+ "on": true,
+ "types": ["execution", "feedback", "insight"],
+ "keep": 90
+ }
+ },
+ "shared_kb": { "refs": ["sales-policies", "product-catalog"] },
+ "resources": {
+ "p0": "__yao.inspiration",
+ "p1": "__yao.goal-gen",
+ "p2": "__yao.task-plan",
+ "p3": "__yao.validator",
+ "p4": "__yao.delivery",
+ "p5": "__yao.learning",
+ "agents": ["data-analyst", "chart-gen"],
+ "mcp": [{ "id": "database", "tools": ["query"] }]
+ },
+ "delivery": {
+ "type": "email",
+ "opts": { "to": ["manager@company.com"] }
+ }
+ }
}
```
-## Core Interfaces
+---
-### Manager Interface
+## 6. Lifecycle
+
+### 6.1 State Diagram
+
+```
+βββββββββββ POST create βββββββββββ
+β β ββββββββββββββΆ β β
+β None β β Active ββββββββ
+β β β β β
+βββββββββββ ββββββ¬βββββ β
+ β β
+ PATCH pause β PATCH resume
+ βΌ β
+ βββββββββββ β
+ β Paused ββββββββ
+ ββββββ¬βββββ
+ β
+ DELETE β
+ βΌ
+ βββββββββββ
+ β Deleted β
+ βββββββββββ
+```
+
+### 6.2 State Transitions
+
+| From | To | Trigger |
+| ------------- | ------- | --------------------- |
+| - | active | POST create member |
+| active | paused | PATCH status="paused" |
+| paused | active | PATCH status="active" |
+| active/paused | deleted | DELETE member |
+
+### 6.3 Initialization
+
+On create:
+
+1. Validate config
+2. Generate agent_id (if not provided)
+3. Create private KB: `agent_{team_id}_{agent_id}_kb`
+4. Register with Manager (add to cache)
+5. Create Job entry
+6. Set status = "active"
+
+### 6.4 Active State
+
+```
+ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ
+β Idle ββββββΆβ TriggeredββββββΆβ Running ββββββΆβ Learning β
+β βββββββ β β (P0-P4) β β (P5) β
+ββββββββββββ ββββββββββββ ββββββββββββ ββββββ¬ββββββ
+ β² β
+ ββββββββββββββββββββββββββββββββββββββββββββββββββββ
+```
+
+### 6.5 Termination
+
+On delete:
+
+1. Cancel running executions
+2. Remove from cache
+3. Delete Job entry
+4. Handle KB (delete or archive)
+5. Soft delete record
+
+---
+
+## 7. Integrations
+
+### 7.1 Job System (Activity Monitor)
+
+Each Agent maps to a Job, each execution to an Execution:
+
+```
+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+β Activity Monitor (UI) β
+β β’ Task list and status β
+β β’ Real-time progress β
+β β’ Execution logs β
+β β’ Cancel/pause/retry β
+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+ β
+ βΌ
+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+β Job Framework β
+β Job β Execution β Progress β Logs β
+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+```
+
+**APIs:**
+
+| Feature | API |
+| ----------- | -------------------------------------------- |
+| List agents | `GET /api/jobs?category_id=autonomous_agent` |
+| History | `GET /api/jobs/:job_id/executions` |
+| Progress | `GET /api/jobs/:job_id/executions/:id` |
+| Logs | `GET /api/jobs/:job_id/executions/:id/logs` |
+| Cancel | `POST /api/jobs/:job_id/stop` |
+| Trigger | `POST /api/jobs/:job_id/trigger` |
+
+### 7.2 Private Knowledge Base
+
+Auto-created per agent: `agent_{team_id}_{agent_id}_kb`
+
+**Learning categories:**
+
+- `execution`: Task process, success/failure
+- `feedback`: Validation, errors
+- `insight`: Patterns, best practices
+
+**Lifecycle:**
+
+- Create: On agent creation
+- Update: After each execution (P5)
+- Cleanup: Based on `keep` config
+- Delete: On agent deletion (or archive)
+
+### 7.3 External Input
+
+**Input types:**
+
+- `schedule`: World Clock
+- `intervene`: Human intervention
+- `event`: Webhooks, DB triggers
+- `callback`: Async task callbacks
+
+**Intervention actions:**
+
+- `adjust_goal`: Modify current goal
+- `add_task`: Add new task
+- `cancel_task`: Cancel task
+- `pause` / `resume` / `abort`
+- `plan`: Queue for later
+
+**Plan Queue:**
+
+- Stores deferred goals/tasks
+- Processed at start of next execution
+
+---
+
+## 8. API Reference
+
+### 8.1 Core Interfaces
```go
-// Manager Autonomous Agent manager
type Manager interface {
- // Start/stop world clock
Start() error
Stop() error
-
- // Load active AI members from database
- LoadActiveAgents(ctx context.Context) ([]*AutonomousAgent, error)
-
- // Check if Agent should execute
- ShouldExecute(agent *AutonomousAgent, now time.Time) bool
-
- // Execute single Agent
- Execute(ctx context.Context, agent *AutonomousAgent) (*ExecutionState, error)
-
- // Manually trigger execution
- Trigger(ctx context.Context, teamID, agentID string) (*ExecutionState, error)
-
- // Query execution history
- GetExecutionHistory(ctx context.Context, teamID, agentID string, limit int) ([]*ExecutionState, error)
+ LoadActiveAgents(ctx context.Context) ([]*Agent, error)
+ ShouldExecute(agent *Agent, now time.Time) bool
+ Execute(ctx context.Context, agent *Agent) (*State, error)
+ Trigger(ctx context.Context, teamID, agentID string) (*State, error)
+ GetHistory(ctx context.Context, teamID, agentID string, limit int) ([]*State, error)
}
```
-### AutonomousAgent Structure
+### 8.2 Execution State
```go
-// AutonomousAgent autonomous agent (loaded from database)
-type AutonomousAgent struct {
- // From team_members table
- TeamID string `json:"team_id"`
- AgentID string `json:"agent_id"`
- RoleID string `json:"role_id"`
- Status string `json:"status"`
-
- // From agent_config JSON
- Config *AgentConfig `json:"config"`
-
- // Runtime state
- LastExecutionTime *time.Time `json:"last_execution_time,omitempty"`
+type State struct {
+ ID string
+ TeamID string
+ AgentID string
+ StartTime time.Time
+ EndTime *time.Time
+ Status Status // pending | running | completed | failed
+ Phase Phase // inspiration | goal_generation | task_decomposition | task_execution | delivery | learning
+ Goals []Goal
+ Tasks []Task
+ Error string
+ Result interface{}
}
```
-## Private Knowledge Base and Self-Learning
-
-Each Autonomous Agent has a dedicated private knowledge base for storing learning outcomes and accumulated experience.
-
-### Automatic KB Creation
-
-When an AI member is created, the system automatically creates a private knowledge base:
-
-```go
-// Auto-create private KB when creating AI member
-func createAgentPrivateKB(teamID, agentID string) (string, error) {
- collectionID := fmt.Sprintf("agent_%s_%s_kb", teamID, agentID)
-
- // Call KB API to create collection
- err := kb.CreateCollection(collectionID, &kb.CollectionConfig{
- Name: fmt.Sprintf("Agent %s Private KB", agentID),
- Description: "Auto-created private knowledge base for autonomous agent",
- Type: "agent_private",
- TeamID: teamID,
- AgentID: agentID,
- })
-
- return collectionID, err
-}
-```
-
-### Learning Content Categories
-
-The private knowledge base stores the following types of knowledge:
-
-| Category | Description | Examples |
-| ----------- | ------------------------- | ------------------------------------------------------------- |
-| `execution` | Execution records/results | Task execution process, success/failure cases |
-| `feedback` | Feedback and evaluation | Validation results, user feedback, error analysis |
-| `insight` | Insights and summaries | Pattern recognition, optimization suggestions, best practices |
-
-### Learning Flow (Phase 5)
-
-```
-After execution β Learning Assistant analyzes execution process
- β
- βΌ
- βββββββββββββββββββββ
- β Analysis content: β
- β β’ Goal achievementβ
- β β’ Task efficiency β
- β β’ Errors/anomaliesβ
- β β’ Success patternsβ
- βββββββββββββββββββββ
- β
- βΌ
- βββββββββββββββββββββ
- β Generate knowledgeβ
- β entries: β
- β β’ Experience β
- β summary β
- β β’ Improvement β
- β suggestions β
- β β’ Cautions β
- βββββββββββββββββββββ
- β
- βΌ
- Write to Private KB (vectorized storage)
-```
-
-### Knowledge Application
-
-In Phase 1 (Goal Generation), the Goal Generator Assistant retrieves from the private knowledge base:
-
-```go
-// Retrieve relevant experience during goal generation
-func (e *Executor) generateGoals(ctx *context.Context, agent *AutonomousAgent) ([]Goal, error) {
- // 1. Build retrieval query
- query := buildGoalQuery(agent.Config.Identity)
-
- // 2. Retrieve relevant experience from private KB
- experiences, err := kb.Search(agent.Config.PrivateKB.CollectionID, query, &kb.SearchOptions{
- Categories: []string{"insight", "feedback"},
- Limit: 10,
- })
-
- // 3. Call Goal Generator Assistant, inject historical experience
- messages := []context.Message{
- {Role: "system", Content: buildGoalPrompt(agent.Config.Identity, experiences)},
- {Role: "user", Content: "Please generate today's goals based on current state and historical experience"},
- }
-
- return e.callAssistant(ctx, agent.Config.Resources.GoalGenerator, messages)
-}
-```
-
-### Knowledge Base Lifecycle
-
-- **Creation**: Auto-created when AI member is created
-- **Update**: New knowledge written after each execution
-- **Cleanup**: Auto-cleanup of expired knowledge based on `retention_days` config
-- **Deletion**: When AI member is deleted, KB can be retained or deleted
-
-## Integration with Assistant
-
-Autonomous Agents complete various phase tasks by calling existing Assistants:
-
-```go
-// Call Assistant example
-func (e *Executor) callAssistant(ctx *context.Context, assistantID string, messages []context.Message) (*context.Response, error) {
- ast, err := assistant.Get(assistantID)
- if err != nil {
- return nil, err
- }
-
- return ast.Stream(ctx, messages, &context.Options{
- // Configuration options
- })
-}
-```
-
-## Lifecycle Management
-
-### AI Member Lifecycle Diagram
-
-```
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β AI Member Lifecycle β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-
- βββββββββββββββ
- β Create β POST /api/teams/:team_id/members
- β (member_type: "ai")
- ββββββββ¬βββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Initialization β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β 1. Validate agent_config β β
-β β 2. Generate agent_id (if not provided) β β
-β β 3. Create private KB: agent_{team_id}_{agent_id}_kb β β
-β β 4. Register with Manager (add to cache) β β
-β β 5. Create Job entry for scheduling β β
-β β 6. Set status = "active" β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Active State β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β β β
-β β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β β
-β β β Idle ββββββΆβ TriggeredββββββΆβ Running ββββββΆβ Learning β β β
-β β β βββββββ β β β β β β β
-β β ββββββββββββ ββββββββββββ ββββββββββββ ββββββ¬ββββββ β β
-β β β² β β β
-β β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
-β β β β
-β β Triggers: β β
-β β β’ World Clock (schedule) β β
-β β β’ Human Intervention (intervene) β β
-β β β’ External Events (event) β β
-β β β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- β PATCH /api/teams/:team_id/members/:member_id
- β (status: "paused")
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Paused State β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β β’ Removed from active cache β β
-β β β’ No longer triggered by World Clock β β
-β β β’ Private KB preserved β β
-β β β’ Can be resumed: PATCH status = "active" β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- β DELETE /api/teams/:team_id/members/:member_id
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Termination β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β 1. Cancel running executions (if any) β β
-β β 2. Remove from Manager cache β β
-β β 3. Delete Job entry β β
-β β 4. Handle private KB: β β
-β β β’ Option A: Delete KB (default) β β
-β β β’ Option B: Archive KB (if preserve_kb=true) β β
-β β 5. Mark record as deleted (soft delete) β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
- βββββββββββββββ
- β Deleted β
- β (archived) β
- βββββββββββββββ
-
-
-State Transitions:
-ββββββββββββ¬ββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββ
-β From β To β Trigger β
-ββββββββββββΌββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββ€
-β - β active β POST create member β
-β active β paused β PATCH status="paused" β
-β paused β active β PATCH status="active" β
-β active β deleted β DELETE member β
-β paused β deleted β DELETE member β
-ββββββββββββ΄ββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββ
-```
-
-### Creating AI Member
-
-```go
-// Add AI member via Team API
-POST /api/teams/:team_id/members
-{
- "member_type": "ai",
- "agent_id": "sales-bot",
- "role_id": "analyst",
- "agent_config": {
- "triggers": {
- "schedule": { "enabled": true },
- "intervene": { "enabled": true },
- "event": { "enabled": false }
- },
- "schedule": {
- "type": "cron",
- "expr": "0 9 * * 1-5",
- "tz": "Asia/Shanghai",
- "timeout": "30m"
- },
- "identity": {
- "role": "Sales Analyst",
- "duties": ["Analyze sales data", "Generate weekly reports"],
- "rules": ["Only access sales-related data"]
- },
- "quota": {
- "max": 2,
- "queue": 10,
- "priority": 5
- },
- "private_kb": {
- "learn": { "on": true, "types": ["execution", "feedback", "insight"], "keep": 90 }
- },
- "shared_kb": {
- "refs": ["sales-policies", "product-catalog"]
- },
- "resources": {
- "p0": "__yao.inspiration",
- "p1": "__yao.goal-gen",
- "p2": "__yao.task-plan",
- "p3": "__yao.validator",
- "p4": "__yao.delivery",
- "p5": "__yao.learning",
- "agents": ["data-analyst", "chart-gen"],
- "mcp": [{ "id": "database", "tools": ["query"] }]
- },
- "delivery": {
- "type": "email",
- "opts": { "to": ["manager@company.com"] }
- }
- }
-}
-
-// System automatically:
-// 1. Creates private KB: agent_{team_id}_{agent_id}_kb
-// 2. Registers with scheduler, allocates resources by quota
-```
-
-### Deleting AI Member
-
-```go
-// Remove AI member via Team API
-DELETE /api/teams/:team_id/members/:member_id
-
-// Manager will automatically stop this Agent on next Tick
-```
-
-## Execution State Persistence
+### 8.3 Database Schema
```sql
--- Execution history table
CREATE TABLE autonomous_executions (
id VARCHAR(64) PRIMARY KEY,
team_id VARCHAR(64) NOT NULL,
@@ -1723,561 +667,63 @@ CREATE TABLE autonomous_executions (
goals JSON,
tasks JSON,
error TEXT,
- delivery_result JSON,
+ result JSON,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
-
INDEX idx_team_agent (team_id, agent_id),
- INDEX idx_status (status),
- INDEX idx_start_time (start_time)
+ INDEX idx_status (status)
);
```
-## Security Considerations
+---
-1. **Team Isolation**: AI members can only access resources belonging to their team
-2. **Permission Inheritance**: AI member permissions are determined by their role_id
-3. **Resource Restrictions**: Callable resources limited via agent_config.resources
-4. **Execution Timeout**: Prevent infinite execution via max_execution_time
-5. **Audit Logs**: All execution records persisted to autonomous_executions table
+## 9. Security
-## External Input and Intervention Mechanism
+1. **Team Isolation**: Agents only access their team's resources
+2. **Permission Inheritance**: Permissions from role_id
+3. **Resource Restrictions**: Limited by `resources` config
+4. **Execution Timeout**: Enforced by `timeout` config
+5. **Audit Logs**: All executions persisted
-Besides scheduled triggers, Autonomous Agents need to respond to external inputs (human intervention, event notifications, etc.).
+---
-### Input Types
+## 10. Quick Reference
-```go
-// InputType input type
-type InputType string
-
-const (
- InputTypeSchedule InputType = "schedule" // Scheduled trigger
- InputTypeIntervene InputType = "intervene" // Human intervention (adjust goals/tasks)
- InputTypeEvent InputType = "event" // External event (webhook, system event)
- InputTypeCallback InputType = "callback" // Async task callback
-)
-
-// ExternalInput external input
-type ExternalInput struct {
- ID string `json:"id"`
- Type InputType `json:"type"`
- Source string `json:"source"` // Source identifier
- Priority int `json:"priority"` // Priority (1-10, 10 highest)
- Content interface{} `json:"content"` // Input content
- Metadata map[string]interface{} `json:"metadata"`
- CreatedAt time.Time `json:"created_at"`
-}
-```
-
-### Input Queue and Isolation
-
-Each Agent maintains an independent input queue for input isolation:
-
-```
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Autonomous Agent β
-β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Input Queue (Isolated) β β
-β β βββββββββββββ βββββββββββββ βββββββββββββ β β
-β β β Schedule β β Intervene β β Event β β β
-β β β Queue β β Queue β β Queue β β β
-β β β(Scheduled)β β(Intervention)β(Events) β β β
-β β βββββββ¬ββββββ βββββββ¬ββββββ βββββββ¬ββββββ β β
-β β β β β β β
-β β βββββββββββββββ΄ββββββββββββββ β β
-β β β β β
-β β βΌ β β
-β β βββββββββββββββββββ β β
-β β β Input Router β β β
-β β β (Priority Sort) β β β
-β β ββββββββββ¬βββββββββ β β
-β βββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββ β
-β βΌ β
-β Execution Engine β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-```
-
-### Input Processing Strategy
-
-```go
-// InputConfig input configuration (in AgentConfig)
-type InputConfig struct {
- // Input isolation settings
- Isolation *IsolationConfig `json:"isolation"`
-
- // Processing strategy for each input type
- Strategies map[InputType]*InputStrategy `json:"strategies"`
-}
-
-// IsolationConfig isolation configuration
-type IsolationConfig struct {
- QueueSize int `json:"queue_size"` // Queue size limit
- EnableRateLimit bool `json:"enable_rate_limit"` // Enable rate limiting
- RatePerMinute int `json:"rate_per_minute"` // Max inputs per minute
-}
-
-// InputStrategy input processing strategy
-type InputStrategy struct {
- Enabled bool `json:"enabled"` // Enable this input type
- Priority int `json:"priority"` // Default priority
- Action string `json:"action"` // immediate | queue | merge
- // immediate: Process immediately, can interrupt current execution
- // queue: Queue up, process by priority
- // merge: Merge into current/next execution plan
-}
-```
-
-### Intervention Processing Flow
-
-When receiving human intervention input:
-
-```
-External Intervention Input
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Intervene Handler β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β 1. Parse intervention intent β β
-β β β’ adjust_goal: Adjust current goal β β
-β β β’ add_task: Add new task β β
-β β β’ cancel_task: Cancel task β β
-β β β’ pause: Pause execution β β
-β β β’ resume: Resume execution β β
-β β β’ abort: Abort current execution β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Decide handling based on intervention type and current state β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β If currently executing: β β
-β β β’ High priority intervention β Interrupt current task,β β
-β β process immediately β β
-β β β’ Low priority intervention β Schedule into current β β
-β β task list β β
-β β If currently idle: β β
-β β β’ Trigger new execution cycle β β
-β β If intervention is plan-type: β β
-β β β’ Write to plan queue for later β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-```
-
-### Intervention Type Definitions
-
-```go
-// InterveneAction intervention action
-type InterveneAction string
-
-const (
- InterveneAdjustGoal InterveneAction = "adjust_goal" // Adjust goal
- InterveneAddTask InterveneAction = "add_task" // Add task
- InterveneCancelTask InterveneAction = "cancel_task" // Cancel task
- IntervenePause InterveneAction = "pause" // Pause
- InterveneResume InterveneAction = "resume" // Resume
- InterveneAbort InterveneAction = "abort" // Abort
- IntervenePlan InterveneAction = "plan" // Queue for later plan
-)
-
-// InterveneInput intervention input content
-type InterveneInput struct {
- Action InterveneAction `json:"action"`
- TargetID string `json:"target_id,omitempty"` // Goal/task ID
- Description string `json:"description"` // Intervention description
- Data map[string]interface{} `json:"data,omitempty"` // Additional data
- ScheduleAt *time.Time `json:"schedule_at,omitempty"` // Scheduled execution time
-}
-```
-
-## Event Trigger Mechanism
-
-Besides scheduled triggers, supports multiple event sources to trigger Agent execution.
-
-### Event Sources
-
-```go
-// EventSource event source configuration
-type EventSource struct {
- Type string `json:"type"` // webhook | database | mq | system
- Config map[string]interface{} `json:"config"`
- Filter *EventFilter `json:"filter"` // Event filter conditions
- Mapping *EventMapping `json:"mapping"` // Event to input mapping
-}
-
-// EventFilter event filter
-type EventFilter struct {
- EventTypes []string `json:"event_types"` // Subscribed event types
- Conditions map[string]interface{} `json:"conditions"` // Filter conditions
-}
-```
-
-### Configuration Example
+### Trigger Config
```yaml
-agent_config:
- # ... other config ...
-
- # Input configuration
- input:
- isolation:
- queue_size: 100
- enable_rate_limit: true
- rate_per_minute: 10
-
- strategies:
- schedule:
- enabled: true
- priority: 5
- action: "immediate"
-
- intervene:
- enabled: true
- priority: 10 # Highest priority
- action: "immediate"
-
- event:
- enabled: true
- priority: 7
- action: "queue"
-
- # Event source configuration
- event_sources:
- - type: "webhook"
- config:
- endpoint: "/webhook/agent/{agent_id}"
- filter:
- event_types: ["order.created", "customer.feedback"]
-
- - type: "database"
- config:
- table: "sales_orders"
- trigger: "insert"
- filter:
- conditions:
- amount: { "$gt": 10000 }
+triggers:
+ schedule: { enabled: true }
+ intervene: { enabled: true, actions: [...] }
+ event: { enabled: false }
```
-## Plan Queue
-
-Supports queuing tasks for later plans, enabling delayed execution and batch processing.
-
-### Plan Queue Structure
-
-```go
-// PlanQueue plan queue
-type PlanQueue struct {
- AgentID string `json:"agent_id"`
- Items []PlanItem `json:"items"`
-}
-
-// PlanItem plan item
-type PlanItem struct {
- ID string `json:"id"`
- Type string `json:"type"` // goal | task | input
- Content interface{} `json:"content"`
- Priority int `json:"priority"`
- ScheduleAt *time.Time `json:"schedule_at"` // nil means process on next execution
- Source string `json:"source"` // Source (intervene, event)
- CreatedAt time.Time `json:"created_at"`
- Status string `json:"status"` // pending | processed | cancelled
-}
-```
-
-### Plan Processing
-
-Before Phase 1 (Goal Generation), check the plan queue:
-
-```
-Execution Start
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Phase 0: Plan Processing β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β 1. Check due items in plan queue β β
-β β 2. Sort by priority β β
-β β 3. Merge into current execution: β β
-β β β’ goal type β Inject into goal generation β β
-β β β’ task type β Add directly to task list β β
-β β β’ input type β Process as additional input β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-Phase 1: Goal Generation
- β
- ...
-```
-
-## Integration with Job System (Activity Monitor)
-
-Autonomous Agent task execution is based on the existing Job framework (`yao/job`), reusing its complete task scheduling, execution monitoring, and logging capabilities, with visual management through the **Activity Monitor** UI.
-
-### Job System Architecture
-
-```
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Activity Monitor β
-β (UI Dashboard) β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β β’ Task list and status β β
-β β β’ Real-time progress tracking β β
-β β β’ Execution log viewing β β
-β β β’ Cancel/pause/retry operations β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Job Framework (yao/job) β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β β’ Job: Task definition (once/cron/daemon) β β
-β β β’ Execution: Execution instance (supports parent-child) β β
-β β β’ Worker: Executor (goroutine/process) β β
-β β β’ Log: Multi-level execution logs β β
-β β β’ Progress: Real-time progress tracking β β
-β β β’ Health: Health check β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β Autonomous Agent Executor β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-β β Phase 0 β Phase 1 β Phase 2 β Phase 3 β Phase 4 β Phase 5β β
-β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-```
-
-### Agent Execution Mapping to Job
-
-Each Autonomous Agent corresponds to a Job, each execution cycle corresponds to an Execution:
-
-```go
-// Create Job corresponding to Agent
-func createAgentJob(agent *AutonomousAgent) (*job.Job, error) {
- jobData := map[string]interface{}{
- "name": fmt.Sprintf("Agent: %s", agent.AgentID),
- "description": fmt.Sprintf("Autonomous Agent for team %s", agent.TeamID),
- "category_id": "autonomous_agent",
- "__yao_team_id": agent.TeamID,
- }
-
- var j *job.Job
- var err error
-
- switch agent.Config.Schedule.Type {
- case "cron":
- j, err = job.CronAndSave(job.GOROUTINE, jobData, agent.Config.Schedule.Expression)
- case "daemon":
- j, err = job.DaemonAndSave(job.GOROUTINE, jobData)
- default:
- j, err = job.OnceAndSave(job.GOROUTINE, jobData)
- }
-
- if err != nil {
- return nil, err
- }
-
- // Associate Agent configuration
- j.SetConfig(map[string]interface{}{
- "agent_id": agent.AgentID,
- "team_id": agent.TeamID,
- "agent_config": agent.Config,
- })
-
- return j, nil
-}
-```
-
-### Execution and Execution Phases
-
-Each Execution runs the complete Agent cycle, tracking each phase via Progress and Log:
-
-```go
-// Agent execution function (registered to Job)
-func agentExecutionHandler(ctx *job.ExecutionContext) error {
- execution := ctx.Execution
- agentConfig := ctx.Args["agent_config"].(*AgentConfig)
-
- // Phase 0: Plan Processing
- execution.Info("Phase 0: Processing plan queue")
- execution.SetProgress(5, "Processing pending plans...")
- processPlanQueue(ctx, agentConfig)
-
- // Phase 1: Goal Generation
- execution.Info("Phase 1: Generating goals")
- execution.SetProgress(15, "Generating goals...")
- goals, err := generateGoals(ctx, agentConfig)
- if err != nil {
- execution.Error("Goal generation failed: %v", err)
- return err
- }
-
- // Phase 2: Task Decomposition
- execution.Info("Phase 2: Decomposing tasks")
- execution.SetProgress(30, "Decomposing tasks...")
- tasks, err := decomposeTasks(ctx, agentConfig, goals)
- if err != nil {
- execution.Error("Task decomposition failed: %v", err)
- return err
- }
-
- // Phase 3: Task Execution (create child Execution for each task)
- execution.Info("Phase 3: Executing %d tasks", len(tasks))
- for i, task := range tasks {
- progress := 30 + (50 * (i + 1) / len(tasks))
- execution.SetProgress(progress, fmt.Sprintf("Task %d/%d: %s", i+1, len(tasks), task.Description))
- executeTaskWithChildExecution(ctx, execution, agentConfig, &task)
- }
-
- // Phase 4: Delivery
- execution.Info("Phase 4: Delivering results")
- execution.SetProgress(85, "Generating deliverables...")
- deliver(ctx, agentConfig, tasks)
-
- // Phase 5: Learning
- execution.Info("Phase 5: Learning from execution")
- execution.SetProgress(95, "Updating knowledge base...")
- learn(ctx, agentConfig, goals, tasks)
-
- execution.SetProgress(100, "Completed")
- return nil
-}
-```
-
-### Child Task Tracking (Parent-Child Execution)
-
-Each task in Agent execution creates a child Execution, expandable in the Activity Monitor:
-
-```go
-// Create child Execution for Agent task
-func executeTaskWithChildExecution(ctx *job.ExecutionContext, parent *job.Execution, config *AgentConfig, task *Task) error {
- // Create child Execution
- childExec := &job.Execution{
- JobID: parent.JobID,
- ParentExecutionID: &parent.ExecutionID,
- Status: "running",
- TriggerCategory: "agent_task",
- ExecutionConfig: &job.ExecutionConfig{
- Type: job.ExecutionTypeFunc,
- FuncID: fmt.Sprintf("task_%s", task.ID),
- FuncName: task.Description,
- },
- }
- job.SaveExecution(childExec)
-
- // Execute task
- childExec.Info("Starting task: %s", task.Description)
- err := executeTask(ctx, config, task)
-
- // Update child Execution status
- if err != nil {
- childExec.Status = "failed"
- childExec.Error("Task failed: %v", err)
- } else {
- childExec.Status = "completed"
- childExec.Info("Task completed successfully")
- }
- job.SaveExecution(childExec)
-
- return err
-}
-```
-
-### Activity Monitor Features
-
-Via Job API (`yao/openapi/job`), the Activity Monitor provides:
-
-| Feature | API | Description |
-| ------------------ | ------------------------------------------------ | -------------------------- |
-| Agent task list | `GET /api/jobs?category_id=autonomous_agent` | View all Agent Jobs |
-| Execution history | `GET /api/jobs/:job_id/executions` | View execution history |
-| Real-time progress | `GET /api/jobs/:job_id/executions/:id` | View current progress |
-| Execution logs | `GET /api/jobs/:job_id/executions/:id/logs` | View detailed logs |
-| Expand child tasks | `GET /api/jobs/:job_id/executions?parent_id=:id` | View child tasks |
-| Cancel execution | `POST /api/jobs/:job_id/stop` | Cancel running task |
-| Manual trigger | `POST /api/jobs/:job_id/trigger` | Manually trigger execution |
-
-### Log Levels
-
-Agent execution logs map to Job log levels:
-
-```go
-// Log level mapping
-execution.Debug("Detailed debug info") // Debug
-execution.Info("Phase start/complete") // Info
-execution.Warn("Non-fatal warning") // Warn
-execution.Error("Error, interrupt execution") // Error
-```
-
-### Job Configuration
+### Phase Agents
```yaml
-agent_config:
- # ... other config ...
-
- # Job execution configuration
- job:
- mode: "goroutine" # goroutine | process
- max_worker_nums: 1 # Max concurrent executions
- max_retry_count: 3 # Max retry count
- default_timeout: 1800 # Default timeout (seconds)
- priority: 5 # Execution priority (affects queue sorting)
+resources:
+ p0: "__yao.inspiration" # Inspiration
+ p1: "__yao.goal-gen" # Goal Generator
+ p2: "__yao.task-plan" # Task Planner
+ p3: "__yao.validator" # Validator
+ p4: "__yao.delivery" # Delivery
+ p5: "__yao.learning" # Learning
```
-## Complete Config Structure
+### Quota
-```go
-// Config AI member complete configuration
-type Config struct {
- Triggers *Triggers `json:"triggers,omitempty"` // Trigger sources (all enabled by default)
- Schedule *Schedule `json:"schedule,omitempty"` // Timing config
- Identity *Identity `json:"identity"` // Role & duties
- Quota *Quota `json:"quota"` // Concurrency quota
- PrivateKB *KB `json:"private_kb"` // Private KB
- SharedKB *KB `json:"shared_kb,omitempty"` // Shared KB refs
- Resources *Resources `json:"resources"` // Agents & tools
- Delivery *Delivery `json:"delivery"` // Output config
- Input *Input `json:"input,omitempty"` // Input isolation
- Events []Event `json:"events,omitempty"` // Event sources
- Monitor *Monitor `json:"monitor,omitempty"` // Monitoring
-}
-
-// Triggers trigger sources (all enabled by default)
-type Triggers struct {
- Schedule *Trigger `json:"schedule,omitempty"`
- Intervene *Trigger `json:"intervene,omitempty"`
- Event *Trigger `json:"event,omitempty"`
-}
-
-// Trigger single trigger config
-type Trigger struct {
- Enabled bool `json:"enabled"`
- Actions []string `json:"actions,omitempty"` // For intervene only
-}
-
-// Monitor monitoring config
-type Monitor struct {
- On bool `json:"on"`
- Alerts []Alert `json:"alerts,omitempty"`
-}
-
-// Alert rule definition
-type Alert struct {
- Name string `json:"name"` // Rule name
- When string `json:"when"` // failed | timeout | error_rate
- Value float64 `json:"value"` // Threshold
- Window string `json:"window"` // 1h | 24h
- Do []Action `json:"do"` // Actions
- Cooldown string `json:"cooldown"` // Cooldown period
-}
-
-// Action alert action
-type Action struct {
- Type string `json:"type"` // email | webhook | notify
- Opts map[string]interface{} `json:"opts"`
-}
+```yaml
+quota:
+ max: 2 # Max concurrent
+ queue: 10 # Queue size
+ priority: 5 # 1-10
+```
+
+### Schedule
+
+```yaml
+schedule:
+ type: cron # cron | interval
+ expr: "0 9 * * 1-5" # Cron or duration
+ tz: Asia/Shanghai
+ timeout: 30m
```