From 160b29a839967054376845c7036049e63d59cb32 Mon Sep 17 00:00:00 2001 From: harmoon Date: Sun, 5 Apr 2026 14:04:05 +0800 Subject: [PATCH] refactor(agent): improve completeness of tool result cloning and hook processing Extend cloneToolResult to properly copy ArtifactTags and Messages fields, ensuring deep copies of all ToolResult data. Consolidate event emission and user message handling to match the normal tool execution flow. --- pkg/agent/hooks.go | 7 +++++++ pkg/agent/loop.go | 34 +++++++++++++++++++--------------- 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/pkg/agent/hooks.go b/pkg/agent/hooks.go index 526a5356b..c23961dc6 100644 --- a/pkg/agent/hooks.go +++ b/pkg/agent/hooks.go @@ -800,6 +800,13 @@ func cloneToolResult(result *tools.ToolResult) *tools.ToolResult { if len(result.Media) > 0 { cloned.Media = append([]string(nil), result.Media...) } + if len(result.ArtifactTags) > 0 { + cloned.ArtifactTags = append([]string(nil), result.ArtifactTags...) + } + if len(result.Messages) > 0 { + cloned.Messages = make([]providers.Message, len(result.Messages)) + copy(cloned.Messages, result.Messages) + } return &cloned } diff --git a/pkg/agent/loop.go b/pkg/agent/loop.go index d4c534c64..28421680b 100644 --- a/pkg/agent/loop.go +++ b/pkg/agent/loop.go @@ -2389,22 +2389,12 @@ turnLoop: toolDuration := time.Duration(0) // Hook execution time unknown - // Emit ToolExecEnd event - al.emitEvent( - EventKindToolExecEnd, - ts.eventMeta("runTurn", "turn.tool.end"), - ToolExecEndPayload{ - Tool: toolName, - Duration: toolDuration, - ForLLMLen: len(hookResult.ContentForLLM()), - ForUserLen: len(hookResult.ForUser), - IsError: hookResult.IsError, - Async: hookResult.Async, - }, - ) - // Send ForUser content to user - if !hookResult.Silent && hookResult.ForUser != "" && ts.opts.SendResponse { + // For ResponseHandled results, send regardless of SendResponse setting, + // same as normal tool execution path. + shouldSendForUser := !hookResult.Silent && hookResult.ForUser != "" && + (ts.opts.SendResponse || hookResult.ResponseHandled) + if shouldSendForUser { al.bus.PublishOutbound(ctx, bus.OutboundMessage{ Channel: ts.channel, ChatID: ts.chatID, @@ -2476,6 +2466,20 @@ turnLoop: toolResultMsg.Media = append(toolResultMsg.Media, hookResult.Media...) } + // Emit ToolExecEnd event (after filtering, same as normal tool execution) + al.emitEvent( + EventKindToolExecEnd, + ts.eventMeta("runTurn", "turn.tool.end"), + ToolExecEndPayload{ + Tool: toolName, + Duration: toolDuration, + ForLLMLen: len(contentForLLM), + ForUserLen: len(hookResult.ForUser), + IsError: hookResult.IsError, + Async: hookResult.Async, + }, + ) + messages = append(messages, toolResultMsg) if !ts.opts.NoHistory { ts.agent.Sessions.AddFullMessage(ts.sessionKey, toolResultMsg)