package evolve // engine_integration.go defines the intended bridge between Evolver and the // main Engine. Three built-in tools live here (CreateTool / LearnSkill / // Reflect) plus the system-prompt fragment describing self-evolution to the // model. // // Status (2026-04-21): the adapter that would register these three tools and // the Agent-authored RuntimeTool instances into Engine's tool registry is NOT // wired in core. The Evolver type exposes ToolBuilder() / SkillLearner() / // Reflector() / History() getters, but no EngineTools() enumerator and no // engine.Tools().Register() call-site exists anywhere in core/. Consumers // currently must construct and register these tools themselves. // // Rationale for the gap: the "Agent creates its own tools at runtime" path // (C-plan) is on the roadmap but deferred. Subagents / skill library / memory // already cover the "reusable capability accumulation" need for current // products. C-plan's unique value lands when a long-running industry platform // (logistics / erp) repeatedly hits the same operational shape and wants the // muscle memory exposed as a first-class tool the model sees in its tool // list. Revisit when such a workload surfaces. // // engine_integration.go 定义 Evolver 与主 Engine 的预期桥接. 本文件里 3 个 // 内置工具 (CreateTool / LearnSkill / Reflect) + 系统提示词片段是 C 方案 // (Agent 运行时自造工具) 的前端部分. // // 现状 (2026-04-21): core 里没有把这 3 个工具 + Agent 动态生成的 // RuntimeTool 注册进 Engine.Tools() 的适配器. Evolver 只暴露 // ToolBuilder()/SkillLearner()/Reflector()/History() 这几个 getter, 没有 // EngineTools() 枚举器也没有注册调用点. 消费方如需启用需自行构造注册. // // 缺口原因: C 方案 "Agent 自己写工具" 路线在路线图里但延后 -- subagent / // skill 库 / memory 三路已经覆盖当前产品的 "能力沉淀" 需求. C 方案独有价值 // 在行业 platform (logistics / erp) 长期跑相似运维动作时显现 (把"肌肉记忆" // 提到工具面板, 模型扫一眼就知道自己会这招). 等真实业务场景触发再接. import ( "context" "encoding/json" "fmt" ) // --- 暴露给 Agent 的 3 个进化工具 --- // CreateToolTool 是"创建新工具"的工具. // Agent 调用此工具来定义一个新的运行时工具. type CreateToolTool struct { evolver *Evolver cwd string } // NewCreateToolTool 创建 CreateTool 工具. func NewCreateToolTool(evolver *Evolver, cwd string) *CreateToolTool { return &CreateToolTool{evolver: evolver, cwd: cwd} } func (t *CreateToolTool) Name() string { return "CreateTool" } func (t *CreateToolTool) Description(ctx context.Context) string { return "Create a new runtime tool. Use this when existing tools cannot solve the current problem. " + "You define the tool's name, description, input schema, and execution script. " + "The tool will be available immediately after creation and persisted for future sessions." } func (t *CreateToolTool) InputSchema() json.RawMessage { return json.RawMessage(`{ "type": "object", "properties": { "name": { "type": "string", "description": "Unique tool name (no spaces, must not conflict with built-in tools)" }, "description": { "type": "string", "description": "What this tool does (shown to the model)" }, "input_schema": { "type": "object", "description": "JSON Schema defining the tool's input parameters" }, "script": { "type": "string", "description": "Bash script to execute. Input params are available as TOOL_INPUT_ env vars" }, "rationale": { "type": "string", "description": "Why you need this tool (for audit trail)" }, "read_only": { "type": "boolean", "description": "Whether this tool only reads data (no side effects)" } }, "required": ["name", "description", "input_schema", "script", "rationale"] }`) } func (t *CreateToolTool) Execute(ctx context.Context, input json.RawMessage, progress func(float64, string)) (*ToolResult, error) { var req struct { Name string `json:"name"` Description string `json:"description"` InputSchema json.RawMessage `json:"input_schema"` Script string `json:"script"` Rationale string `json:"rationale"` ReadOnly bool `json:"read_only"` } if err := json.Unmarshal(input, &req); err != nil { return &ToolResult{Output: "invalid input: " + err.Error(), IsError: true}, nil } def := &ToolDefinition{ Name: req.Name, Description: req.Description, InputSchema: req.InputSchema, ExecutionType: ExecScript, Script: req.Script, Rationale: req.Rationale, ReadOnly: req.ReadOnly, ConcurrencySafe: req.ReadOnly, // 只读工具默认可并发 Version: 1, } proposal := &EvolutionProposal{ Type: EvolveNewTool, Title: fmt.Sprintf("Create tool: %s", req.Name), Description: req.Description, Rationale: req.Rationale, Content: def, } if err := t.evolver.Propose(ctx, proposal); err != nil { return &ToolResult{Output: "failed to create tool: " + err.Error(), IsError: true}, nil } if proposal.Status == StatusRejected { return &ToolResult{Output: "tool creation was rejected by the user", IsError: true}, nil } return &ToolResult{ Output: fmt.Sprintf("Tool '%s' created successfully. It is now available for use.", req.Name), }, nil } // LearnSkillTool 是"学习新技能"的工具. type LearnSkillTool struct { evolver *Evolver } // NewLearnSkillTool 创建 LearnSkill 工具. func NewLearnSkillTool(evolver *Evolver) *LearnSkillTool { return &LearnSkillTool{evolver: evolver} } func (t *LearnSkillTool) Name() string { return "LearnSkill" } func (t *LearnSkillTool) Description(ctx context.Context) string { return "Save a successful workflow as a reusable skill. Use this after completing a complex task " + "to capture the approach for future similar tasks. Include the steps, tools used, and key decisions." } func (t *LearnSkillTool) InputSchema() json.RawMessage { return json.RawMessage(`{ "type": "object", "properties": { "name": { "type": "string", "description": "Skill name" }, "description": { "type": "string", "description": "What this skill does" }, "when_to_use": { "type": "string", "description": "When should this skill be applied (triggers)" }, "prompt": { "type": "string", "description": "Full prompt template for this skill" }, "required_tools": { "type": "array", "items": {"type": "string"}, "description": "Tools needed for this skill" }, "tags": { "type": "array", "items": {"type": "string"}, "description": "Classification tags" } }, "required": ["name", "description", "when_to_use", "prompt"] }`) } func (t *LearnSkillTool) Execute(ctx context.Context, input json.RawMessage, progress func(float64, string)) (*ToolResult, error) { var req struct { Name string `json:"name"` Description string `json:"description"` WhenToUse string `json:"when_to_use"` Prompt string `json:"prompt"` RequiredTools []string `json:"required_tools"` Tags []string `json:"tags"` } if err := json.Unmarshal(input, &req); err != nil { return &ToolResult{Output: "invalid input: " + err.Error(), IsError: true}, nil } def := &SkillDefinition{ Name: req.Name, Description: req.Description, WhenToUse: req.WhenToUse, Prompt: req.Prompt, RequiredTools: req.RequiredTools, Tags: req.Tags, SuccessRate: 1.0, // 刚学会,假设成功率 100% Version: 1, } proposal := &EvolutionProposal{ Type: EvolveNewSkill, Title: fmt.Sprintf("Learn skill: %s", req.Name), Description: req.Description, Rationale: "Learned from successful task completion", Content: def, } if err := t.evolver.Propose(ctx, proposal); err != nil { return &ToolResult{Output: "failed to learn skill: " + err.Error(), IsError: true}, nil } return &ToolResult{ Output: fmt.Sprintf("Skill '%s' learned successfully. It will be available in future sessions.", req.Name), }, nil } // ReflectTool 是"自我反思"的工具. type ReflectTool struct { evolver *Evolver } // NewReflectTool 创建 Reflect 工具. func NewReflectTool(evolver *Evolver) *ReflectTool { return &ReflectTool{evolver: evolver} } func (t *ReflectTool) Name() string { return "Reflect" } func (t *ReflectTool) Description(ctx context.Context) string { return "Record a reflection about the current session. Use this to note patterns, lessons learned, " + "and suggestions for future improvement. Reflections are persisted and influence future behavior." } func (t *ReflectTool) InputSchema() json.RawMessage { return json.RawMessage(`{ "type": "object", "properties": { "summary": { "type": "string", "description": "Brief summary of the reflection" }, "observations": { "type": "array", "items": { "type": "object", "properties": { "pattern": {"type": "string"}, "impact": {"type": "string"} } }, "description": "Patterns observed" }, "lessons": { "type": "array", "items": {"type": "string"}, "description": "Lessons to remember for future sessions" } }, "required": ["summary"] }`) } func (t *ReflectTool) Execute(ctx context.Context, input json.RawMessage, progress func(float64, string)) (*ToolResult, error) { var req struct { Summary string `json:"summary"` Observations []struct { Pattern string `json:"pattern"` Impact string `json:"impact"` } `json:"observations"` Lessons []string `json:"lessons"` } if err := json.Unmarshal(input, &req); err != nil { return &ToolResult{Output: "invalid input: " + err.Error(), IsError: true}, nil } var observations []Observation for _, o := range req.Observations { observations = append(observations, Observation{ Pattern: o.Pattern, Impact: o.Impact, }) } var adjustments []Adjustment for _, lesson := range req.Lessons { adjustments = append(adjustments, Adjustment{ Type: AdjustLesson, Description: lesson, Suggestion: lesson, Priority: 3, }) } reflection := &Reflection{ ID: fmt.Sprintf("ref_%d", len(observations)), Type: ReflectPostSession, Summary: req.Summary, Observations: observations, Adjustments: adjustments, } proposal := &EvolutionProposal{ Type: EvolveSelfAdjust, Title: "Session reflection", Description: req.Summary, Rationale: "Self-improvement through reflection", Content: reflection, } if err := t.evolver.Propose(ctx, proposal); err != nil { return &ToolResult{Output: "failed to save reflection: " + err.Error(), IsError: true}, nil } return &ToolResult{ Output: fmt.Sprintf("Reflection saved. %d observations, %d lessons recorded.", len(observations), len(req.Lessons)), }, nil } // --- 系统提示词注入 --- // SystemPromptFragment 返回注入到系统提示中的进化能力说明. // 让 Agent 知道自己有创建工具,学习技能,自我反思的能力. func (e *Evolver) SystemPromptFragment() string { fragment := ` # Self-Evolution Capabilities You have the ability to evolve and improve yourself during and across sessions: ## CreateTool When existing tools cannot solve a problem, you can create a new tool at runtime. Define its name, input schema, and a bash script. The tool becomes immediately available. Use this sparingly — only when no existing tool combination can achieve the goal. ## LearnSkill After completing a complex task successfully, save the workflow as a reusable skill. Future sessions will see your learned skills and can apply them to similar problems. ## Reflect At the end of a session or after encountering difficulties, record your observations and lessons learned. These reflections will guide your behavior in future sessions. Important: All evolution actions require user approval. Be transparent about why you want to evolve and what the expected benefit is. ` // 追加已学习的技能 if skills, err := e.skillLearner.FormatForSystemPrompt(); err == nil && skills != "" { fragment += skills } // 追加历史教训 if lessons, err := e.reflector.FormatForSystemPrompt(); err == nil && lessons != "" { fragment += lessons } return fragment }