diff --git a/src/agents/pi-embedded-runner/run/attempt.ts b/src/agents/pi-embedded-runner/run/attempt.ts index 92e038111..8b07575ac 100644 --- a/src/agents/pi-embedded-runner/run/attempt.ts +++ b/src/agents/pi-embedded-runner/run/attempt.ts @@ -233,16 +233,6 @@ export async function runEmbeddedAttempt( const toolsSanitized = sanitizeToolsForGoogle({ tools: toolsRaw, provider: params.provider }); logToolSchemasForGoogle({ tools: toolsSanitized, provider: params.provider }); - // Wrap tools with before_tool_call hook if plugins have registered handlers - const hookRunner = getGlobalHookRunner(); - const tools = hookRunner?.hasHooks("before_tool_call") - ? wrapToolsWithBeforeCallHook(toolsSanitized, { - hookRunner, - agentId: params.agentAccountId, - sessionKey: params.sessionKey ?? params.sessionId, - }) - : toolsSanitized; - const machineName = await getMachineDisplayName(); const runtimeChannel = normalizeMessageChannel(params.messageChannel ?? params.messageProvider); let runtimeCapabilities = runtimeChannel @@ -292,6 +282,18 @@ export async function runEmbeddedAttempt( sessionKey: params.sessionKey, config: params.config, }); + + // Wrap tools with before_tool_call hook if plugins have registered handlers + // This must happen after sessionAgentId is resolved for correct hook context + const hookRunner = getGlobalHookRunner(); + const tools = hookRunner?.hasHooks("before_tool_call") + ? wrapToolsWithBeforeCallHook(toolsSanitized, { + hookRunner, + agentId: sessionAgentId, + sessionKey: params.sessionKey ?? params.sessionId, + }) + : toolsSanitized; + const sandboxInfo = buildEmbeddedSandboxInfo(sandbox, params.bashElevated); const reasoningTagHint = isReasoningTagProvider(params.provider); // Resolve channel-specific message actions for system prompt diff --git a/src/agents/pi-tools.before-call-hook.ts b/src/agents/pi-tools.before-call-hook.ts index 9834da294..a8d7aa126 100644 --- a/src/agents/pi-tools.before-call-hook.ts +++ b/src/agents/pi-tools.before-call-hook.ts @@ -63,10 +63,11 @@ export function wrapToolWithBeforeCallHook( // Check if the hook blocked the tool call if (hookResult?.block) { const reason = hookResult.blockReason ?? "Tool call blocked by policy"; - // Return a properly structured AgentToolResult error + // Return a properly structured AgentToolResult error with status="error" + // so downstream error detection (isToolResultError) recognizes it as an error const blockedResult: AgentToolResult = { content: [{ type: "text", text: `Error: ${reason}` }], - details: { blocked: true, reason }, + details: { status: "error", error: reason, blocked: true }, }; return blockedResult; }