1+ import { createHash } from 'crypto'
2+
13import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events'
24import { supportsCacheControl } from '@codebuff/common/old-constants'
35import { TOOLS_WHICH_WONT_FORCE_NEXT_STEP } from '@codebuff/common/tools/constants'
@@ -7,6 +9,7 @@ import { systemMessage, userMessage } from '@codebuff/common/util/messages'
79import { APICallError , type ToolSet } from 'ai'
810import { cloneDeep , mapValues } from 'lodash'
911
12+ import { CACHE_DEBUG_FULL_LOGGING } from './constants'
1013import { callTokenCountAPI } from './llm-api/codebuff-web-api'
1114import { getMCPToolData } from './mcp'
1215import { getAgentStreamFromTemplate } from './prompt-agent-stream'
@@ -18,6 +21,7 @@ import { getAgentPrompt } from './templates/strings'
1821import { getToolSet } from './tools/prompts'
1922import { processStream } from './tools/stream-parser'
2023import { getAgentOutput } from './util/agent-output'
24+ import { writeCacheDebugSnapshot } from './util/cache-debug'
2125import {
2226 withSystemInstructionTags ,
2327 withSystemTags as withSystemTags ,
@@ -461,7 +465,7 @@ export async function loopAgentSteps(
461465 params : {
462466 addAgentStep : AddAgentStepFn
463467 agentState : AgentState
464- agentType : AgentTemplateType
468+ agentType : string
465469 clearUserPromptMessagesAfterResponse ?: boolean
466470 clientSessionId : string
467471 content ?: Array < TextPart | ImagePart >
@@ -711,6 +715,36 @@ export async function loopAgentSteps(
711715 inputSchema : tool . inputSchema as { } ,
712716 } ) )
713717
718+ if ( CACHE_DEBUG_FULL_LOGGING ) {
719+ // Debug: hash the system prompt and tool definitions to detect prompt cache invalidation
720+ const systemHash = createHash ( 'sha256' ) . update ( system ) . digest ( 'hex' ) . slice ( 0 , 8 )
721+ const sortedToolDefs = Object . keys ( toolDefinitions ) . sort ( ) . reduce ( ( acc , key ) => {
722+ acc [ key ] = toolDefinitions [ key ]
723+ return acc
724+ } , { } as Record < string , unknown > )
725+ const toolsHash = createHash ( 'sha256' ) . update ( JSON . stringify ( sortedToolDefs ) ) . digest ( 'hex' ) . slice ( 0 , 8 )
726+ logger . debug (
727+ {
728+ systemHash,
729+ toolsHash,
730+ systemLength : system . length ,
731+ toolCount : Object . keys ( toolDefinitions ) . length ,
732+ toolNames : Object . keys ( toolDefinitions ) . sort ( ) ,
733+ agentType,
734+ } ,
735+ `[Cache Debug] System prompt hash: ${ systemHash } , Tools hash: ${ toolsHash } ` ,
736+ )
737+
738+ writeCacheDebugSnapshot ( {
739+ agentType : String ( agentType ) ,
740+ system,
741+ toolDefinitions : sortedToolDefs ,
742+ messages : initialMessages ,
743+ logger,
744+ projectRoot : fileContext . projectRoot ,
745+ } )
746+ }
747+
714748 const additionalToolDefinitionsWithCache = async ( ) => {
715749 if ( ! cachedAdditionalToolDefinitions ) {
716750 cachedAdditionalToolDefinitions = await additionalToolDefinitions ( {
0 commit comments