mirror of
https://github.com/sipeed/picoclaw.git
synced 2026-06-12 18:08:54 +00:00
refactor(agent): Agent Looper refactor phase2, restructure pipeline and rename loop files to agent (#2585)
* refactor(agent): introduce interfaces for MessageBus and ChannelManager Phase 2 of loop.go refactor — dependency inversion using adapter pattern. - Add interfaces.MessageBus and interfaces.ChannelManager interfaces - Create adapters/messagebus.go wrapping *bus.MessageBus - Create adapters/channelmanager.go wrapping *channels.Manager - Update AgentLoop to use interfaces instead of concrete types - Update registerSharedTools to accept interfaces.MessageBus Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor(agent): restructure pipeline and rename loop files Pipeline refactoring: - Split pipeline.go (1400 lines) into focused files: - pipeline_setup.go (~115 lines): SetupTurn method - pipeline_llm.go (~519 lines): CallLLM method - pipeline_execute.go (~693 lines): ExecuteTools method - pipeline_finalize.go (~78 lines): Finalize method - Pipeline struct and NewPipeline remain in pipeline.go (~39 lines) Agent file renaming: - Rename loop_*.go to agent_*.go for consistent naming: - loop.go -> agent.go, loop_message.go -> agent_message.go, etc. - Merge turn.go + turn_exec.go into turn_state.go - Rename loop_turn.go -> turn_coord.go Documentation: - Update docs/pipeline-restructuring-plan.md - Add docs/agent-rename-plan.md Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(agent): code format fixed * refactor(agent): code test file added/renamed * docs(agent): update agent refactor docs * fix(agent): fix agent hardAbortX --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
# AgentLoop File Split
|
||||
|
||||
> **Note:** This document describes the file split that was completed in a previous phase. The `loop_*` naming has since been renamed to `agent_*` and `turn_*`. See [agent-rename-plan.md](./agent-rename-plan.md) for the current file structure.
|
||||
|
||||
## Overview
|
||||
|
||||
The `pkg/agent/loop.go` file (originally 4384 lines) has been split into 12 focused source files. This is a pure refactoring with no behavioral changes.
|
||||
@@ -11,76 +13,65 @@ The `pkg/agent/loop.go` file (originally 4384 lines) has been split into 12 focu
|
||||
- Maintain all existing functionality and tests
|
||||
- Keep imports minimal per file
|
||||
|
||||
## File Map
|
||||
## Original File Map (Renamed in Phase 2)
|
||||
|
||||
| File | Lines | Responsibility |
|
||||
|------|-------|----------------|
|
||||
| `loop.go` | ~650 | Core `AgentLoop` struct, `Run`, `Stop`, `Close`, `ReloadProviderAndConfig`, `runAgentLoop` |
|
||||
| `loop_turn.go` | ~1880 | Turn execution: `runTurn`, `abortTurn`, `selectCandidates`, `askSideQuestion`, `isolatedSideQuestionProvider`, side question model config |
|
||||
| `loop_utils.go` | ~480 | Standalone utility functions: formatters, cloners, helpers (no receiver) |
|
||||
| `loop_init.go` | ~355 | `NewAgentLoop` constructor and `registerSharedTools` |
|
||||
| `loop_message.go` | ~300 | Message handling: `processMessage`, `processSystemMessage`, routing helpers, `ProcessDirect`, `ProcessHeartbeat` |
|
||||
| `loop_command.go` | ~265 | Command processing: `handleCommand`, `applyExplicitSkillCommand`, pending skills management |
|
||||
| `loop_mcp.go` | ~235 | MCP runtime: `ensureMCPInitialized`, server discovery, deferred server handling |
|
||||
| `loop_event.go` | ~205 | Event system helpers: `emitEvent`, `logEvent`, `hookAbortError`, `newTurnEventScope`, `MountHook`, `SubscribeEvents` |
|
||||
| `loop_media.go` | ~198 | Media resolution: `resolveMediaRefs`, artifact building, MIME detection |
|
||||
| `loop_outbound.go` | ~165 | Response publishing: `PublishResponseIfNeeded`, `publishPicoReasoning`, `handleReasoning` |
|
||||
| `loop_transcribe.go` | ~110 | Audio transcription: `transcribeAudioInMessage`, `sendTranscriptionFeedback` |
|
||||
| `loop_steering.go` | ~97 | Steering queue: `runTurnWithSteering`, `processMessageSync`, `resolveSteeringTarget` |
|
||||
| `loop_inject.go` | ~104 | Setter injection: `SetChannelManager`, `SetMediaStore`, `SetTranscriber`, `GetRegistry`, `GetConfig`, `RecordLastChannel` |
|
||||
| Old File | New File | Responsibility |
|
||||
|----------|----------|----------------|
|
||||
| `loop.go` | `agent.go` | Core `AgentLoop` struct, `Run`, `Stop`, `Close` |
|
||||
| `loop_turn.go` | `turn_coord.go` + `pipeline_*.go` | Turn execution: coordinator + Pipeline methods |
|
||||
| `loop_utils.go` | `agent_utils.go` | Standalone utility functions |
|
||||
| `loop_init.go` | `agent_init.go` | `NewAgentLoop` constructor and tool registration |
|
||||
| `loop_message.go` | `agent_message.go` | Message handling and routing |
|
||||
| `loop_command.go` | `agent_command.go` | Command processing |
|
||||
| `loop_mcp.go` | `agent_mcp.go` | MCP runtime |
|
||||
| `loop_event.go` | `agent_event.go` | Event system helpers |
|
||||
| `loop_media.go` | `agent_media.go` | Media resolution |
|
||||
| `loop_outbound.go` | `agent_outbound.go` | Response publishing |
|
||||
| `loop_transcribe.go` | `agent_transcribe.go` | Audio transcription |
|
||||
| `loop_steering.go` | `agent_steering.go` | Steering queue |
|
||||
| `loop_inject.go` | `agent_inject.go` | Setter injection |
|
||||
|
||||
## Current File Structure
|
||||
|
||||
See [agent-rename-plan.md](./agent-rename-plan.md) for the complete current file structure.
|
||||
|
||||
## Phase 2: Rename and Pipeline Restructuring
|
||||
|
||||
Phase 2 completed the following:
|
||||
|
||||
1. **File renaming**: All `loop_*` files renamed to `agent_*` or `turn_*`
|
||||
2. **Turn state merging**: `turn.go` + `turn_exec.go` → `turn_state.go`
|
||||
3. **Pipeline extraction**: Split large `runTurn` into Pipeline methods
|
||||
|
||||
### Pipeline Architecture
|
||||
|
||||
The Pipeline methods provide structured turn execution:
|
||||
|
||||
| Method | File | Responsibility |
|
||||
|--------|------|----------------|
|
||||
| `SetupTurn()` | `pipeline_setup.go` | History assembly, message building, candidate selection |
|
||||
| `CallLLM()` | `pipeline_llm.go` | PreLLM hooks, fallback, retry, AfterLLM hooks |
|
||||
| `ExecuteTools()` | `pipeline_execute.go` | Tool execution with hooks |
|
||||
| `Finalize()` | `pipeline_finalize.go` | Session persistence, compression |
|
||||
|
||||
## Core Principles Applied
|
||||
|
||||
### 1. Same Package, Independent Files
|
||||
All files belong to the `agent` package and compile together. This preserves the original visibility rules — no interface abstraction was introduced in this phase.
|
||||
All files belong to the `agent` package and compile together. This preserves the original visibility rules.
|
||||
|
||||
### 2. No Logic Changes
|
||||
All functions were moved verbatim (except updating import statements). The extraction script used the original `loop.go.backup` as source of truth to ensure no drift.
|
||||
All functions were moved verbatim. The extraction preserved behavioral equivalence.
|
||||
|
||||
### 3. Shared Types Remain in loop.go
|
||||
The `AgentLoop` struct, `processOptions`, `continuationTarget`, and all hook/event types stay in `loop.go` since they are referenced across files.
|
||||
|
||||
### 4. Turn State Is Central
|
||||
`loop_turn.go` is the largest file because the turn lifecycle (`runTurn`) is inherently large. It contains the core LLM interaction loop, tool execution, subturn spawning, and steering injection.
|
||||
|
||||
## What's Left in loop.go
|
||||
|
||||
```go
|
||||
// Core struct
|
||||
type AgentLoop struct { ... }
|
||||
|
||||
// Main lifecycle
|
||||
func (al *AgentLoop) Run(ctx context.Context) error
|
||||
func (al *AgentLoop) Stop()
|
||||
func (al *AgentLoop) Close()
|
||||
func (al *AgentLoop) ReloadProviderAndConfig(ctx, provider, cfg)
|
||||
|
||||
// Turn orchestration (calls into loop_turn.go)
|
||||
func (al *AgentLoop) runAgentLoop(ctx, agent, opts) (string, error)
|
||||
```
|
||||
|
||||
## Extraction Method
|
||||
|
||||
The split was done programmatically using Node.js to:
|
||||
1. Identify function boundaries using brace counting
|
||||
2. Extract each function to its target file
|
||||
3. Add necessary imports to each file
|
||||
4. Remove the extracted function from loop.go
|
||||
5. Run `go fmt` and `go vet` to verify
|
||||
### 3. Shared Types in turn_state.go
|
||||
The `turnState`, `turnExecution`, `Control`, `ToolControl`, and `LLMPhase` types are centralized in `turn_state.go`.
|
||||
|
||||
## Testing
|
||||
|
||||
All existing tests pass. The 5 failing tests (`TestGlobalSkillFileContentChange` and 4 Seahorse tests) are pre-existing failures unrelated to this refactor (database file locking issues on Windows).
|
||||
All existing tests pass. The 5 failing tests (`TestGlobalSkillFileContentChange` and 4 Seahorse tests) are pre-existing failures unrelated to this refactor.
|
||||
|
||||
Build status: `go build ./pkg/agent/...` passes with no errors.
|
||||
|
||||
## Phase 2: Dependency Inversion (Planned)
|
||||
|
||||
A future phase will introduce interface types to decouple `AgentLoop` from its dependencies, enabling:
|
||||
- Easier testing with mock dependencies
|
||||
- Alternative runtime configurations
|
||||
- Cleaner boundaries for MCP and other extensions
|
||||
|
||||
## See Also
|
||||
|
||||
- [agent-rename-plan.md](./agent-rename-plan.md) — Current file naming convention
|
||||
- [context.md](context.md) — context management and session handling
|
||||
|
||||
Reference in New Issue
Block a user