feat(tools): restore and enhance team tool with SubTurn integration#1940
feat(tools): restore and enhance team tool with SubTurn integration#1940lppp04808 wants to merge 11 commits intosipeed:mainfrom
Conversation
- Add team.go (947 lines) with complete team coordination features - Add spawn_sub_agent.go for sub-agent spawning - Add team_test.go with comprehensive test coverage - Update subagent.go: add teamConfig and bus fields - Update loop.go: fix NewSubagentManager calls with new signature - Update filesystem.go: add ConcurrentFS, EditFile, and Open methods - Update config.go: add TeamToolsConfig and LogLevel documentation - Update toolloop.go: merge context memory fixes - Fix all test files to use updated NewSubagentManager signature All tests passing, build successful.
- Add team.go (947 lines) with complete team coordination features - Add spawn_sub_agent.go for sub-agent spawning - Add team_test.go with comprehensive test coverage - Update subagent.go: add teamConfig and bus fields - Update loop.go: fix NewSubagentManager calls with new signature - Update filesystem.go: add ConcurrentFS, EditFile, and Open methods - Update config.go: add TeamToolsConfig and LogLevel documentation - Update toolloop.go: merge context memory fixes - Fix all test files to use updated NewSubagentManager signature All tests passing, build successful.
…mprove message handling
1 Core Components2 Detailed Explanation of Four Execution Strategies
Team Execution StrategiesThe 1. sequentialLinear execution of team members in defined order. 2. parallelAll members execute concurrently (no dependencies). 3. DAG (Directed Acyclic Graph)Complex dependency-driven workflows with parallel branches and convergence points. Key Features of DAG Strategy
4. evaluator_optimizerStateful iterative self-refinement loop (inspired by o1-style reasoning). Key Features of Evaluator Optimizer Strategy
These strategies make the restored team tool production-ready for both simple linear tasks See:
2.1 evaluator_optimizer Strategy// State persistence: Worker's message history is preserved across iterations
workerMessages := []providers.Message{
{Role: "system", Content: worker.Role},
{Role: "user", Content: worker.Task},
}
// After each iteration:
if workerMsgs != nil {
workerMessages = workerMsgs // Update state for next loop
}This is the most complex strategy:
3 Configuration Structuretype TeamToolsConfig struct {
MaxMembers int // Maximum number of members
MaxTeamTokens int // Token budget limit
MaxEvaluatorLoops int // Max evaluator loop count (default: 5)
MaxTimeoutMinutes int // Timeout duration
DisableAutoReviewer bool // Disable automatic reviewer
ReviewerModel string // Model used for reviewer
AllowedStrategies []string // Allowed strategies
AllowedModels []TeamModelConfig // Allowed model list
}4 Concurrency-Safe Design4.1 ConcurrentFS Mechanism// ConcurrentFS wraps any fileSystem with global per-path locking
type ConcurrentFS struct {
baseFS fileSystem
// Note: No embedded mutex. Uses global getPathLock(path) instead.
}
// Global lock map for file paths
var globalPathLocks sync.Map // path -> *sync.RWMutex
func getPathLock(path string) *sync.RWMutex {
actual, _ := globalPathLocks.LoadOrStore(path, &sync.RWMutex{})
return actual.(*sync.RWMutex)
}
// Example: ReadFile acquires read lock
func (c *ConcurrentFS) ReadFile(path string) ([]byte, error) {
lock := getPathLock(path)
lock.RLock()
defer lock.RUnlock()
return c.baseFS.ReadFile(path)
}
// Example: WriteFile acquires write lock
func (c *ConcurrentFS) WriteFile(path string, data []byte) error {
lock := getPathLock(path)
lock.Lock()
defer lock.Unlock()
return c.baseFS.WriteFile(path, data)
}Tool Upgrade Interfacetype ConcurrencyUpgradeable interface {
UpgradeToConcurrent() Tool
}When the strategy is parallel or dag, file tools are automatically upgraded:
Note: 5 Automatic QA Reviewervar reviewerTaskTemplates = map[string]string{
"code": "Check syntax errors, import issues, logic errors...",
"data": "Check format, field completeness, schema consistency...",
"document": "Check logical consistency, completeness, structure quality...",
}When team members declare The reviewer:
6 Key Implementation Details6.1 DAG Execution Flow
6.2 Context Passing in DAG// Shared context map for passing results between dependencies
contextMap := make(map[string]*strings.Builder)
var contextMu sync.Mutex
// When a node completes, append its result to all dependents
for _, dependentID := range graph[res.id] {
contextMu.Lock()
b := contextMap[dependentID]
if b == nil {
b = &strings.Builder{}
}
b.WriteString(fmt.Sprintf("--- Result from [%s] ---\n%s\n\n", res.id, res.res))
contextMap[dependentID] = b
contextMu.Unlock()
inDegree[dependentID]--
if inDegree[dependentID] == 0 {
readyChan <- dependentID
}
}6.3 Evaluator-Optimizer Loopfor attempt := 1; attempt <= maxLoops; attempt++ {
// 1. Worker executes with full state
workerContent, workerMsgs, err := t.spawnWorker(ctx, workerConfig, workerMessages, budget)
// 2. Save worker's state for next iteration
if workerMsgs != nil {
workerMessages = workerMsgs
}
// 3. Evaluator reviews (no tools, stateless)
evalContext := fmt.Sprintf("%s\n\n--- Worker's Output ---\n%s\n\nIf correct, reply with '[PASS]'",
evaluator.Task, workerContent)
evalContent, _, err := t.spawnWorker(ctx, evalConfig, evalMessages, budget)
// 4. Check for [PASS]
if strings.HasPrefix(strings.TrimSpace(evalContent), "[PASS]") {
return success
}
// 5. Append evaluator feedback to worker's memory
workerMessages = append(workerMessages,
providers.Message{Role: "user", Content: "Evaluator feedback: " + evalContent})
}7 Summary of CorrectionsThis document corrects the following errors from the original:
Verified correct claims:
|
Team Tool Configuration GuideThe Configuration LocationSettings are located in Comprehensive Example{
"tools": {
"team": {
"enabled": true,
"max_members": 5,
"max_team_tokens": 100000,
"max_evaluator_loops": 3,
"max_timeout_minutes": 20,
"max_context_runes": 8000,
"disable_auto_reviewer": false,
"reviewer_model": "gpt-4o-mini",
"allowed_strategies": [
"sequential",
"parallel",
"dag",
"evaluator_optimizer"
],
"allowed_models": [
{
"name": "gpt-4o",
"tags": ["vision", "code", "reasoning"]
},
{
"name": "claude-3-5-sonnet",
"tags": ["coding", "precise"]
}
]
}
}
}Field Reference
Feature Highlights1. Robust ParallelismIn Parallel mode, if some workers fail while others succeed, the tool returns Partial Success. Successful results are preserved, and failures are summarized separately so the coordinator can decide how to proceed. 2. Context TruncationTo prevent "Token Bombs," the tool automatically truncates long outputs when injecting them as dependencies/context for downstream workers. You can tune this via 3. Dedicated QA ReviewerThe Auto-Reviewer automatically validates artifacts like code or documentation. By setting 4. DAG Pipeline safetyThe DAG strategy implements Cycle Detection (Kahn's Algorithm). If the LLM proposes a circular dependency, the tool will intercept and report it as an error before wasting tokens. |
Fixed formatting issues in three files to comply with golines requirements: - pkg/agent/loop.go: Split long function calls and logger statements - pkg/config/config.go: Align struct field tags - pkg/tools/toolloop.go: Split long function calls Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Fixed formatting issues in three files to comply with golines requirements: - pkg/agent/loop.go: Split long function calls and logger statements - pkg/config/config.go: Align struct field tags - pkg/tools/toolloop.go: Split long function calls Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Split long line in Chat() call to meet 120 character limit. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
📝 Description
Summary
Restores the team coordination tool from #976 and integrates it with the new SubTurn mechanism from Phase 1 agent refactor.
Implements #1934 (partial - task coordination aspect)
Supersedes #976
Context
The original team tool (#976) was developed before the Phase 1 agent refactor. This PR:
RunToolLoopcalls withSubTurnSpawnerinterfaceKey Changes from #976
SetSpawner()method for dependency injectionspawnWorker()abstraction with fallback supportConcurrentFSFeatures (from original #976)
Testing
Migration Notes
This implementation focuses on task coordination (explicit collaboration). The agent discovery and implicit collaboration aspects from #1934 are deferred to future work.
🗣️ Type of Change
🤖 AI Code Generation
🔗 Related Issue
📚 Technical Context (Skip for Docs)
🧪 Test Environment
📸 Evidence (Optional)
Click to view Logs/Screenshots
☑️ Checklist