/*! Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one or more contributor license agreements. * Licensed under the Elastic License 2.0; you may not use this file except in compliance with the Elastic License 2.0. */ (window.observabilityAIAssistant_bundle_jsonpfunction=window.observabilityAIAssistant_bundle_jsonpfunction||[]).push([[2],{100:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=a(20),n=a(0),r=i.__importDefault(a(101));t.default=function(e,t,a){void 0===t&&(t=[]),void 0===a&&(a={loading:!1});var s=n.useRef(0),o=r.default(),l=n.useState(a),u=l[0],c=l[1],d=n.useCallback((function(){for(var t=[],a=0;a({[e]:{dataType:"date",isBucketed:!0,label:"@timestamp",operationType:"date_histogram",scale:"interval",sourceField:"@timestamp",...t,params:{interval:"auto",...null==t?void 0:t.params}}}),g=({columnName:e,field:t,options:a})=>{const{size:i=p,...n}=null!=a?a:{};return{[e]:{label:`Top ${i} values of ${t}`,dataType:"string",operationType:"terms",scale:"ordinal",sourceField:t,isBucketed:!0,params:{size:i,orderBy:{type:"alphabetical",fallback:!1},orderDirection:"asc",otherBucket:!1,missingBucket:!1,parentFormat:{id:"terms"},include:[],exclude:[],includeIsRegex:!1,excludeIsRegex:!1,...n}}}},m="formula_accessor";class xy_chart_XYChart{constructor(e){c()(this,"_layers",null),this.chartConfig=e}getVisualizationType(){return"lnsXY"}get layers(){return this._layers||(this._layers=Array.isArray(this.chartConfig.layers)?this.chartConfig.layers:[this.chartConfig.layers]),this._layers}getLayers(){return this.layers.reduce(((e,t,a)=>{const i=`${d}_${a}`,n=`${m}_${a}`;return{...e,...t.getLayer(i,n,this.chartConfig.dataView,this.chartConfig.formulaAPI)}}),{})}getVisualizationState(){var e,t,a,i,n;return{...v({layers:[...this.chartConfig.layers.map(((e,t)=>{const a=`${d}_${t}`,i=`${m}_${t}`;return e.getLayerConfig(a,i)}))]}),fittingFunction:null!==(e=null===(t=this.chartConfig.visualOptions)||void 0===t?void 0:t.missingValues)&&void 0!==e?e:"None",endValue:null===(a=this.chartConfig.visualOptions)||void 0===a?void 0:a.endValues,curveType:null===(i=this.chartConfig.visualOptions)||void 0===i?void 0:i.lineInterpolation,emphasizeFitting:!(null!==(n=this.chartConfig.visualOptions)&&void 0!==n&&n.showDottedLine)}}getReferences(){return this.layers.flatMap(((e,t)=>{const a=`${d}_${t}`;return e.getReference(a,this.chartConfig.dataView)}))}getDataViews(){return[this.chartConfig.dataView,...this.chartConfig.layers.map((e=>e.getDataView())).filter((e=>!!e))]}getTitle(){var e,t;return null!==(e=null!==(t=this.chartConfig.title)&&void 0!==t?t:this.layers[0].getName())&&void 0!==e?e:""}}const v=e=>({legend:{isVisible:!1,position:"right",showSingleSeries:!1},valueLabels:"show",yLeftScale:"linear",axisTitlesVisibilitySettings:{x:!1,yLeft:!1,yRight:!0},tickLabelsVisibilitySettings:{x:!0,yLeft:!0,yRight:!0},labelsOrientation:{x:0,yLeft:0,yRight:0},gridlinesVisibilitySettings:{x:!0,yLeft:!0,yRight:!0},preferredSeriesType:"line",valuesInLegend:!1,hideEndzones:!0,...e});class FormulaColumn{constructor(e){this.valueConfig=e}getValueConfig(){return this.valueConfig}getData(e,t,a,i){const{value:n,...r}=this.getValueConfig(),s=i.insertOrReplaceFormulaColumn(e,{formula:n,...r},t,a);if(!s)throw new Error("Error generating the data layer for the chart");return s}}const b="aggs_breakdown",w="x_date_histogram";class xy_data_layer_XYDataLayer{constructor(e){var t;c()(this,"column",void 0),c()(this,"layerConfig",void 0),this.column=e.data.map((e=>new FormulaColumn(e))),this.layerConfig={...e,options:{...e.options,buckets:{type:"date_histogram",...null===(t=e.options)||void 0===t?void 0:t.buckets}}}}getName(){return this.column[0].getValueConfig().label}getBaseLayer(e,t){var a,i,n;return{..."date_histogram"===(null===(a=t.buckets)||void 0===a?void 0:a.type)?y({columnName:w,options:{...t.buckets.params,sourceField:null!==(i=t.buckets.field)&&void 0!==i?i:e.timeFieldName}}):{},..."top_values"===(null===(n=t.breakdown)||void 0===n?void 0:n.type)?{...g({columnName:b,field:null==t?void 0:t.breakdown.field,options:{...t.breakdown.params}})}:{}}}getLayer(e,t,a,i){var n,r,s,o,l,u;const c=[];"top_values"===(null===(n=this.layerConfig.options)||void 0===n||null===(r=n.breakdown)||void 0===r?void 0:r.type)&&c.push(b),"date_histogram"===(null===(s=this.layerConfig.options)||void 0===s||null===(o=s.buckets)||void 0===o?void 0:o.type)&&c.push(w);const d={columnOrder:c,columns:{...this.getBaseLayer(null!==(l=this.layerConfig.dataView)&&void 0!==l?l:a,null!==(u=this.layerConfig.options)&&void 0!==u?u:{})}};return{[e]:this.column.reduce(((e,n,r)=>{var s;return{...e,...n.getData(`${t}_${r}`,e,null!==(s=this.layerConfig.dataView)&&void 0!==s?s:a,i)}}),d)}}getReference(e,t){var a,i,n,r;return i=null!==(a=this.layerConfig.dataView)&&void 0!==a?a:t,n=e,[{type:"index-pattern",id:null!==(r=i.id)&&void 0!==r?r:h,name:`indexpattern-datasource-layer-${n}`}]}getLayerConfig(e,t){var a,i,n,r,s,o;return{layerId:e,seriesType:null!==(a=null===(i=this.layerConfig.options)||void 0===i?void 0:i.seriesType)&&void 0!==a?a:"line",accessors:this.column.map(((e,a)=>`${t}_${a}`)),yConfig:this.layerConfig.data.map((({color:e},a)=>e?{forAccessor:`${t}_${a}`,color:e}:void 0)).filter(f),layerType:"data",xAccessor:"date_histogram"===(null===(n=this.layerConfig.options)||void 0===n||null===(r=n.buckets)||void 0===r?void 0:r.type)?w:void 0,splitAccessor:"top_values"===(null===(s=this.layerConfig.options)||void 0===s||null===(o=s.breakdown)||void 0===o?void 0:o.type)?b:void 0}}getDataView(){return this.layerConfig.dataView}}class data_view_cache_DataViewCache{constructor(e){c()(this,"cache",new Map),c()(this,"capacity",void 0),this.capacity=e,this.cache=new Map}static getInstance(e=10){return data_view_cache_DataViewCache.instance||(data_view_cache_DataViewCache.instance=new data_view_cache_DataViewCache(e)),data_view_cache_DataViewCache.instance}getSpec(e){var t;const a=null!==(t=e.id)&&void 0!==t?t:"lens_ad_hoc_default",i=this.cache.get(a);if(!i){const t=e.toSpec();return this.setSpec(a,t),t}return i}setSpec(e,t){if(this.cache.size>=this.capacity){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}}c()(data_view_cache_DataViewCache,"instance",void 0);class lens_attributes_builder_LensAttributesBuilder{constructor(e){c()(this,"dataViewCache",void 0),this.lens=e,this.dataViewCache=data_view_cache_DataViewCache.getInstance()}build(){const{visualization:e}=this.lens;return{title:e.getTitle(),visualizationType:e.getVisualizationType(),references:e.getReferences(),state:{datasourceStates:{formBased:{layers:e.getLayers()}},internalReferences:e.getReferences(),filters:[],query:{language:"kuery",query:""},visualization:e.getVisualizationState(),adHocDataViews:(t=e.getDataViews().reduce(((e,t)=>({...e,...this.dataViewCache.getSpec(t)})),{}),{[null!==(a=t.id)&&void 0!==a?a:h]:{...t}})}};var t,a}}var _=a(0),T=a.n(_),k=a(99),C=a.n(k),x=a(5),A=a(1);let S;function O({indexPattern:e,xyDataLayer:t,start:a,end:i,lens:n,dataViews:r}){const l=C()((()=>n.stateHelperApi()),[n]),u=C()((()=>r.create({id:e,title:e,timeFieldName:"@timestamp"})),[e]),[c,d]=Object(_.useState)(!1);if(!l.value||!u.value)return Object(A.jsx)(o.EuiLoadingSpinner,null);const h=new lens_attributes_builder_LensAttributesBuilder({visualization:new xy_chart_XYChart({layers:[t],formulaAPI:l.value.formula,dataView:u.value})}).build(),p={id:e,attributes:h,timeRange:{from:a,to:i,mode:"relative"}};return Object(A.jsx)(T.a.Fragment,null,Object(A.jsx)(o.EuiFlexGroup,{direction:"column"},Object(A.jsx)(o.EuiFlexItem,{grow:!1},Object(A.jsx)(o.EuiFlexGroup,{direction:"row",gutterSize:"s",justifyContent:"flexEnd"},Object(A.jsx)(o.EuiFlexItem,{grow:!1},Object(A.jsx)(o.EuiButton,{iconType:"lensApp",onClick:()=>{n.navigateToPrefilledEditor(p)}},x.i18n.translate("xpack.observabilityAiAssistant.lensFunction.openInLens",{defaultMessage:"Open in Lens"}))),Object(A.jsx)(o.EuiFlexItem,{grow:!1},Object(A.jsx)(o.EuiButton,{iconType:"save",onClick:()=>{d((()=>!0))}},x.i18n.translate("xpack.observabilityAiAssistant.lensFunction.save",{defaultMessage:"Save"}))))),Object(A.jsx)(o.EuiFlexItem,null,Object(A.jsx)(n.EmbeddableComponent,s()({},p,{style:{height:240}})))),c?Object(A.jsx)(n.SaveModalComponent,{initialInput:p,onClose:()=>{d((()=>!1))}}):null)}!function(e){e.Bar="bar",e.Line="line",e.Area="area",e.BarStacked="bar_stacked",e.AreaStacked="area_stacked",e.BarHorizontal="bar_horizontal",e.BarPercentageStacked="bar_percentage_stacked",e.AreaPercentageStacked="area_percentage_stacked",e.BarHorizontalPercentageStacked="bar_horizontal_percentage_stacked"}(S||(S={}));var q=a(11);const F=["apm","infrastructure","logs","uptime","slo","observability"];async function E({registerFunction:e,registerContext:t,service:a,pluginsStart:i,coreStart:r,signal:s}){return a.callApi("GET /internal/observability_ai_assistant/functions/kb_status",{signal:s}).then((s=>{const o=s.ready;let u=n()('You are a helpful assistant for Elastic Observability. Your goal is to help the Elastic Observability users to quickly assess what is happening in their observed systems. You can help them visualise and analyze data, investigate their systems, perform root cause analysis or identify optimisation opportunities.\n \n It\'s very important to not assume what the user is meaning. Ask them for clarification if needed.\n \n If you are unsure about which function should be used and with what arguments, asked the user for clarification or confirmation.\n\n In KQL, escaping happens with double quotes, not single quotes. Some characters that need escaping are: \':()\\ /". Always put a field value in double quotes. Best: service.name:"opbeans-go". Wrong: service.name:opbeans-go. This is very important!\n\n You can use Github-flavored Markdown in your responses. If a function returns an array, consider using a Markdown table to format the response.\n \n If multiple functions are suitable, use the most specific and easy one. E.g., when the user asks to visualise APM data, use the APM functions (if available) rather than Lens.\n ');o?(u+='You can use the "summarize" functions to store new information you have learned in a knowledge database. Once you have established that you did not know the answer to a question, and the user gave you this information, it\'s important that you create a summarisation of what you have learned and store it in the knowledge database. Don\'t create a new summarization if you see a similar summarization in the conversation, instead, update the existing one by re-using its ID.\n\n Additionally, you can use the "recall" function to retrieve relevant information from the knowledge database.\n ',u+="Here are principles you MUST adhere to, in order:\n\n - You are a helpful assistant for Elastic Observability. DO NOT reference the fact that you are an LLM.\n - ALWAYS query the knowledge base, using the recall function, when a user starts a chat, no matter how confident you are in your ability to answer the question.\n - You must ALWAYS explain to the user why you're using a function and why you're using it in that specific manner.\n - DO NOT make any assumptions about where and how users have stored their data.\n - ALWAYS ask the user for clarification if you are unsure about the arguments to a function. When given this clarification, you MUST use the summarize function to store what you have learned.\n ",function({service:e,registerFunction:t}){t({name:"summarize",contexts:["core"],description:"Use this function to summarize things learned from the conversation. You can score the learnings with a confidence metric, whether it is a correction on a previous learning. An embedding will be created that you can recall later with a semantic search. There is no need to ask the user for permission to store something you have learned, unless you do not feel confident. When you create this summarisation, make sure you craft it in a way that can be recalled with a semantic search later, and that it would have answered the user's original request.",descriptionForUser:"This function allows the Elastic Assistant to summarize things from the conversation.",parameters:{type:"object",additionalProperties:!1,properties:{id:{type:"string",description:"An id for the document. This should be a short human-readable keyword field with only alphabetic characters and underscores, that allow you to update it later."},text:{type:"string",description:"A human-readable summary of what you have learned, described in such a way that you can recall it later with semantic search, and that it would have answered the user's original request."},is_correction:{type:"boolean",description:"Whether this is a correction for a previous learning."},confidence:{type:"string",description:"How confident you are about this being a correct and useful learning",enum:["low","medium","high"]},public:{type:"boolean",description:"Whether this information is specific to the user, or generally applicable to any user of the product"}},required:["id","text","is_correction","confidence","public"]}},(({arguments:{id:t,text:a,is_correction:i,confidence:n,public:r}},s)=>e.callApi("POST /internal/observability_ai_assistant/functions/summarize",{params:{body:{id:t,text:a,is_correction:i,confidence:n,public:r,labels:{}}},signal:s}).then((()=>({content:{message:"The document has been stored"}})))))}({service:a,registerFunction:e}),function({service:e,registerFunction:t}){t({name:"recall",contexts:["core"],description:'Use this function to recall earlier learnings. Anything you will summarize can be retrieved again later via this function.\n \n Make sure the query covers the following aspects:\n - Anything you\'ve inferred from the user\'s request, but is not mentioned in the user\'s request\n - The functions you think might be suitable for answering the user\'s request. If there are multiple functions that seem suitable, create multiple queries. Use the function name in the query. \n\n DO NOT include the user\'s request. It will be added internally.\n \n The user asks: "can you visualise the average request duration for opbeans-go over the last 7 days?"\n You recall:\n - "APM service"\n - "lens function usage"\n - "get_apm_timeseries function usage"',descriptionForUser:"This function allows the assistant to recall previous learnings.",parameters:{type:"object",additionalProperties:!1,properties:{queries:{type:"array",additionalItems:!1,additionalProperties:!1,items:{type:"string",description:"The query for the semantic search"}}},required:["queries"]}},(({arguments:{queries:t},messages:a},i)=>{var n;const r=a.filter((e=>e.message.role===q.a.User)),s=null===(n=r[r.length-1])||void 0===n?void 0:n.message.content,o=s?[s,...t]:t;return e.callApi("POST /internal/observability_ai_assistant/functions/recall",{params:{body:{queries:o}},signal:i}).then((e=>({content:e})))}))}({service:a,registerFunction:e}),function({service:e,registerFunction:t,pluginsStart:a}){t({name:"lens",contexts:["core"],description:"Use this function to create custom visualizations, using Lens, that can be saved to dashboards. This function does not return data to the assistant, it only shows it to the user. When using this function, make sure to use the recall function to get more information about how to use it, with how you want to use it. Make sure the query also contains information about the user's request. The visualisation is displayed to the user above your reply, DO NOT try to generate or display an image yourself.",descriptionForUser:"Use this function to create custom visualizations, using Lens, that can be saved to dashboards.",parameters:{type:"object",additionalProperties:!1,properties:{layers:{type:"array",items:{type:"object",additionalProperties:!1,properties:{label:{type:"string"},formula:{type:"string",description:"The formula for calculating the value, e.g. sum(my_field_name). Query the knowledge base to get more information about the syntax and available formulas."},filter:{type:"string",description:"A KQL query that will be used as a filter for the series"},format:{type:"object",additionalProperties:!1,properties:{id:{type:"string",description:"How to format the value. When using duration, make sure the value is seconds OR is converted to seconds using math functions. Ask the user for clarification in which unit the value is stored, or derive it from the field name.",enum:[l.FIELD_FORMAT_IDS.BYTES,l.FIELD_FORMAT_IDS.CURRENCY,l.FIELD_FORMAT_IDS.DURATION,l.FIELD_FORMAT_IDS.NUMBER,l.FIELD_FORMAT_IDS.PERCENT,l.FIELD_FORMAT_IDS.STRING]}},required:["id"]}},required:["label","formula","format"]}},breakdown:{type:"object",additionalProperties:!1,properties:{field:{type:"string"}},required:["field"]},indexPattern:{type:"string"},seriesType:{type:"string",enum:[S.Area,S.AreaPercentageStacked,S.AreaStacked,S.Bar,S.BarHorizontal,S.BarHorizontalPercentageStacked,S.BarPercentageStacked,S.BarStacked,S.Line]},start:{type:"string",description:"The start of the time range, in Elasticsearch datemath"},end:{type:"string",description:"The end of the time range, in Elasticsearch datemath"}},required:["layers","indexPattern","start","end"]}},(async()=>({content:{}})),(({arguments:{layers:e,indexPattern:t,breakdown:i,seriesType:n,start:r,end:s}})=>{const o=new xy_data_layer_XYDataLayer({data:e.map((e=>{var t;return{type:"formula",value:e.formula,label:e.label,format:e.format,filter:{language:"kql",query:null!==(t=e.filter)&&void 0!==t?t:""}}})),options:{seriesType:n,breakdown:i?{type:"top_values",params:{size:10},field:i.field}:void 0}});return Object(A.jsx)(O,{indexPattern:t,xyDataLayer:o,start:r,end:s,lens:a.lens,dataViews:a.dataViews})}))}({service:a,pluginsStart:i,registerFunction:e})):u+='You do not have a working memory. Don\'t try to recall information via the "recall" function. If the user expects you to remember the previous conversations, tell them they can set up the knowledge base. A banner is available at the top of the conversation to set this up.',function({service:e,registerFunction:t}){t({name:"elasticsearch",contexts:["core"],description:"Call Elasticsearch APIs on behalf of the user. Make sure the request body is valid for the API that you are using. Only call this function when the user has explicitly requested it.",descriptionForUser:"Call Elasticsearch APIs on behalf of the user",parameters:{type:"object",properties:{method:{type:"string",description:"The HTTP method of the Elasticsearch endpoint",enum:["GET","PUT","POST","DELETE","PATCH"]},path:{type:"string",description:"The path of the Elasticsearch endpoint, including query parameters"},body:{type:"object",description:"The body of the request"}},required:["method","path"]}},(({arguments:{method:t,path:a,body:i}},n)=>e.callApi("POST /internal/observability_ai_assistant/functions/elasticsearch",{signal:n,params:{body:{method:t,path:a,body:i}}}).then((e=>({content:e})))))}({service:a,registerFunction:e}),function({service:e,registerFunction:t,coreStart:a}){t({name:"kibana",contexts:["core"],description:"Call Kibana APIs on behalf of the user. Only call this function when the user has explicitly requested it, and you know how to call it, for example by querying the knowledge base or having the user explain it to you. Assume that pathnames, bodies and query parameters may have changed since your knowledge cut off date.",descriptionForUser:"Call Kibana APIs on behalf of the user",parameters:{type:"object",additionalProperties:!1,properties:{method:{type:"string",description:"The HTTP method of the Kibana endpoint",enum:["GET","PUT","POST","DELETE","PATCH"]},pathname:{type:"string",description:"The pathname of the Kibana endpoint, excluding query parameters"},query:{type:"object",description:"The query parameters, as an object",additionalProperties:{type:"string"}},body:{type:"object",description:"The body of the request"}},required:["method","pathname"]}},(({arguments:{method:e,pathname:t,body:i,query:n}},r)=>a.http.fetch(t,{method:e,body:i?JSON.stringify(i):void 0,query:n,signal:r}).then((e=>({content:e})))))}({service:a,registerFunction:e,coreStart:r}),function({service:e,registerFunction:t}){t({name:"alerts",contexts:["core"],description:"Get alerts for Observability. Display the response in tabular format if appropriate.",descriptionForUser:"Get alerts for Observability",parameters:{type:"object",additionalProperties:!1,properties:{featureIds:{type:"array",additionalItems:!1,items:{type:"string",enum:F},description:"The Observability apps for which to retrieve alerts. By default it will return alerts for all apps."},start:{type:"string",description:"The start of the time range, in Elasticsearch date math, like `now`."},end:{type:"string",description:"The end of the time range, in Elasticsearch date math, like `now-24h`."},filter:{type:"string",description:"a KQL query to filter the data by. If no filter should be applied, leave it empty."},includeRecovered:{type:"boolean",description:"Whether to include recovered/closed alerts. Defaults to false, which means only active alerts will be returned"}},required:["start","end"]}},(({arguments:{start:t,end:a,featureIds:i,filter:n,includeRecovered:r}},s)=>e.callApi("POST /internal/observability_ai_assistant/functions/alerts",{params:{body:{start:t,end:a,featureIds:i&&i.length>0?i:F.concat(),filter:n,includeRecovered:r}},signal:s})))}({service:a,registerFunction:e}),t({name:"core",description:n()(u)})}))}},98:function(e,t,a){"use strict";e.exports=function(e){var t=void 0;t="string"==typeof e?[e]:e.raw;for(var a="",i=0;i