@grafana/assistant 0.1.27 → 0.1.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -0
- package/dist/components/index.d.ts +1 -0
- package/dist/components/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/terms/settings.gen.d.ts +129 -0
- package/dist/terms/settings.gen.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -797,6 +797,49 @@ function DashboardEditor() {
|
|
|
797
797
|
}
|
|
798
798
|
```
|
|
799
799
|
|
|
800
|
+
#### `useAIGeneration(options): UseAIGenerationResult`
|
|
801
|
+
|
|
802
|
+
The hook behind `AITextInput` and `AITextArea`. Use it when you want the same inline-assistant rewrite behavior but with your own trigger and text control — for example, an "Improve with AI" button next to a plain textarea.
|
|
803
|
+
|
|
804
|
+
**Options (`UseAIGenerationOptions`):**
|
|
805
|
+
|
|
806
|
+
- `value: string` - **Required** The current text (controlled)
|
|
807
|
+
- `onChange: (value: string) => void` - **Required** Called with the generated text (and blanked while generating)
|
|
808
|
+
- `origin: string` - **Required** Origin for analytics tracking
|
|
809
|
+
- `systemPrompt?: string` - Optional system prompt to guide the assistant
|
|
810
|
+
- `getUserPrompt?: (textInput: string) => string` - Wrap the current text into the prompt sent to the assistant
|
|
811
|
+
- `onComplete?: (text: string) => void` / `onError?: (error: Error) => void` / `onDelta?: (delta: string) => void` - Generation lifecycle callbacks
|
|
812
|
+
- `disabled?: boolean`, `autoGenerate?: boolean`, `streaming?: boolean` - Same semantics as `AITextArea`
|
|
813
|
+
|
|
814
|
+
**Returns:** `{ displayValue, isSendDisabled, handleGenerate, isGenerating, error }`
|
|
815
|
+
|
|
816
|
+
**Example:**
|
|
817
|
+
|
|
818
|
+
```typescript
|
|
819
|
+
import { useAIGeneration } from '@grafana/assistant';
|
|
820
|
+
import { useState } from 'react';
|
|
821
|
+
|
|
822
|
+
function InstructionsField() {
|
|
823
|
+
const [text, setText] = useState('');
|
|
824
|
+
const { handleGenerate, isGenerating } = useAIGeneration({
|
|
825
|
+
value: text,
|
|
826
|
+
onChange: setText,
|
|
827
|
+
origin: 'my-app/instructions',
|
|
828
|
+
systemPrompt: 'Refine the user input into a clear, actionable prompt. Output only the prompt.',
|
|
829
|
+
getUserPrompt: (input) => `Improve this prompt, keeping its intent: ${input}`,
|
|
830
|
+
});
|
|
831
|
+
|
|
832
|
+
return (
|
|
833
|
+
<div>
|
|
834
|
+
<button type="button" onClick={handleGenerate} disabled={!text.trim() || isGenerating}>
|
|
835
|
+
{isGenerating ? 'Improving…' : 'Improve with AI'}
|
|
836
|
+
</button>
|
|
837
|
+
<textarea value={text} onChange={(e) => setText(e.target.value)} />
|
|
838
|
+
</div>
|
|
839
|
+
);
|
|
840
|
+
}
|
|
841
|
+
```
|
|
842
|
+
|
|
800
843
|
### Using the Inline Assistant
|
|
801
844
|
|
|
802
845
|
The `useInlineAssistant` hook generates content inline without opening the sidebar — perfect for filling form fields with AI-generated text.
|
|
@@ -2,6 +2,7 @@ export { OpenAssistantButton, type OpenAssistantButtonProps } from './button/Ope
|
|
|
2
2
|
export { OpenAssistantSplitButton, type OpenAssistantSplitButtonProps } from './button/OpenAssistantSplitButton';
|
|
3
3
|
export { AITextInput, type AITextInputProps } from './input/AITextInput';
|
|
4
4
|
export { AITextArea, type AITextAreaProps } from './input/AITextArea';
|
|
5
|
+
export { useAIGeneration, type UseAIGenerationOptions } from './input/useAIGeneration';
|
|
5
6
|
export { QueryWithAssistantButton, type QueryWithAssistantButtonProps } from './button/QueryWithAssistantButton';
|
|
6
7
|
export { AssistantPromptCard, AssistantPromptCardView, type AssistantPromptCardProps, type AssistantPromptCardViewProps, } from './prompt-card/AssistantPromptCard';
|
|
7
8
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/components/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,KAAK,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAClG,OAAO,EAAE,wBAAwB,EAAE,KAAK,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AACjH,OAAO,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAE,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACtE,OAAO,EAAE,wBAAwB,EAAE,KAAK,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AACjH,OAAO,EACL,mBAAmB,EACnB,uBAAuB,EACvB,KAAK,wBAAwB,EAC7B,KAAK,4BAA4B,GAClC,MAAM,mCAAmC,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/components/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,KAAK,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAClG,OAAO,EAAE,wBAAwB,EAAE,KAAK,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AACjH,OAAO,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAE,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACtE,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,wBAAwB,EAAE,KAAK,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AACjH,OAAO,EACL,mBAAmB,EACnB,uBAAuB,EACvB,KAAK,wBAAwB,EAC7B,KAAK,4BAA4B,GAClC,MAAM,mCAAmC,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(()=>{"use strict";var e={d:(t,n)=>{for(var a in n)e.o(n,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:n[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};function n(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n);return(t>>>0).toString(16)}e.r(t),e.d(t,{AITextArea:()=>Ne,AITextInput:()=>Le,ASSISTANT_PLUGIN_ID:()=>O,ASSISTANT_PLUGIN_TITLE:()=>G,AssistantPromptCard:()=>Ue,AssistantPromptCardView:()=>De,CALLBACK_EXTENSION_POINT:()=>q,ComponentNodeData:()=>w,DashboardNodeData:()=>S,DatasourceNodeData:()=>A,EntityNodeData:()=>C,FolderNodeData:()=>I,K6SetScriptContentEvent:()=>Je,LIMITS_UPDATED_EVENT:()=>Ve,LabelNameNodeData:()=>T,LabelValueNodeData:()=>L,OpenAssistantButton:()=>se,OpenAssistantSplitButton:()=>de,QueryWithAssistantButton:()=>je,SkillNodeData:()=>P,StructuredNodeData:()=>r,TERMS_AND_CONDITIONS_REFRESH_EVENT:()=>Me,checkLimits:()=>Ke,checkTerms:()=>Ge,closeAssistant:()=>Z,createAssistantContextItem:()=>_,createTool:()=>We,ensureInlineAssistantInitialized:()=>ye,getExposeAssistantFunctionsConfig:()=>F,getInlineAssistantFactory:()=>xe,isAssistantAvailable:()=>Q,newFunctionNamespace:()=>B,onK6SetScriptContent:()=>Xe,openAssistant:()=>Y,provideComponents:()=>k,providePageContext:()=>f,provideQuestions:()=>j,setInlineAssistantFactory:()=>be,setInlineAssistantInitializer:()=>ve,toggleAssistant:()=>ee,useAssistant:()=>te,useInlineAssistant:()=>Ie,useLimits:()=>He,usePageComponents:()=>E,usePageContext:()=>v,useProvidePageContext:()=>b,useProvideQuestions:()=>R,useQuestions:()=>U,useTerms:()=>ze});class a{constructor(e){this.params=e,this.text="",this.id=n(e.id),this.type=e.type}get bypassLimits(){var e;return null!==(e=this.params.bypassLimits)&&void 0!==e&&e}formatForLLM(e){var t,n;return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:null!==(t=this.params.text)&&void 0!==t?t:"",text:null!==(n=this.params.text)&&void 0!==n?n:""}}}equals(e){return e instanceof a&&this.id===e.id&&this.type===e.type}}class r extends a{constructor(e){super({...e,id:n(JSON.stringify(e.data)),type:"structured"}),this.data=e.data}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:this.data}}}const s=require("@grafana/runtime"),o=require("react"),i="__grafanaAssistantPageContextRegistry__",l="grafana-assistant:page-context-registry-changed",d="grafana-assistant:page-context-update",c="grafana-assistant:page-context-remove",u="grafana-assistant:page-context-sync";function p(){return window[i]}function m(e,t=!1){window[i]=e,window.dispatchEvent(new CustomEvent(l)),t||window.dispatchEvent(new CustomEvent(u,{detail:{registry:e}}))}window[i]||(window[i]=[]);let g=!1;function f(e,t){var n;(n=e)instanceof RegExp?n.source:"string"!=typeof n||n&&""!==n.trim()||console.warn("useProvidePageContext: Empty string passed as urlPattern. This will cause the context to not match any pages.");const a={id:y(),urlPattern:e,context:[...t]};m([...p(),a]),window.dispatchEvent(new CustomEvent(d,{detail:a}));const r=e=>{const t=p(),n=t.findIndex(e=>e.id===a.id);if(-1!==n){const a=[...t];a[n]={...a[n],context:[...e]},m(a),window.dispatchEvent(new CustomEvent(d,{detail:a[n]}))}};return r.unregister=()=>{const e=p(),t=e.findIndex(e=>e.id===a.id);-1!==t&&(m(e.filter((e,n)=>n!==t)),window.dispatchEvent(new CustomEvent(c,{detail:{id:a.id}})))},r}g||(g=!0,window.addEventListener(d,e=>{const t=e.detail;if(!(null==t?void 0:t.id))return;const n=p(),a=n.findIndex(e=>e.id===t.id);if(-1!==a){const e=[...n];e[a]=t,m(e,!0)}else m([...n,t],!0)}),window.addEventListener(c,e=>{var t;const n=null===(t=e.detail)||void 0===t?void 0:t.id;if(!n)return;const a=p(),r=a.findIndex(e=>e.id===n);-1!==r&&m(a.filter((e,t)=>t!==r),!0)}),window.addEventListener(u,e=>{var t;const n=null===(t=e.detail)||void 0===t?void 0:t.registry;if(!Array.isArray(n))return;const a=p(),r=new Set(a.map(e=>e.id)),s=n.filter(e=>!r.has(e.id));s.length>0&&m([...a,...s],!0)}));const h=[];function b(e,t=h){const n=(0,o.useRef)(void 0),a=(0,o.useRef)(void 0),r=(0,o.useRef)(!1);return(0,o.useEffect)(()=>{r.current=!1;const s=void 0!==a.current?a.current:t;return n.current=f(e,s),void 0!==a.current&&(a.current=void 0),()=>{var e;null===(e=n.current)||void 0===e||e.unregister(),n.current=void 0}},[e]),(0,o.useEffect)(()=>{!r.current&&n.current&&n.current(t)},[t]),(0,o.useCallback)(e=>{r.current=!0,n.current?n.current(e):a.current=e},[])}function v(e={allowQuestions:!1,allowComponents:!1}){const[t,n]=(0,o.useState)([]),a=(0,s.useLocationService)(),r=(0,o.useRef)("");(0,o.useEffect)(()=>{const e=()=>{const e=function(e){if(!e)return[];const t=[],n=p();for(const a of n)x(e,a.urlPattern)&&t.push(...a.context);return t}(a.getLocation().pathname);n(e)},t=()=>{e()},s=a.getLocationObservable().subscribe(t=>{const n=t.pathname;n!==r.current&&(r.current=n,e())});return window.addEventListener(l,t),window.addEventListener(d,t),window.addEventListener(c,t),window.addEventListener(u,t),e(),()=>{s.unsubscribe(),window.removeEventListener(l,t),window.removeEventListener(d,t),window.removeEventListener(c,t),window.removeEventListener(u,t)}},[a]);let i=t;return e.allowQuestions||(i=i.filter(e=>{var t;return"question"!==(null===(t=e.node.data)||void 0===t?void 0:t.type)})),e.allowComponents||(i=i.filter(e=>{var t;return"component"!==(null===(t=e.node.data)||void 0===t?void 0:t.type)})),i}function y(e="page-context"){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function x(e,t){if(t instanceof RegExp)return t.test(e);if("string"==typeof t){if(!t||""===t.trim())return!1;const n=t.replace(/\*\*/g,"\0DOUBLE_STAR\0").replace(/\*/g,"[^/]*").replace(/\u0000DOUBLE_STAR\u0000/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(e)}return!1}class w extends a{constructor(e){const t=e.namespace||"components";super({...e,id:`${t}-${Object.keys(e.components).join("-")}`,type:"component"}),this.components=e.components,this.prompt=e.prompt,this.namespace=t}formatForLLM(e){return{type:this.type,codeElementIds:e,data:{name:`Custom UI components (${this.namespace})`,prompt:this.prompt?this.prompt+"\n\nIMPORTANT: The instructions and components described above are scoped to this specific context item only. Do not apply them to unrelated queries or components.":""}}}}function E(){const e=v({allowComponents:!0,allowQuestions:!1});return(0,o.useMemo)(()=>{const t={};for(const n of e.filter(e=>{var t;return null===(t=e.node.data)||void 0===t?void 0:t.components})){const e=n.node.data;if((null==e?void 0:e.components)&&Object.keys(e.components).length>0){const n=e.namespace||e.name||"components";for(const[a,r]of Object.entries(e.components))t[`${n}_${a}`]=r}}return t},[e])}function k(e,t,n,a=/.*/){if((r=a)instanceof RegExp?".*"===r.source&&""===r.flags:".*"===r||"/.*/"===r){const a=f(/.*/,[_("component",{components:n,prompt:e,namespace:t})]),r=(e,n)=>{a([_("component",{components:e,prompt:n,namespace:t})])};return r.unregister=a.unregister,r}var r;const s=f(/.*/,[_("component",{components:n,prompt:"",namespace:t})]),o=f(a,[_("component",{components:{},prompt:e,namespace:t})]),i=(e,n)=>{s([_("component",{components:e,prompt:"",namespace:t})]),o([_("component",{components:{},prompt:n,namespace:t})])};return i.unregister=()=>{s.unregister(),o.unregister()},i}class S extends a{constructor(e){super({...e,id:e.dashboardUid,type:"dashboard"}),this.dashboardUid=e.dashboardUid,this.dashboardTitle=e.dashboardTitle,this.folderUid=e.folderUid,this.folderTitle=e.folderTitle,this.text=e.dashboardTitle}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.dashboardTitle,dashboardUid:this.dashboardUid,dashboardTitle:this.dashboardTitle,folderUid:this.folderUid,folderTitle:this.folderTitle,text:this.text}}}}class I extends a{constructor(e){super({...e,id:e.folderUid,type:"dashboard_folder"}),this.text="",this.folderUid=e.folderUid,this.folderTitle=e.folderTitle,this.text=e.folderTitle}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.folderTitle,folderUid:this.folderUid,folderTitle:this.folderTitle,text:this.text}}}}class A extends a{constructor(e){super({...e,id:e.datasourceUid,type:"datasource"}),this.datasourceUid=e.datasourceUid,this.datasourceType=e.datasourceType,this.datasourceName=e.datasourceName,this.img=e.img,this.text=e.datasourceName}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.datasourceName,uid:this.datasourceUid,type:this.datasourceType,text:this.text}}}}class C extends a{constructor(e){var t,n,a;super({id:`${e.type}-${e.name}-${[null===(t=e.scope)||void 0===t?void 0:t.env,null===(n=e.scope)||void 0===n?void 0:n.site,null===(a=e.scope)||void 0===a?void 0:a.namespace].filter(Boolean).join("-")}`,type:"entity",title:e.title,hidden:e.hidden,img:e.img,icon:e.icon,text:e.name}),this.entityType=e.type,this.name=e.name,this.scope=e.scope,this.properties=e.properties,this.text=e.name}formatForLLM(e){return{type:"entity",codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.name,text:this.text,type:this.entityType,scope:this.scope,properties:this.properties}}}}class T extends a{constructor(e){super({...e,id:`${e.datasourceUid}-${e.labelName}`,type:"label_name"}),this.datasourceUid=e.datasourceUid,this.datasourceType=e.datasourceType,this.datasourceName=e.datasourceName,this.labelName=e.labelName,this.text=e.labelName,this.img=e.img}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.labelName,datasourceUid:this.datasourceUid,datasourceType:this.datasourceType,datasourceName:this.datasourceName,labelName:this.labelName,text:this.text}}}}class L extends a{constructor(e){super({...e,id:`${e.datasourceUid}-${e.labelName}-${e.labelValue}-${e.operator||"="}`,type:"label_value"}),this.datasourceUid=e.datasourceUid,this.datasourceType=e.datasourceType,this.datasourceName=e.datasourceName,this.labelName=e.labelName,this.labelValue=e.labelValue,this.text=e.labelValue,this.img=e.img,this.operator=e.operator||"="}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.labelValue,datasourceUid:this.datasourceUid,datasourceType:this.datasourceType,datasourceName:this.datasourceName,labelName:this.labelName,labelValue:this.labelValue,text:this.text,operator:this.operator}}}}function $(e){var t,n,a,r,o;const i=(0,s.getDataSourceSrv)().getInstanceSettings(e);return{datasourceType:null!==(t=null==i?void 0:i.type)&&void 0!==t?t:"unknown",datasourceName:null!==(n=null==i?void 0:i.name)&&void 0!==n?n:e,img:null===(o=null===(r=null===(a=null==i?void 0:i.meta)||void 0===a?void 0:a.info)||void 0===r?void 0:r.logos)||void 0===o?void 0:o.small}}const N={datasource:"database",label_name:"database",label_value:"database",dashboard:"dashboard",dashboard_folder:"folder",unknown:"circle-mono",structured:"gf-grid",component:"gf-grid",entity:"asserts",skill:"play"};function _(e,t){var n,s,o;const i=function(e,t){switch(e){case"datasource":return new A({...t,...$(t.datasourceUid)});case"label_name":return new T({...t,...$(t.datasourceUid)});case"label_value":return new L({...t,...$(t.datasourceUid)});case"dashboard":return new S(t);case"dashboard_folder":return new I(t);case"structured":return new r(t);case"component":return new w({...t,hidden:!0});case"entity":return new C(t);case"unknown":return new a(t);default:return console.error(`Unknown context type: ${e}`),new a(t)}}(e,t),l=null!==(n=t.title)&&void 0!==n?n:function(e){var t;return e instanceof r?e.formatForLLM().data.name:null!==(t=e.text)&&void 0!==t?t:"Given Context"}(i),d=null!==(s=t.img)&&void 0!==s?s:function(e){if("img"in e)return e.img}(i);return{node:{id:i.id,name:l,img:d,icon:null!==(o=t.icon)&&void 0!==o?o:N[e],navigable:!1,selectable:!0,data:i},occurrences:[]}}class P extends a{constructor(e){super({...e,id:e.skillId,type:"skill",text:e.skillName}),this.skillId=e.skillId,this.skillName=e.skillName,this.text=e.skillName}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.skillName,skillId:this.skillId,skillName:this.skillName,text:this.text}}}}function j(e,t){const n=y("question"),a=e=>e.map((e,t)=>({node:{id:`question-${n}-${t}`,name:e.title||e.prompt,navigable:!1,selectable:!0,icon:"question-circle",data:{type:"question",prompt:e.prompt,title:e.title,context:e.context||[]}},occurrences:[]})),r=f(e,a(t)),s=e=>{r(a(e))};return s.unregister=r.unregister,s}function R(e,t=[]){const n=(0,o.useMemo)(()=>y("question"),[]),a=e=>e.map((e,t)=>{var a;return{node:{id:`question-${n}-${t}`,name:null!==(a=e.title)&&void 0!==a?a:e.prompt,navigable:!1,selectable:!0,icon:"question-circle",data:{type:"question",prompt:e.prompt,title:e.title,context:e.context||[]}},occurrences:[]}}),r=b(e,a(t));return e=>{r(a(e))}}function U(){const e=v({allowQuestions:!0,allowComponents:!1});return D(e)}const D=e=>e.filter(e=>{var t;return"question"===(null===(t=e.node.data)||void 0===t?void 0:t.type)}).map(e=>{var t,n,a;return{prompt:(null===(t=e.node.data)||void 0===t?void 0:t.prompt)||e.node.name,title:null===(n=e.node.data)||void 0===n?void 0:n.title,context:(null===(a=e.node.data)||void 0===a?void 0:a.context)||[]}}),q="grafana-assistant-app/callback/v0-alpha";function B(e,t){return{namespace:e,functions:t}}function F(e){return{title:"callback",targets:[q],fn:()=>e.map(e=>({namespace:e.namespace,functions:e.functions}))}}const M=require("rxjs"),O="grafana-assistant-app",G="Grafana Assistant",z=10,W=100,V=5e3;function Q(){return s.getObservablePluginLinks?(0,M.defer)(()=>{try{return(0,s.getObservablePluginLinks)({extensionPointId:"grafana/extension-sidebar/v0-alpha"}).pipe((0,M.map)(e=>e.some(e=>e.pluginId===O&&e.title===G)))}catch(e){return(0,M.throwError)(()=>e)}}).pipe((0,M.retry)({count:z,delay:(e,t)=>{var n;const a=(null===(n=null==e?void 0:e.message)||void 0===n?void 0:n.toLowerCase())||"";if(!(a.includes("can only be used after")||a.includes("grafana instance has started")||a.includes("not started")))throw e;const r=Math.min(W*2**(t-1),V);return(0,M.timer)(r)}}),(0,M.catchError)(()=>(0,M.of)(!1))):(0,M.of)(!1)}const K=require("@grafana/data");class H extends K.BusEventWithPayload{}H.type="open-extension-sidebar";class J extends K.BusEventBase{}J.type="close-extension-sidebar";class X extends K.BusEventWithPayload{}function Y(e){var t;(0,s.reportInteraction)("grafana_assistant_app_opened_sidebar",{from:e.origin}),function(e,t,n){const a=new H({pluginId:e,componentTitle:t,props:n});(0,s.getAppEvents)().publish(a)}(O,G,{initialPrompt:e.prompt,initialContext:e.context,initialAutoSend:null===(t=e.autoSend)||void 0===t||t,origin:e.origin,initialMode:e.mode,chatId:e.chatId,appendContext:e.appendContext})}function Z(){!function(){const e=new J;(0,s.getAppEvents)().publish(e)}()}function ee(e){var t,n;(0,s.reportInteraction)("grafana_assistant_app_toggled_sidebar",{from:e.origin,prompt:null!==(t=e.prompt)&&void 0!==t?t:""}),function(e,t,n){const a=new X({pluginId:e,componentTitle:t,props:n});(0,s.getAppEvents)().publish(a)}(O,G,{initialPrompt:e.prompt,initialContext:e.context,initialAutoSend:null===(n=e.autoSend)||void 0===n||n,origin:e.origin,initialMode:e.mode,chatId:e.chatId,appendContext:e.appendContext})}function te(){const[e,t]=(0,o.useState)(void 0);(0,o.useEffect)(()=>{const e=Q().subscribe(t);return()=>e.unsubscribe()},[]);const n=null!=e&&e;return{isLoading:void 0===e,isAvailable:n,openAssistant:n?Y:void 0,closeAssistant:n?Z:void 0,toggleAssistant:n?ee:void 0}}X.type="toggle-extension-sidebar";const ne=require("react/jsx-runtime"),ae=require("@grafana/ui"),re=require("@emotion/css");function se(e){const{isAvailable:t,openAssistant:n}=te();return t&&n?(0,ne.jsx)(oe,{...e,openAssistant:n}):null}function oe({prompt:e,origin:t,context:n,autoSend:a=!0,title:r="Analyze with Assistant",size:i="sm",iconOnlyButton:l=!1,openAssistant:d,onClick:c}){const u=(0,ae.useStyles2)(ie);return(0,o.useEffect)(()=>{(0,s.reportInteraction)("grafana_assistant_app_open_sidebar_button_displayed",{from:t})},[t]),(0,ne.jsx)(ne.Fragment,{children:l?(0,ne.jsx)(ae.IconButton,{name:"ai-sparkle",onClick:()=>{null==c||c(),d({prompt:e,context:n,autoSend:a,origin:t})},variant:"secondary",size:i,"aria-label":r,className:u.icon,tooltip:r,"data-testid":"assistant-icon-button"}):(0,ne.jsx)(ae.Button,{icon:"ai-sparkle",onClick:()=>{null==c||c(),d({prompt:e,context:n,autoSend:a,origin:t})},variant:"secondary",fill:"solid",size:i,title:r,"aria-label":r,className:u.button,"data-testid":"assistant-button",children:r})})}const ie=e=>{const t=e.colors.secondary.main,n=e.colors.emphasize(t,.05),a=e.colors.background.canvas,r=e.shape.radius.default,s=`max(calc(${r} - 1px), 1px)`,o={content:'""',position:"absolute",inset:0,borderRadius:r,cornerShape:"squircle",background:"linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))",zIndex:-2,pointerEvents:"none"},i=e=>({content:'""',position:"absolute",inset:"1px",borderRadius:s,cornerShape:"squircle",background:`linear-gradient(${e}, ${e}), ${a}`,zIndex:-1,transition:"none",pointerEvents:"none"});return{button:(0,re.css)({label:"assistant-button",width:"fit-content",maxWidth:"100%",position:"relative",isolation:"isolate",border:"none",transition:"none !important","&::before":o,"&::after":{...i(t),transition:"none"},"&:hover":{transition:"none !important"},"&:hover::after":{background:`linear-gradient(${n}, ${n}), ${a}`}}),icon:(0,re.css)({label:"assistant-icon",position:"relative",isolation:"isolate",border:"none",background:"none",padding:e.spacing(.5),"&::before":{...o,transition:"background 0.1s ease"},"&:hover::after":{...i(t),background:`linear-gradient(${n}, ${n}), ${a}`}})}},le={sm:32,md:36,lg:40};function de(e){const{isAvailable:t,openAssistant:n}=te();return t&&n?(0,ne.jsx)(ce,{...e,openAssistant:n}):null}function ce({prompt:e,origin:t,context:n,autoSend:a=!0,title:r="Chat with Assistant",size:i="sm",onClick:l,menuItems:d,tooltip:c,dropdownButtonWidth:u,openAssistant:p}){const m=(0,ae.useStyles2)(ue),g=Boolean(d),f="number"==typeof(h=null!=u?u:le[i])?`${h}px`:h;var h;(0,o.useEffect)(()=>{(0,s.reportInteraction)("grafana_assistant_app_open_sidebar_split_button_displayed",{from:t})},[t]);const b=(0,ne.jsx)("div",{className:m.wrapper,children:(0,ne.jsxs)(ae.ButtonGroup,{className:m.buttonGroup,children:[(0,ne.jsx)(ae.Button,{icon:"ai-sparkle",onClick:()=>{null==l||l(),p({prompt:e,context:n,autoSend:a,origin:t})},variant:"secondary",fill:"solid",size:i,"aria-label":r,className:(0,re.cx)(m.segmentButton,g?m.mainButtonSplit:m.mainButtonSolo),"data-testid":"assistant-split-button-main",children:r}),d&&(0,ne.jsx)(ae.Dropdown,{overlay:d,children:(0,ne.jsx)(ae.Button,{variant:"secondary",icon:"angle-down",size:i,"aria-label":"More AI actions",className:(0,re.cx)(m.segmentButton,m.dropdownButton),style:{width:f,minWidth:f},"data-testid":"assistant-split-button-dropdown"})})]})});return c?(0,ne.jsx)(ae.Tooltip,{content:c,children:b}):b}const ue=e=>{const t=e.colors.secondary.main,n=e.colors.emphasize(t,.05),a=e.colors.background.canvas,r=e.colors.border.weak,s=e.shape.radius.default,o=`max(calc(${s} - 1px), 1px)`;return{wrapper:(0,re.css)({label:"assistant-split-button-wrapper",position:"relative",isolation:"isolate",display:"inline-block","&::before":{content:'""',position:"absolute",inset:0,borderRadius:s,cornerShape:"squircle",background:"linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))",zIndex:-1,pointerEvents:"none"},"&::after":{content:'""',position:"absolute",inset:"1px",borderRadius:o,cornerShape:"squircle",background:`linear-gradient(${t}, ${t}), ${a}`,zIndex:-1,pointerEvents:"none"}}),buttonGroup:(0,re.css)({label:"assistant-split-button-group",gap:0,position:"relative",zIndex:1,borderRadius:o,overflow:"hidden","& button":{border:"none",boxShadow:"none",background:"transparent !important"}}),segmentButton:(0,re.css)({label:"assistant-split-button-segment",position:"relative","&:hover":{background:`${n} !important`},"&:focus-visible":{background:`${n} !important`},'&[aria-expanded="true"]':{background:`${n} !important`}}),mainButtonSolo:(0,re.css)({label:"assistant-split-button-main-solo",borderRadius:o}),mainButtonSplit:(0,re.css)({label:"assistant-split-button-main-split",borderTopLeftRadius:o,borderBottomLeftRadius:o,borderTopRightRadius:0,borderBottomRightRadius:0}),dropdownButton:(0,re.css)({label:"assistant-split-button-dropdown",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:0,borderTopLeftRadius:0,borderBottomLeftRadius:0,borderTopRightRadius:o,borderBottomRightRadius:o,padding:"0 !important",boxShadow:`inset 1px 0 0 ${r}`,"& svg":{margin:0}})}},pe=e=>{const t=["rgb(168, 85, 247)","rgb(249, 115, 22)"];if("dark"===e.name.toLowerCase()||"light"===e.name.toLowerCase())return t;const n=e.colors.gradients.brandHorizontal.match(/#[0-9A-Fa-f]{6}/g);return!n||n.length<2?t:[n[0],n[1]]},me=(e,t,n,a)=>{const r=Array.from({length:101},(e,t)=>t),s={},[o,i]=pe(e),l=null!=n?n:o,d=null!=a?a:i;for(const e of r)s[`${e}%`]={backgroundImage:`\n linear-gradient(${t}, ${t}),\n conic-gradient(from ${3.6*e}deg, transparent 60%, ${l} 80%, ${d} 100%, transparent 15%)\n `};return s},ge="__grafanaAssistantInlineFactory__",fe="__grafanaAssistantInlineInitializer__",he="__grafanaAssistantInlineInitPromise__";function be(e){const t=window[ge];t&&t!==e?console.warn("InlineAssistant factory already set; ignoring subsequent setInlineAssistantFactory call"):t||(window[ge]=e)}function ve(e){const t=window[fe];t&&t!==e?console.warn("InlineAssistant initializer already set; ignoring subsequent setInlineAssistantInitializer call"):t||(window[fe]=e)}async function ye(){if(window[ge])return;const e=window[fe];if(!e)throw new Error("InlineAssistant not initialized. Make sure the Grafana Assistant plugin is loaded and initialized.");const t=window[he];if(t)return t;const n=(async()=>{try{await e()}catch(e){throw window[he]=null,e}})();return window[he]=n,n}function xe(){const e=window[ge];if(!e)throw new Error("InlineAssistant factory not initialized. Make sure the Grafana Assistant plugin is loaded.");return e}const we=["message","error","err","detail","details"];function Ee(e){if("string"!=typeof e)return null;const t=e.trim();return""===t?null:t}function ke(e,t=new Set){var n;const a=Ee(e);if(a)return a;if(e instanceof Error){const a=Ee(e.message);if((r=a)&&"[object Object]"!==r&&"Error"!==r&&"Unknown error"!==r)return a;const s=ke(e.cause,t);if(s)return s;return ke(Object.fromEntries(Object.entries(e).filter(([e])=>"message"!==e&&"name"!==e)),t)||(null!==(n=null!=a?a:Ee(e.name))&&void 0!==n?n:null)}var r;if(!e||"object"!=typeof e)return null;if(t.has(e))return null;t.add(e);const s=e;if("data"in s){const e=ke(s.data,t);if(e)return e}for(const e of we)if(e in s){const n=ke(s[e],t);if(n)return n}const o=s.status,i=Ee(s.statusText);if(("number"==typeof o||"string"==typeof o)&&i)return`HTTP ${o}: ${i}`;if(Array.isArray(e)){const n=e.map(e=>ke(e,t)).filter(e=>Boolean(e));if(n.length>0)return n.join("; ")}return null}function Se(e){const t=ke(e);if(t)return t;if(e&&"object"==typeof e)try{return JSON.stringify(e)}catch(e){return"Unknown error (could not serialize error object)"}return null==e?"Unknown error":String(e)}function Ie(){const[e,t]=(0,o.useState)(!1),[n,a]=(0,o.useState)(""),[r,s]=(0,o.useState)(null),i=(0,o.useRef)(null),l=(0,o.useCallback)(()=>{s(null),a("")},[]),d=(0,o.useCallback)(()=>{i.current&&i.current.cancel(),t(!1)},[]),c=(0,o.useCallback)(async e=>{var n;s(null),a(""),t(!0);try{await ye();const n=xe();i.current||(i.current=await n(e.origin)),await i.current.sendPrompt({prompt:e.prompt,agentName:e.agentName,agentId:e.agentId,systemPrompt:e.systemPrompt,tools:e.tools,onStart:()=>{t(!0)},onDelta:t=>{var n;a(e=>e+t),null===(n=e.onDelta)||void 0===n||n.call(e,t)},onComplete:n=>{var r;a(n),t(!1),null===(r=e.onComplete)||void 0===r||r.call(e,n)},onError:n=>{var a;s(n),t(!1),null===(a=e.onError)||void 0===a||a.call(e,n)}})}catch(a){const r=new Error(Se(a),{cause:a});s(r),t(!1),null===(n=e.onError)||void 0===n||n.call(e,r)}},[]);return(0,o.useEffect)(()=>()=>{i.current&&(i.current.cancel(),i.current.dispose(),i.current=null)},[]),{generate:c,isGenerating:e,content:n,error:r,cancel:d,reset:l}}function Ae({value:e,onChange:t,origin:n,systemPrompt:a,onComplete:r,onError:s,onDelta:i,disabled:l=!1,autoGenerate:d=!1,streaming:c=!1,getUserPrompt:u}){const{generate:p,isGenerating:m,content:g,error:f,reset:h}=Ie(),b=(0,o.useRef)(!1),v=(0,o.useRef)(e),y=(0,o.useRef)(u);y.current=u;const x=m?c?g:"":e,w=!(u?u(e.trim()):e.trim())||l||m,E=(0,o.useCallback)(o=>{v.current=e,t(""),h(),p({prompt:o,origin:n,systemPrompt:a,onDelta:i,onComplete:e=>{t(e),null==r||r(e)},onError:e=>{t(v.current),null==s||s(e)}})},[e,t,n,a,i,r,s,p,h]),k=(0,o.useRef)(()=>{});return k.current=()=>{!d||!a||e||b.current||l||(b.current=!0,E(a))},(0,o.useEffect)(()=>{k.current()},[]),{displayValue:x,isSendDisabled:w,handleGenerate:(0,o.useCallback)(()=>{const t=y.current,n=t?t(e.trim()):e.trim();!n||l||m||E(n)},[e,l,m,E]),isGenerating:m,error:f}}const Ce=["Generating...","Brewing...","Cooking...","Crunching...","Phrasing...","Wording...","Crafting...","Composing...","Drafting...","Shaping...","Forming...","Molding...","Sketching...","Whipping up...","Conjuring...","Stirring..."];function Te(e,t){const[n,a]=(0,o.useState)(""),r=(0,o.useRef)(!1);if(e&&!r.current){const e=Ce[Math.floor(Math.random()*Ce.length)];return a(e),r.current=!0,e}return e||(r.current=!1),e?n:t}function Le({value:e,onChange:t,placeholder:n,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l=!1,autoGenerate:d=!1,streaming:c=!1,getUserPrompt:u,className:p,"data-testid":m}){const{displayValue:g,isSendDisabled:f,handleGenerate:h,isGenerating:b,error:v}=Ae({value:e,onChange:t,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l,autoGenerate:d,streaming:c,getUserPrompt:u}),y=(0,ae.useStyles2)($e),x=Te(b,null!=n?n:"Ask AI to generate..."),w=(0,ne.jsx)(ae.IconButton,{name:"ai-sparkle",onClick:h,disabled:f,tooltip:f?"Enter text to generate":"Generate with AI","data-testid":m?`${m}-send`:void 0});return(0,ne.jsx)("div",{className:(0,re.cx)(y.wrapper,{[y.animatedWrapper]:b},p),"data-testid":m,children:(0,ne.jsx)(ae.Input,{value:g,onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),h())},onChange:e=>t(e.currentTarget.value),placeholder:x,disabled:l||b,suffix:w,invalid:!!v,"data-testid":m?`${m}-input`:void 0})})}const $e=e=>{const t=e.colors.background.primary,n=(0,re.keyframes)({label:"ai-input-border-animation",...me(e,t)}),[a,r]=pe(e);return{wrapper:(0,re.css)({label:"ai-text-input-wrapper",position:"relative",border:"1px solid transparent",borderRadius:e.shape.radius.default,cornerShape:"squircle"}),animatedWrapper:(0,re.css)({label:"ai-text-input-animated",border:"1px solid transparent",backgroundImage:`\n linear-gradient(${t}, ${t}),\n conic-gradient(from 0deg, transparent 60%, ${a} 80%, ${r} 100%, transparent 15%)\n `,backgroundOrigin:"border-box",backgroundClip:"padding-box, border-box",animation:`${n} 2s linear infinite`,"& input":{border:"none !important"}})}};function Ne({value:e,onChange:t,placeholder:n,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l=!1,autoGenerate:d=!1,streaming:c=!1,getUserPrompt:u,rows:p=4,className:m,"data-testid":g}){const{displayValue:f,isSendDisabled:h,handleGenerate:b,isGenerating:v,error:y}=Ae({value:e,onChange:t,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l,autoGenerate:d,streaming:c,getUserPrompt:u}),x=(0,ae.useStyles2)(_e),w=Te(v,null!=n?n:"Ask AI to generate... (Cmd/Ctrl+Enter to send)"),E=Math.max(p,2);return(0,ne.jsxs)("div",{className:(0,re.cx)(x.textareaWrapper,{[x.animatedWrapper]:v},m),"data-testid":g,children:[(0,ne.jsx)(ae.TextArea,{value:f,onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())},onChange:e=>t(e.currentTarget.value),placeholder:w,disabled:l||v,rows:E,className:x.textarea,invalid:!!y,"data-testid":g?`${g}-textarea`:void 0}),(0,ne.jsx)(ae.IconButton,{name:"ai-sparkle",onClick:b,disabled:h,className:x.sendButton,"aria-label":"Generate with AI",tooltip:h?"Enter text to generate":"Generate with AI (Cmd/Ctrl+Enter)","data-testid":g?`${g}-send`:void 0})]})}const _e=e=>{const t=e.colors.background.primary,n=(0,re.keyframes)({label:"ai-textarea-border-animation",...me(e,t)}),[a,r]=pe(e);return{textareaWrapper:(0,re.css)({label:"ai-textarea-wrapper",position:"relative",border:"1px solid transparent",borderRadius:e.shape.radius.default,cornerShape:"squircle"}),animatedWrapper:(0,re.css)({label:"ai-textarea-animated",border:"1px solid transparent",backgroundImage:`\n linear-gradient(${t}, ${t}),\n conic-gradient(from 0deg, transparent 60%, ${a} 80%, ${r} 100%, transparent 15%)\n `,backgroundOrigin:"border-box",backgroundClip:"padding-box, border-box",animation:`${n} 2s linear infinite`,"& textarea":{border:"none !important"}}),textarea:(0,re.css)({label:"ai-textarea",paddingRight:e.spacing(4),minHeight:e.spacing(6),"& textarea":{minHeight:e.spacing(6)},scrollbarWidth:"none","&::-webkit-scrollbar":{display:"none"}}),sendButton:(0,re.css)({label:"ai-textarea-send",position:"absolute",right:e.spacing(1),top:e.spacing(1)})}};function Pe(e){const t=["refId","hide","key","queryType","datasource"];for(const n in e)if("label"!==n&&!t.includes(n))return!1;return!0}function je({size:e,currentQuery:t,queries:n,dataSourceInstanceSettings:a,app:r,datasourceApi:s,title:o="Query with Assistant"}){var i;const{isAvailable:l,openAssistant:d}=te();if(!l||!d)return null;const c=`grafana/query-editor/${a.type}/${null!==(i=null!=r?r:K.CoreApp.Unknown)&&void 0!==i?i:"unknown"}`,u=!Pe(t),p=n.filter(e=>e.refId!==t.refId&&!Pe(e)),m=[_("datasource",{datasourceUid:a.uid})];u&&m.push(_("structured",{title:"Current query",data:t})),p.length>0&&m.push(_("structured",{title:"Other queries",data:{queries:p}}));const g=u&&(null==s?void 0:s.getQueryDisplayText)?s.getQueryDisplayText(t):null,f=!!g,h=f?"Help me update the current query to answer my questions and provide the insights I need.":"Help me create a new query to answer my questions and provide the insights I need.",b=[];g&&b.push(`Current query: ${g}`),b.push(`Selected data source: ${a.name}`);const v=f?"Please describe what you want to change or improve in this query.":"Please describe what you want to query and what insights you're looking for.",y=[h,"```",...b,"```",v].join("\n");return(0,ne.jsx)(oe,{prompt:y,origin:c,context:m,autoSend:!1,title:o,size:e,openAssistant:d})}const Re=["What does this panel show?","Explain the trend in this data","Why is there a spike?","Add a threshold at 80%","Change the legend to table mode"];function Ue(e){const{isAvailable:t,openAssistant:n}=te();return t&&n?(0,ne.jsx)(De,{...e,openAssistant:n}):null}function De({origin:e,context:t,mode:n,placeholder:a,examplePrompts:r,animated:i=!0,onClose:l,onSubmit:d,onClick:c,className:u,openAssistant:p}){const[m,g]=(0,o.useState)(""),f=(0,o.useRef)(null),h=(0,ae.useStyles2)(Be),b=null!=a?a:"Ask Assistant...",v=function(e,t,n){const[a,r]=(0,o.useState)(""),s=(0,o.useRef)(0),i=(0,o.useRef)(0),l=(0,o.useRef)("typing");return(0,o.useEffect)(()=>{if(s.current=0,i.current=0,l.current="typing",r(""),n||0===t.length)return;let e;const a=()=>{e=setTimeout(()=>{(()=>{const e=t[s.current];"typing"===l.current?(i.current++,r(e.slice(0,i.current)),i.current>=e.length&&(l.current="pause")):"pause"===l.current?l.current="erasing":"erasing"===l.current&&(i.current--,r(e.slice(0,i.current)),i.current<=0&&(l.current="typing",s.current=(s.current+1)%t.length))})(),a()},"pause"===l.current?800:"erasing"===l.current?15:30+20*Math.random())};return a(),()=>clearTimeout(e)},[n,t]),n||0===t.length?e:a}(b,null!=r?r:void 0!==a?[]:Re,m.length>0);(0,o.useEffect)(()=>{(0,s.reportInteraction)("grafana_assistant_app_prompt_card_displayed",{from:e})},[e]),(0,o.useEffect)(()=>{const e=requestAnimationFrame(()=>{var e;return null===(e=f.current)||void 0===e?void 0:e.focus()});return()=>cancelAnimationFrame(e)},[t]);const y=(0,o.useCallback)(a=>{const r=a.trim();r&&(p({prompt:r,context:t,autoSend:!0,origin:e,mode:n}),null==d||d(r),g(""))},[p,t,e,n,d]);return(0,ne.jsx)("div",{className:(0,re.cx)(i?h.card:h.cardStatic,u),onClick:c,role:"search","aria-label":b,"data-testid":"assistant-prompt-card",children:(0,ne.jsx)("div",{className:h.inputRow,children:(0,ne.jsx)(ae.Input,{ref:f,value:m,onChange:e=>g(e.currentTarget.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),y(m)),"Escape"===e.key&&(e.preventDefault(),null==l||l())},placeholder:v,suffix:(0,ne.jsx)(ae.IconButton,{name:"ai-sparkle",onClick:()=>y(m),disabled:!m.trim(),tooltip:"Send to assistant","aria-label":"Send to assistant","data-testid":"assistant-prompt-card-send"}),"data-testid":"assistant-prompt-card-input"})})})}function qe(e){return["rgba(168, 85, 247, 0.25) 3px -1px 20px","rgba(249, 115, 22, 0.18) -5px 3px 40px","rgba(168, 85, 247, 0.12) 7px 4px 60px",(e.isDark?"rgb(17 18 23)":"rgb(245 245 245)")+" 0 6px 30px"].join(", ")}const Be=e=>{const t=e.colors.background.primary,[n,a]=pe(e),r=(0,re.keyframes)({label:"prompt-card-border",...me(e,t)}),s={label:"assistant-prompt-card",position:"relative",display:"flex",flexDirection:"column",gap:e.spacing(1),padding:e.spacing(1),borderRadius:e.shape.radius.lg,boxShadow:qe(e)};return{card:(0,re.css)({...s,cornerShape:"squircle",background:t,border:"1px solid transparent",backgroundImage:`\n linear-gradient(${t}, ${t}),\n conic-gradient(from 0deg, transparent 60%, ${n} 80%, ${a} 100%, transparent 15%)\n `,backgroundOrigin:"border-box",backgroundClip:"padding-box, border-box",[e.transitions.handleMotion("no-preference")]:{animation:`${r} 2s linear infinite`}}),cardStatic:(0,re.css)({...s,label:"assistant-prompt-card-static",background:e.colors.background.elevated,border:`1px solid ${e.colors.border.weak}`}),inputRow:(0,re.css)({label:"prompt-card-input-row",display:"flex",alignItems:"center",gap:e.spacing(.5),"& input":{border:"none !important"}})}};function Fe(e){const t=e.split("+")[0].split("-"),n=t[0],a=t.length>1?t.slice(1).join("-"):void 0,r=n.split(".").map(Number);return 3!==r.length||r.some(isNaN)?null:{major:r[0],minor:r[1],patch:r[2],prerelease:a}}const Me="grafana-assistant-terms-and-conditions-refresh";async function Oe(){var e;const t=(0,s.getBackendSrv)(),n=`/api/plugins/${O}/resources/api/v1/settings/terms`,a=(await(0,M.lastValueFrom)(t.fetch({url:n,method:"GET",showErrorAlert:!1}))).data.data,r=null!==(e=a.acceptedTermsAndConditions)&&void 0!==e&&e,o=a.acceptedVersion,i=a.version,l=a.termsType;if("msa"===l)return{accepted:r,termsType:l};if(!r||!o||!i)return{accepted:!1,termsType:l};const d=1===function(e,t){const n=Fe(e),a=Fe(t);return n&&a?n.major!==a.major?n.major>a.major?1:-1:n.minor!==a.minor?n.minor>a.minor?1:-1:n.patch!==a.patch?n.patch>a.patch?1:-1:n.prerelease&&a.prerelease?n.prerelease===a.prerelease?0:n.prerelease>a.prerelease?1:-1:n.prerelease&&!a.prerelease?-1:!n.prerelease&&a.prerelease?1:0:null}(i,o);return{accepted:r&&!d,termsType:l}}async function Ge(){try{return(await Oe()).accepted}catch(e){throw new Error(`Failed to check terms requirements: ${e instanceof Error?e.message:String(e)}`)}}function ze(){const[e,t]=(0,o.useState)(!1),[n,a]=(0,o.useState)(null),[r,s]=(0,o.useState)(!0),[i,l]=(0,o.useState)(null);return(0,o.useEffect)(()=>{async function e(){try{s(!0),l(null);const e=await Oe();t(e.accepted),a(e.termsType)}catch(e){const n=e instanceof Error?e.message:"Failed to check terms";l(n),t(!1),a(null)}finally{s(!1)}}e();const n=()=>{e()};return document.addEventListener(Me,n),()=>{document.removeEventListener(Me,n)}},[]),{accepted:e,termsType:n,loading:r,error:i}}function We(e,t){var n;const{explainer:a,...r}=null!==(n=t.metadata)&&void 0!==n?n:{},s={name:t.name,description:t.description,inputSchema:t.inputSchema,metadata:a?{...r,explainer:e=>a(e)}:r,responseFormat:t.responseFormat,verboseParsingErrors:t.verboseParsingErrors,async invoke(n,a){var r;try{if(null===(r=a.signal)||void 0===r?void 0:r.aborted)throw new Error(`Tool ${t.name} execution was aborted`);const s=t.validate(n),o=[e(s,a)];return a.signal&&o.push(new Promise((e,n)=>{var r;null===(r=a.signal)||void 0===r||r.addEventListener("abort",()=>{n(new Error(`Tool ${t.name} execution was aborted`))},{once:!0})})),a.timeout&&a.timeout>0&&o.push(new Promise((e,n)=>{setTimeout(()=>{n(new Error(`Tool ${t.name} execution timed out after ${a.timeout}ms`))},a.timeout)})),Promise.race(o)}catch(e){throw t.verboseParsingErrors&&console.error(`Error invoking tool ${t.name}:`,e,n),e}}};return s}const Ve="grafana-assistant-limits-updated";async function Qe(){var e,t,n;const a=(0,s.getBackendSrv)(),r=`/api/plugins/${O}/resources/api/v1/usage/limits/prompt`,o=(await(0,M.lastValueFrom)(a.fetch({url:r,method:"GET",showErrorAlert:!1}))).data.data,i=null!==(e=o.total)&&void 0!==e?e:0,l=null!==(t=o.limit)&&void 0!==t?t:0;return{count:i,limit:l,month:null!==(n=o.month)&&void 0!==n?n:"",isLimitReached:l>0&&i>=l}}async function Ke(){try{return await Qe()}catch(e){throw new Error(`Failed to check limits: ${e instanceof Error?e.message:String(e)}`)}}function He(){const[e,t]=(0,o.useState)(0),[n,a]=(0,o.useState)(0),[r,s]=(0,o.useState)(""),[i,l]=(0,o.useState)(!0),[d,c]=(0,o.useState)(null),u=(0,o.useCallback)(async()=>{try{l(!0),c(null);const e=await Qe();t(e.count),a(e.limit),s(e.month)}catch(e){const n=e instanceof Error?e.message:"Failed to fetch limits";c(n),t(0),a(0),s("")}finally{l(!1)}},[]);return(0,o.useEffect)(()=>{u()},[u]),(0,o.useEffect)(()=>{const e=e=>{const n=e;n.detail&&(t(n.detail.count),a(n.detail.limit),c(null))};return window.addEventListener(Ve,e),()=>{window.removeEventListener(Ve,e)}},[]),{count:e,limit:n,month:r,isLimitReached:n>0&&e>=n,loading:i,error:d,refetch:u}}class Je extends K.BusEventWithPayload{}function Xe(e){const t=(0,s.getAppEvents)().subscribe(Je,t=>{e(t.payload)});return()=>t.unsubscribe()}Je.type="grafana-assistant:k6-set-script-content",module.exports=t})();
|
|
1
|
+
(()=>{"use strict";var e={d:(t,n)=>{for(var a in n)e.o(n,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:n[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};function n(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n);return(t>>>0).toString(16)}e.r(t),e.d(t,{AITextArea:()=>Ne,AITextInput:()=>Le,ASSISTANT_PLUGIN_ID:()=>O,ASSISTANT_PLUGIN_TITLE:()=>G,AssistantPromptCard:()=>Ue,AssistantPromptCardView:()=>De,CALLBACK_EXTENSION_POINT:()=>q,ComponentNodeData:()=>w,DashboardNodeData:()=>S,DatasourceNodeData:()=>A,EntityNodeData:()=>C,FolderNodeData:()=>I,K6SetScriptContentEvent:()=>Je,LIMITS_UPDATED_EVENT:()=>Ve,LabelNameNodeData:()=>T,LabelValueNodeData:()=>L,OpenAssistantButton:()=>se,OpenAssistantSplitButton:()=>de,QueryWithAssistantButton:()=>je,SkillNodeData:()=>P,StructuredNodeData:()=>r,TERMS_AND_CONDITIONS_REFRESH_EVENT:()=>Me,checkLimits:()=>Ke,checkTerms:()=>Ge,closeAssistant:()=>Z,createAssistantContextItem:()=>_,createTool:()=>We,ensureInlineAssistantInitialized:()=>ye,getExposeAssistantFunctionsConfig:()=>F,getInlineAssistantFactory:()=>xe,isAssistantAvailable:()=>Q,newFunctionNamespace:()=>B,onK6SetScriptContent:()=>Xe,openAssistant:()=>Y,provideComponents:()=>k,providePageContext:()=>f,provideQuestions:()=>j,setInlineAssistantFactory:()=>be,setInlineAssistantInitializer:()=>ve,toggleAssistant:()=>ee,useAIGeneration:()=>Ae,useAssistant:()=>te,useInlineAssistant:()=>Ie,useLimits:()=>He,usePageComponents:()=>E,usePageContext:()=>v,useProvidePageContext:()=>b,useProvideQuestions:()=>R,useQuestions:()=>U,useTerms:()=>ze});class a{constructor(e){this.params=e,this.text="",this.id=n(e.id),this.type=e.type}get bypassLimits(){var e;return null!==(e=this.params.bypassLimits)&&void 0!==e&&e}formatForLLM(e){var t,n;return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:null!==(t=this.params.text)&&void 0!==t?t:"",text:null!==(n=this.params.text)&&void 0!==n?n:""}}}equals(e){return e instanceof a&&this.id===e.id&&this.type===e.type}}class r extends a{constructor(e){super({...e,id:n(JSON.stringify(e.data)),type:"structured"}),this.data=e.data}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:this.data}}}const s=require("@grafana/runtime"),o=require("react"),i="__grafanaAssistantPageContextRegistry__",l="grafana-assistant:page-context-registry-changed",d="grafana-assistant:page-context-update",c="grafana-assistant:page-context-remove",u="grafana-assistant:page-context-sync";function p(){return window[i]}function m(e,t=!1){window[i]=e,window.dispatchEvent(new CustomEvent(l)),t||window.dispatchEvent(new CustomEvent(u,{detail:{registry:e}}))}window[i]||(window[i]=[]);let g=!1;function f(e,t){var n;(n=e)instanceof RegExp?n.source:"string"!=typeof n||n&&""!==n.trim()||console.warn("useProvidePageContext: Empty string passed as urlPattern. This will cause the context to not match any pages.");const a={id:y(),urlPattern:e,context:[...t]};m([...p(),a]),window.dispatchEvent(new CustomEvent(d,{detail:a}));const r=e=>{const t=p(),n=t.findIndex(e=>e.id===a.id);if(-1!==n){const a=[...t];a[n]={...a[n],context:[...e]},m(a),window.dispatchEvent(new CustomEvent(d,{detail:a[n]}))}};return r.unregister=()=>{const e=p(),t=e.findIndex(e=>e.id===a.id);-1!==t&&(m(e.filter((e,n)=>n!==t)),window.dispatchEvent(new CustomEvent(c,{detail:{id:a.id}})))},r}g||(g=!0,window.addEventListener(d,e=>{const t=e.detail;if(!(null==t?void 0:t.id))return;const n=p(),a=n.findIndex(e=>e.id===t.id);if(-1!==a){const e=[...n];e[a]=t,m(e,!0)}else m([...n,t],!0)}),window.addEventListener(c,e=>{var t;const n=null===(t=e.detail)||void 0===t?void 0:t.id;if(!n)return;const a=p(),r=a.findIndex(e=>e.id===n);-1!==r&&m(a.filter((e,t)=>t!==r),!0)}),window.addEventListener(u,e=>{var t;const n=null===(t=e.detail)||void 0===t?void 0:t.registry;if(!Array.isArray(n))return;const a=p(),r=new Set(a.map(e=>e.id)),s=n.filter(e=>!r.has(e.id));s.length>0&&m([...a,...s],!0)}));const h=[];function b(e,t=h){const n=(0,o.useRef)(void 0),a=(0,o.useRef)(void 0),r=(0,o.useRef)(!1);return(0,o.useEffect)(()=>{r.current=!1;const s=void 0!==a.current?a.current:t;return n.current=f(e,s),void 0!==a.current&&(a.current=void 0),()=>{var e;null===(e=n.current)||void 0===e||e.unregister(),n.current=void 0}},[e]),(0,o.useEffect)(()=>{!r.current&&n.current&&n.current(t)},[t]),(0,o.useCallback)(e=>{r.current=!0,n.current?n.current(e):a.current=e},[])}function v(e={allowQuestions:!1,allowComponents:!1}){const[t,n]=(0,o.useState)([]),a=(0,s.useLocationService)(),r=(0,o.useRef)("");(0,o.useEffect)(()=>{const e=()=>{const e=function(e){if(!e)return[];const t=[],n=p();for(const a of n)x(e,a.urlPattern)&&t.push(...a.context);return t}(a.getLocation().pathname);n(e)},t=()=>{e()},s=a.getLocationObservable().subscribe(t=>{const n=t.pathname;n!==r.current&&(r.current=n,e())});return window.addEventListener(l,t),window.addEventListener(d,t),window.addEventListener(c,t),window.addEventListener(u,t),e(),()=>{s.unsubscribe(),window.removeEventListener(l,t),window.removeEventListener(d,t),window.removeEventListener(c,t),window.removeEventListener(u,t)}},[a]);let i=t;return e.allowQuestions||(i=i.filter(e=>{var t;return"question"!==(null===(t=e.node.data)||void 0===t?void 0:t.type)})),e.allowComponents||(i=i.filter(e=>{var t;return"component"!==(null===(t=e.node.data)||void 0===t?void 0:t.type)})),i}function y(e="page-context"){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function x(e,t){if(t instanceof RegExp)return t.test(e);if("string"==typeof t){if(!t||""===t.trim())return!1;const n=t.replace(/\*\*/g,"\0DOUBLE_STAR\0").replace(/\*/g,"[^/]*").replace(/\u0000DOUBLE_STAR\u0000/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(e)}return!1}class w extends a{constructor(e){const t=e.namespace||"components";super({...e,id:`${t}-${Object.keys(e.components).join("-")}`,type:"component"}),this.components=e.components,this.prompt=e.prompt,this.namespace=t}formatForLLM(e){return{type:this.type,codeElementIds:e,data:{name:`Custom UI components (${this.namespace})`,prompt:this.prompt?this.prompt+"\n\nIMPORTANT: The instructions and components described above are scoped to this specific context item only. Do not apply them to unrelated queries or components.":""}}}}function E(){const e=v({allowComponents:!0,allowQuestions:!1});return(0,o.useMemo)(()=>{const t={};for(const n of e.filter(e=>{var t;return null===(t=e.node.data)||void 0===t?void 0:t.components})){const e=n.node.data;if((null==e?void 0:e.components)&&Object.keys(e.components).length>0){const n=e.namespace||e.name||"components";for(const[a,r]of Object.entries(e.components))t[`${n}_${a}`]=r}}return t},[e])}function k(e,t,n,a=/.*/){if((r=a)instanceof RegExp?".*"===r.source&&""===r.flags:".*"===r||"/.*/"===r){const a=f(/.*/,[_("component",{components:n,prompt:e,namespace:t})]),r=(e,n)=>{a([_("component",{components:e,prompt:n,namespace:t})])};return r.unregister=a.unregister,r}var r;const s=f(/.*/,[_("component",{components:n,prompt:"",namespace:t})]),o=f(a,[_("component",{components:{},prompt:e,namespace:t})]),i=(e,n)=>{s([_("component",{components:e,prompt:"",namespace:t})]),o([_("component",{components:{},prompt:n,namespace:t})])};return i.unregister=()=>{s.unregister(),o.unregister()},i}class S extends a{constructor(e){super({...e,id:e.dashboardUid,type:"dashboard"}),this.dashboardUid=e.dashboardUid,this.dashboardTitle=e.dashboardTitle,this.folderUid=e.folderUid,this.folderTitle=e.folderTitle,this.text=e.dashboardTitle}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.dashboardTitle,dashboardUid:this.dashboardUid,dashboardTitle:this.dashboardTitle,folderUid:this.folderUid,folderTitle:this.folderTitle,text:this.text}}}}class I extends a{constructor(e){super({...e,id:e.folderUid,type:"dashboard_folder"}),this.text="",this.folderUid=e.folderUid,this.folderTitle=e.folderTitle,this.text=e.folderTitle}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.folderTitle,folderUid:this.folderUid,folderTitle:this.folderTitle,text:this.text}}}}class A extends a{constructor(e){super({...e,id:e.datasourceUid,type:"datasource"}),this.datasourceUid=e.datasourceUid,this.datasourceType=e.datasourceType,this.datasourceName=e.datasourceName,this.img=e.img,this.text=e.datasourceName}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.datasourceName,uid:this.datasourceUid,type:this.datasourceType,text:this.text}}}}class C extends a{constructor(e){var t,n,a;super({id:`${e.type}-${e.name}-${[null===(t=e.scope)||void 0===t?void 0:t.env,null===(n=e.scope)||void 0===n?void 0:n.site,null===(a=e.scope)||void 0===a?void 0:a.namespace].filter(Boolean).join("-")}`,type:"entity",title:e.title,hidden:e.hidden,img:e.img,icon:e.icon,text:e.name}),this.entityType=e.type,this.name=e.name,this.scope=e.scope,this.properties=e.properties,this.text=e.name}formatForLLM(e){return{type:"entity",codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.name,text:this.text,type:this.entityType,scope:this.scope,properties:this.properties}}}}class T extends a{constructor(e){super({...e,id:`${e.datasourceUid}-${e.labelName}`,type:"label_name"}),this.datasourceUid=e.datasourceUid,this.datasourceType=e.datasourceType,this.datasourceName=e.datasourceName,this.labelName=e.labelName,this.text=e.labelName,this.img=e.img}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.labelName,datasourceUid:this.datasourceUid,datasourceType:this.datasourceType,datasourceName:this.datasourceName,labelName:this.labelName,text:this.text}}}}class L extends a{constructor(e){super({...e,id:`${e.datasourceUid}-${e.labelName}-${e.labelValue}-${e.operator||"="}`,type:"label_value"}),this.datasourceUid=e.datasourceUid,this.datasourceType=e.datasourceType,this.datasourceName=e.datasourceName,this.labelName=e.labelName,this.labelValue=e.labelValue,this.text=e.labelValue,this.img=e.img,this.operator=e.operator||"="}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.labelValue,datasourceUid:this.datasourceUid,datasourceType:this.datasourceType,datasourceName:this.datasourceName,labelName:this.labelName,labelValue:this.labelValue,text:this.text,operator:this.operator}}}}function $(e){var t,n,a,r,o;const i=(0,s.getDataSourceSrv)().getInstanceSettings(e);return{datasourceType:null!==(t=null==i?void 0:i.type)&&void 0!==t?t:"unknown",datasourceName:null!==(n=null==i?void 0:i.name)&&void 0!==n?n:e,img:null===(o=null===(r=null===(a=null==i?void 0:i.meta)||void 0===a?void 0:a.info)||void 0===r?void 0:r.logos)||void 0===o?void 0:o.small}}const N={datasource:"database",label_name:"database",label_value:"database",dashboard:"dashboard",dashboard_folder:"folder",unknown:"circle-mono",structured:"gf-grid",component:"gf-grid",entity:"asserts",skill:"play"};function _(e,t){var n,s,o;const i=function(e,t){switch(e){case"datasource":return new A({...t,...$(t.datasourceUid)});case"label_name":return new T({...t,...$(t.datasourceUid)});case"label_value":return new L({...t,...$(t.datasourceUid)});case"dashboard":return new S(t);case"dashboard_folder":return new I(t);case"structured":return new r(t);case"component":return new w({...t,hidden:!0});case"entity":return new C(t);case"unknown":return new a(t);default:return console.error(`Unknown context type: ${e}`),new a(t)}}(e,t),l=null!==(n=t.title)&&void 0!==n?n:function(e){var t;return e instanceof r?e.formatForLLM().data.name:null!==(t=e.text)&&void 0!==t?t:"Given Context"}(i),d=null!==(s=t.img)&&void 0!==s?s:function(e){if("img"in e)return e.img}(i);return{node:{id:i.id,name:l,img:d,icon:null!==(o=t.icon)&&void 0!==o?o:N[e],navigable:!1,selectable:!0,data:i},occurrences:[]}}class P extends a{constructor(e){super({...e,id:e.skillId,type:"skill",text:e.skillName}),this.skillId=e.skillId,this.skillName=e.skillName,this.text=e.skillName}formatForLLM(e){return{type:this.type,codeElementIds:e,bypassLimits:this.bypassLimits,data:{name:this.skillName,skillId:this.skillId,skillName:this.skillName,text:this.text}}}}function j(e,t){const n=y("question"),a=e=>e.map((e,t)=>({node:{id:`question-${n}-${t}`,name:e.title||e.prompt,navigable:!1,selectable:!0,icon:"question-circle",data:{type:"question",prompt:e.prompt,title:e.title,context:e.context||[]}},occurrences:[]})),r=f(e,a(t)),s=e=>{r(a(e))};return s.unregister=r.unregister,s}function R(e,t=[]){const n=(0,o.useMemo)(()=>y("question"),[]),a=e=>e.map((e,t)=>{var a;return{node:{id:`question-${n}-${t}`,name:null!==(a=e.title)&&void 0!==a?a:e.prompt,navigable:!1,selectable:!0,icon:"question-circle",data:{type:"question",prompt:e.prompt,title:e.title,context:e.context||[]}},occurrences:[]}}),r=b(e,a(t));return e=>{r(a(e))}}function U(){const e=v({allowQuestions:!0,allowComponents:!1});return D(e)}const D=e=>e.filter(e=>{var t;return"question"===(null===(t=e.node.data)||void 0===t?void 0:t.type)}).map(e=>{var t,n,a;return{prompt:(null===(t=e.node.data)||void 0===t?void 0:t.prompt)||e.node.name,title:null===(n=e.node.data)||void 0===n?void 0:n.title,context:(null===(a=e.node.data)||void 0===a?void 0:a.context)||[]}}),q="grafana-assistant-app/callback/v0-alpha";function B(e,t){return{namespace:e,functions:t}}function F(e){return{title:"callback",targets:[q],fn:()=>e.map(e=>({namespace:e.namespace,functions:e.functions}))}}const M=require("rxjs"),O="grafana-assistant-app",G="Grafana Assistant",z=10,W=100,V=5e3;function Q(){return s.getObservablePluginLinks?(0,M.defer)(()=>{try{return(0,s.getObservablePluginLinks)({extensionPointId:"grafana/extension-sidebar/v0-alpha"}).pipe((0,M.map)(e=>e.some(e=>e.pluginId===O&&e.title===G)))}catch(e){return(0,M.throwError)(()=>e)}}).pipe((0,M.retry)({count:z,delay:(e,t)=>{var n;const a=(null===(n=null==e?void 0:e.message)||void 0===n?void 0:n.toLowerCase())||"";if(!(a.includes("can only be used after")||a.includes("grafana instance has started")||a.includes("not started")))throw e;const r=Math.min(W*2**(t-1),V);return(0,M.timer)(r)}}),(0,M.catchError)(()=>(0,M.of)(!1))):(0,M.of)(!1)}const K=require("@grafana/data");class H extends K.BusEventWithPayload{}H.type="open-extension-sidebar";class J extends K.BusEventBase{}J.type="close-extension-sidebar";class X extends K.BusEventWithPayload{}function Y(e){var t;(0,s.reportInteraction)("grafana_assistant_app_opened_sidebar",{from:e.origin}),function(e,t,n){const a=new H({pluginId:e,componentTitle:t,props:n});(0,s.getAppEvents)().publish(a)}(O,G,{initialPrompt:e.prompt,initialContext:e.context,initialAutoSend:null===(t=e.autoSend)||void 0===t||t,origin:e.origin,initialMode:e.mode,chatId:e.chatId,appendContext:e.appendContext})}function Z(){!function(){const e=new J;(0,s.getAppEvents)().publish(e)}()}function ee(e){var t,n;(0,s.reportInteraction)("grafana_assistant_app_toggled_sidebar",{from:e.origin,prompt:null!==(t=e.prompt)&&void 0!==t?t:""}),function(e,t,n){const a=new X({pluginId:e,componentTitle:t,props:n});(0,s.getAppEvents)().publish(a)}(O,G,{initialPrompt:e.prompt,initialContext:e.context,initialAutoSend:null===(n=e.autoSend)||void 0===n||n,origin:e.origin,initialMode:e.mode,chatId:e.chatId,appendContext:e.appendContext})}function te(){const[e,t]=(0,o.useState)(void 0);(0,o.useEffect)(()=>{const e=Q().subscribe(t);return()=>e.unsubscribe()},[]);const n=null!=e&&e;return{isLoading:void 0===e,isAvailable:n,openAssistant:n?Y:void 0,closeAssistant:n?Z:void 0,toggleAssistant:n?ee:void 0}}X.type="toggle-extension-sidebar";const ne=require("react/jsx-runtime"),ae=require("@grafana/ui"),re=require("@emotion/css");function se(e){const{isAvailable:t,openAssistant:n}=te();return t&&n?(0,ne.jsx)(oe,{...e,openAssistant:n}):null}function oe({prompt:e,origin:t,context:n,autoSend:a=!0,title:r="Analyze with Assistant",size:i="sm",iconOnlyButton:l=!1,openAssistant:d,onClick:c}){const u=(0,ae.useStyles2)(ie);return(0,o.useEffect)(()=>{(0,s.reportInteraction)("grafana_assistant_app_open_sidebar_button_displayed",{from:t})},[t]),(0,ne.jsx)(ne.Fragment,{children:l?(0,ne.jsx)(ae.IconButton,{name:"ai-sparkle",onClick:()=>{null==c||c(),d({prompt:e,context:n,autoSend:a,origin:t})},variant:"secondary",size:i,"aria-label":r,className:u.icon,tooltip:r,"data-testid":"assistant-icon-button"}):(0,ne.jsx)(ae.Button,{icon:"ai-sparkle",onClick:()=>{null==c||c(),d({prompt:e,context:n,autoSend:a,origin:t})},variant:"secondary",fill:"solid",size:i,title:r,"aria-label":r,className:u.button,"data-testid":"assistant-button",children:r})})}const ie=e=>{const t=e.colors.secondary.main,n=e.colors.emphasize(t,.05),a=e.colors.background.canvas,r=e.shape.radius.default,s=`max(calc(${r} - 1px), 1px)`,o={content:'""',position:"absolute",inset:0,borderRadius:r,cornerShape:"squircle",background:"linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))",zIndex:-2,pointerEvents:"none"},i=e=>({content:'""',position:"absolute",inset:"1px",borderRadius:s,cornerShape:"squircle",background:`linear-gradient(${e}, ${e}), ${a}`,zIndex:-1,transition:"none",pointerEvents:"none"});return{button:(0,re.css)({label:"assistant-button",width:"fit-content",maxWidth:"100%",position:"relative",isolation:"isolate",border:"none",transition:"none !important","&::before":o,"&::after":{...i(t),transition:"none"},"&:hover":{transition:"none !important"},"&:hover::after":{background:`linear-gradient(${n}, ${n}), ${a}`}}),icon:(0,re.css)({label:"assistant-icon",position:"relative",isolation:"isolate",border:"none",background:"none",padding:e.spacing(.5),"&::before":{...o,transition:"background 0.1s ease"},"&:hover::after":{...i(t),background:`linear-gradient(${n}, ${n}), ${a}`}})}},le={sm:32,md:36,lg:40};function de(e){const{isAvailable:t,openAssistant:n}=te();return t&&n?(0,ne.jsx)(ce,{...e,openAssistant:n}):null}function ce({prompt:e,origin:t,context:n,autoSend:a=!0,title:r="Chat with Assistant",size:i="sm",onClick:l,menuItems:d,tooltip:c,dropdownButtonWidth:u,openAssistant:p}){const m=(0,ae.useStyles2)(ue),g=Boolean(d),f="number"==typeof(h=null!=u?u:le[i])?`${h}px`:h;var h;(0,o.useEffect)(()=>{(0,s.reportInteraction)("grafana_assistant_app_open_sidebar_split_button_displayed",{from:t})},[t]);const b=(0,ne.jsx)("div",{className:m.wrapper,children:(0,ne.jsxs)(ae.ButtonGroup,{className:m.buttonGroup,children:[(0,ne.jsx)(ae.Button,{icon:"ai-sparkle",onClick:()=>{null==l||l(),p({prompt:e,context:n,autoSend:a,origin:t})},variant:"secondary",fill:"solid",size:i,"aria-label":r,className:(0,re.cx)(m.segmentButton,g?m.mainButtonSplit:m.mainButtonSolo),"data-testid":"assistant-split-button-main",children:r}),d&&(0,ne.jsx)(ae.Dropdown,{overlay:d,children:(0,ne.jsx)(ae.Button,{variant:"secondary",icon:"angle-down",size:i,"aria-label":"More AI actions",className:(0,re.cx)(m.segmentButton,m.dropdownButton),style:{width:f,minWidth:f},"data-testid":"assistant-split-button-dropdown"})})]})});return c?(0,ne.jsx)(ae.Tooltip,{content:c,children:b}):b}const ue=e=>{const t=e.colors.secondary.main,n=e.colors.emphasize(t,.05),a=e.colors.background.canvas,r=e.colors.border.weak,s=e.shape.radius.default,o=`max(calc(${s} - 1px), 1px)`;return{wrapper:(0,re.css)({label:"assistant-split-button-wrapper",position:"relative",isolation:"isolate",display:"inline-block","&::before":{content:'""',position:"absolute",inset:0,borderRadius:s,cornerShape:"squircle",background:"linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))",zIndex:-1,pointerEvents:"none"},"&::after":{content:'""',position:"absolute",inset:"1px",borderRadius:o,cornerShape:"squircle",background:`linear-gradient(${t}, ${t}), ${a}`,zIndex:-1,pointerEvents:"none"}}),buttonGroup:(0,re.css)({label:"assistant-split-button-group",gap:0,position:"relative",zIndex:1,borderRadius:o,overflow:"hidden","& button":{border:"none",boxShadow:"none",background:"transparent !important"}}),segmentButton:(0,re.css)({label:"assistant-split-button-segment",position:"relative","&:hover":{background:`${n} !important`},"&:focus-visible":{background:`${n} !important`},'&[aria-expanded="true"]':{background:`${n} !important`}}),mainButtonSolo:(0,re.css)({label:"assistant-split-button-main-solo",borderRadius:o}),mainButtonSplit:(0,re.css)({label:"assistant-split-button-main-split",borderTopLeftRadius:o,borderBottomLeftRadius:o,borderTopRightRadius:0,borderBottomRightRadius:0}),dropdownButton:(0,re.css)({label:"assistant-split-button-dropdown",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:0,borderTopLeftRadius:0,borderBottomLeftRadius:0,borderTopRightRadius:o,borderBottomRightRadius:o,padding:"0 !important",boxShadow:`inset 1px 0 0 ${r}`,"& svg":{margin:0}})}},pe=e=>{const t=["rgb(168, 85, 247)","rgb(249, 115, 22)"];if("dark"===e.name.toLowerCase()||"light"===e.name.toLowerCase())return t;const n=e.colors.gradients.brandHorizontal.match(/#[0-9A-Fa-f]{6}/g);return!n||n.length<2?t:[n[0],n[1]]},me=(e,t,n,a)=>{const r=Array.from({length:101},(e,t)=>t),s={},[o,i]=pe(e),l=null!=n?n:o,d=null!=a?a:i;for(const e of r)s[`${e}%`]={backgroundImage:`\n linear-gradient(${t}, ${t}),\n conic-gradient(from ${3.6*e}deg, transparent 60%, ${l} 80%, ${d} 100%, transparent 15%)\n `};return s},ge="__grafanaAssistantInlineFactory__",fe="__grafanaAssistantInlineInitializer__",he="__grafanaAssistantInlineInitPromise__";function be(e){const t=window[ge];t&&t!==e?console.warn("InlineAssistant factory already set; ignoring subsequent setInlineAssistantFactory call"):t||(window[ge]=e)}function ve(e){const t=window[fe];t&&t!==e?console.warn("InlineAssistant initializer already set; ignoring subsequent setInlineAssistantInitializer call"):t||(window[fe]=e)}async function ye(){if(window[ge])return;const e=window[fe];if(!e)throw new Error("InlineAssistant not initialized. Make sure the Grafana Assistant plugin is loaded and initialized.");const t=window[he];if(t)return t;const n=(async()=>{try{await e()}catch(e){throw window[he]=null,e}})();return window[he]=n,n}function xe(){const e=window[ge];if(!e)throw new Error("InlineAssistant factory not initialized. Make sure the Grafana Assistant plugin is loaded.");return e}const we=["message","error","err","detail","details"];function Ee(e){if("string"!=typeof e)return null;const t=e.trim();return""===t?null:t}function ke(e,t=new Set){var n;const a=Ee(e);if(a)return a;if(e instanceof Error){const a=Ee(e.message);if((r=a)&&"[object Object]"!==r&&"Error"!==r&&"Unknown error"!==r)return a;const s=ke(e.cause,t);if(s)return s;return ke(Object.fromEntries(Object.entries(e).filter(([e])=>"message"!==e&&"name"!==e)),t)||(null!==(n=null!=a?a:Ee(e.name))&&void 0!==n?n:null)}var r;if(!e||"object"!=typeof e)return null;if(t.has(e))return null;t.add(e);const s=e;if("data"in s){const e=ke(s.data,t);if(e)return e}for(const e of we)if(e in s){const n=ke(s[e],t);if(n)return n}const o=s.status,i=Ee(s.statusText);if(("number"==typeof o||"string"==typeof o)&&i)return`HTTP ${o}: ${i}`;if(Array.isArray(e)){const n=e.map(e=>ke(e,t)).filter(e=>Boolean(e));if(n.length>0)return n.join("; ")}return null}function Se(e){const t=ke(e);if(t)return t;if(e&&"object"==typeof e)try{return JSON.stringify(e)}catch(e){return"Unknown error (could not serialize error object)"}return null==e?"Unknown error":String(e)}function Ie(){const[e,t]=(0,o.useState)(!1),[n,a]=(0,o.useState)(""),[r,s]=(0,o.useState)(null),i=(0,o.useRef)(null),l=(0,o.useCallback)(()=>{s(null),a("")},[]),d=(0,o.useCallback)(()=>{i.current&&i.current.cancel(),t(!1)},[]),c=(0,o.useCallback)(async e=>{var n;s(null),a(""),t(!0);try{await ye();const n=xe();i.current||(i.current=await n(e.origin)),await i.current.sendPrompt({prompt:e.prompt,agentName:e.agentName,agentId:e.agentId,systemPrompt:e.systemPrompt,tools:e.tools,onStart:()=>{t(!0)},onDelta:t=>{var n;a(e=>e+t),null===(n=e.onDelta)||void 0===n||n.call(e,t)},onComplete:n=>{var r;a(n),t(!1),null===(r=e.onComplete)||void 0===r||r.call(e,n)},onError:n=>{var a;s(n),t(!1),null===(a=e.onError)||void 0===a||a.call(e,n)}})}catch(a){const r=new Error(Se(a),{cause:a});s(r),t(!1),null===(n=e.onError)||void 0===n||n.call(e,r)}},[]);return(0,o.useEffect)(()=>()=>{i.current&&(i.current.cancel(),i.current.dispose(),i.current=null)},[]),{generate:c,isGenerating:e,content:n,error:r,cancel:d,reset:l}}function Ae({value:e,onChange:t,origin:n,systemPrompt:a,onComplete:r,onError:s,onDelta:i,disabled:l=!1,autoGenerate:d=!1,streaming:c=!1,getUserPrompt:u}){const{generate:p,isGenerating:m,content:g,error:f,reset:h}=Ie(),b=(0,o.useRef)(!1),v=(0,o.useRef)(e),y=(0,o.useRef)(u);y.current=u;const x=m?c?g:"":e,w=!(u?u(e.trim()):e.trim())||l||m,E=(0,o.useCallback)(o=>{v.current=e,t(""),h(),p({prompt:o,origin:n,systemPrompt:a,onDelta:i,onComplete:e=>{t(e),null==r||r(e)},onError:e=>{t(v.current),null==s||s(e)}})},[e,t,n,a,i,r,s,p,h]),k=(0,o.useRef)(()=>{});return k.current=()=>{!d||!a||e||b.current||l||(b.current=!0,E(a))},(0,o.useEffect)(()=>{k.current()},[]),{displayValue:x,isSendDisabled:w,handleGenerate:(0,o.useCallback)(()=>{const t=y.current,n=t?t(e.trim()):e.trim();!n||l||m||E(n)},[e,l,m,E]),isGenerating:m,error:f}}const Ce=["Generating...","Brewing...","Cooking...","Crunching...","Phrasing...","Wording...","Crafting...","Composing...","Drafting...","Shaping...","Forming...","Molding...","Sketching...","Whipping up...","Conjuring...","Stirring..."];function Te(e,t){const[n,a]=(0,o.useState)(""),r=(0,o.useRef)(!1);if(e&&!r.current){const e=Ce[Math.floor(Math.random()*Ce.length)];return a(e),r.current=!0,e}return e||(r.current=!1),e?n:t}function Le({value:e,onChange:t,placeholder:n,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l=!1,autoGenerate:d=!1,streaming:c=!1,getUserPrompt:u,className:p,"data-testid":m}){const{displayValue:g,isSendDisabled:f,handleGenerate:h,isGenerating:b,error:v}=Ae({value:e,onChange:t,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l,autoGenerate:d,streaming:c,getUserPrompt:u}),y=(0,ae.useStyles2)($e),x=Te(b,null!=n?n:"Ask AI to generate..."),w=(0,ne.jsx)(ae.IconButton,{name:"ai-sparkle",onClick:h,disabled:f,tooltip:f?"Enter text to generate":"Generate with AI","data-testid":m?`${m}-send`:void 0});return(0,ne.jsx)("div",{className:(0,re.cx)(y.wrapper,{[y.animatedWrapper]:b},p),"data-testid":m,children:(0,ne.jsx)(ae.Input,{value:g,onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),h())},onChange:e=>t(e.currentTarget.value),placeholder:x,disabled:l||b,suffix:w,invalid:!!v,"data-testid":m?`${m}-input`:void 0})})}const $e=e=>{const t=e.colors.background.primary,n=(0,re.keyframes)({label:"ai-input-border-animation",...me(e,t)}),[a,r]=pe(e);return{wrapper:(0,re.css)({label:"ai-text-input-wrapper",position:"relative",border:"1px solid transparent",borderRadius:e.shape.radius.default,cornerShape:"squircle"}),animatedWrapper:(0,re.css)({label:"ai-text-input-animated",border:"1px solid transparent",backgroundImage:`\n linear-gradient(${t}, ${t}),\n conic-gradient(from 0deg, transparent 60%, ${a} 80%, ${r} 100%, transparent 15%)\n `,backgroundOrigin:"border-box",backgroundClip:"padding-box, border-box",animation:`${n} 2s linear infinite`,"& input":{border:"none !important"}})}};function Ne({value:e,onChange:t,placeholder:n,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l=!1,autoGenerate:d=!1,streaming:c=!1,getUserPrompt:u,rows:p=4,className:m,"data-testid":g}){const{displayValue:f,isSendDisabled:h,handleGenerate:b,isGenerating:v,error:y}=Ae({value:e,onChange:t,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l,autoGenerate:d,streaming:c,getUserPrompt:u}),x=(0,ae.useStyles2)(_e),w=Te(v,null!=n?n:"Ask AI to generate... (Cmd/Ctrl+Enter to send)"),E=Math.max(p,2);return(0,ne.jsxs)("div",{className:(0,re.cx)(x.textareaWrapper,{[x.animatedWrapper]:v},m),"data-testid":g,children:[(0,ne.jsx)(ae.TextArea,{value:f,onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())},onChange:e=>t(e.currentTarget.value),placeholder:w,disabled:l||v,rows:E,className:x.textarea,invalid:!!y,"data-testid":g?`${g}-textarea`:void 0}),(0,ne.jsx)(ae.IconButton,{name:"ai-sparkle",onClick:b,disabled:h,className:x.sendButton,"aria-label":"Generate with AI",tooltip:h?"Enter text to generate":"Generate with AI (Cmd/Ctrl+Enter)","data-testid":g?`${g}-send`:void 0})]})}const _e=e=>{const t=e.colors.background.primary,n=(0,re.keyframes)({label:"ai-textarea-border-animation",...me(e,t)}),[a,r]=pe(e);return{textareaWrapper:(0,re.css)({label:"ai-textarea-wrapper",position:"relative",border:"1px solid transparent",borderRadius:e.shape.radius.default,cornerShape:"squircle"}),animatedWrapper:(0,re.css)({label:"ai-textarea-animated",border:"1px solid transparent",backgroundImage:`\n linear-gradient(${t}, ${t}),\n conic-gradient(from 0deg, transparent 60%, ${a} 80%, ${r} 100%, transparent 15%)\n `,backgroundOrigin:"border-box",backgroundClip:"padding-box, border-box",animation:`${n} 2s linear infinite`,"& textarea":{border:"none !important"}}),textarea:(0,re.css)({label:"ai-textarea",paddingRight:e.spacing(4),minHeight:e.spacing(6),"& textarea":{minHeight:e.spacing(6)},scrollbarWidth:"none","&::-webkit-scrollbar":{display:"none"}}),sendButton:(0,re.css)({label:"ai-textarea-send",position:"absolute",right:e.spacing(1),top:e.spacing(1)})}};function Pe(e){const t=["refId","hide","key","queryType","datasource"];for(const n in e)if("label"!==n&&!t.includes(n))return!1;return!0}function je({size:e,currentQuery:t,queries:n,dataSourceInstanceSettings:a,app:r,datasourceApi:s,title:o="Query with Assistant"}){var i;const{isAvailable:l,openAssistant:d}=te();if(!l||!d)return null;const c=`grafana/query-editor/${a.type}/${null!==(i=null!=r?r:K.CoreApp.Unknown)&&void 0!==i?i:"unknown"}`,u=!Pe(t),p=n.filter(e=>e.refId!==t.refId&&!Pe(e)),m=[_("datasource",{datasourceUid:a.uid})];u&&m.push(_("structured",{title:"Current query",data:t})),p.length>0&&m.push(_("structured",{title:"Other queries",data:{queries:p}}));const g=u&&(null==s?void 0:s.getQueryDisplayText)?s.getQueryDisplayText(t):null,f=!!g,h=f?"Help me update the current query to answer my questions and provide the insights I need.":"Help me create a new query to answer my questions and provide the insights I need.",b=[];g&&b.push(`Current query: ${g}`),b.push(`Selected data source: ${a.name}`);const v=f?"Please describe what you want to change or improve in this query.":"Please describe what you want to query and what insights you're looking for.",y=[h,"```",...b,"```",v].join("\n");return(0,ne.jsx)(oe,{prompt:y,origin:c,context:m,autoSend:!1,title:o,size:e,openAssistant:d})}const Re=["What does this panel show?","Explain the trend in this data","Why is there a spike?","Add a threshold at 80%","Change the legend to table mode"];function Ue(e){const{isAvailable:t,openAssistant:n}=te();return t&&n?(0,ne.jsx)(De,{...e,openAssistant:n}):null}function De({origin:e,context:t,mode:n,placeholder:a,examplePrompts:r,animated:i=!0,onClose:l,onSubmit:d,onClick:c,className:u,openAssistant:p}){const[m,g]=(0,o.useState)(""),f=(0,o.useRef)(null),h=(0,ae.useStyles2)(Be),b=null!=a?a:"Ask Assistant...",v=function(e,t,n){const[a,r]=(0,o.useState)(""),s=(0,o.useRef)(0),i=(0,o.useRef)(0),l=(0,o.useRef)("typing");return(0,o.useEffect)(()=>{if(s.current=0,i.current=0,l.current="typing",r(""),n||0===t.length)return;let e;const a=()=>{e=setTimeout(()=>{(()=>{const e=t[s.current];"typing"===l.current?(i.current++,r(e.slice(0,i.current)),i.current>=e.length&&(l.current="pause")):"pause"===l.current?l.current="erasing":"erasing"===l.current&&(i.current--,r(e.slice(0,i.current)),i.current<=0&&(l.current="typing",s.current=(s.current+1)%t.length))})(),a()},"pause"===l.current?800:"erasing"===l.current?15:30+20*Math.random())};return a(),()=>clearTimeout(e)},[n,t]),n||0===t.length?e:a}(b,null!=r?r:void 0!==a?[]:Re,m.length>0);(0,o.useEffect)(()=>{(0,s.reportInteraction)("grafana_assistant_app_prompt_card_displayed",{from:e})},[e]),(0,o.useEffect)(()=>{const e=requestAnimationFrame(()=>{var e;return null===(e=f.current)||void 0===e?void 0:e.focus()});return()=>cancelAnimationFrame(e)},[t]);const y=(0,o.useCallback)(a=>{const r=a.trim();r&&(p({prompt:r,context:t,autoSend:!0,origin:e,mode:n}),null==d||d(r),g(""))},[p,t,e,n,d]);return(0,ne.jsx)("div",{className:(0,re.cx)(i?h.card:h.cardStatic,u),onClick:c,role:"search","aria-label":b,"data-testid":"assistant-prompt-card",children:(0,ne.jsx)("div",{className:h.inputRow,children:(0,ne.jsx)(ae.Input,{ref:f,value:m,onChange:e=>g(e.currentTarget.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),y(m)),"Escape"===e.key&&(e.preventDefault(),null==l||l())},placeholder:v,suffix:(0,ne.jsx)(ae.IconButton,{name:"ai-sparkle",onClick:()=>y(m),disabled:!m.trim(),tooltip:"Send to assistant","aria-label":"Send to assistant","data-testid":"assistant-prompt-card-send"}),"data-testid":"assistant-prompt-card-input"})})})}function qe(e){return["rgba(168, 85, 247, 0.25) 3px -1px 20px","rgba(249, 115, 22, 0.18) -5px 3px 40px","rgba(168, 85, 247, 0.12) 7px 4px 60px",(e.isDark?"rgb(17 18 23)":"rgb(245 245 245)")+" 0 6px 30px"].join(", ")}const Be=e=>{const t=e.colors.background.primary,[n,a]=pe(e),r=(0,re.keyframes)({label:"prompt-card-border",...me(e,t)}),s={label:"assistant-prompt-card",position:"relative",display:"flex",flexDirection:"column",gap:e.spacing(1),padding:e.spacing(1),borderRadius:e.shape.radius.lg,boxShadow:qe(e)};return{card:(0,re.css)({...s,cornerShape:"squircle",background:t,border:"1px solid transparent",backgroundImage:`\n linear-gradient(${t}, ${t}),\n conic-gradient(from 0deg, transparent 60%, ${n} 80%, ${a} 100%, transparent 15%)\n `,backgroundOrigin:"border-box",backgroundClip:"padding-box, border-box",[e.transitions.handleMotion("no-preference")]:{animation:`${r} 2s linear infinite`}}),cardStatic:(0,re.css)({...s,label:"assistant-prompt-card-static",background:e.colors.background.elevated,border:`1px solid ${e.colors.border.weak}`}),inputRow:(0,re.css)({label:"prompt-card-input-row",display:"flex",alignItems:"center",gap:e.spacing(.5),"& input":{border:"none !important"}})}};function Fe(e){const t=e.split("+")[0].split("-"),n=t[0],a=t.length>1?t.slice(1).join("-"):void 0,r=n.split(".").map(Number);return 3!==r.length||r.some(isNaN)?null:{major:r[0],minor:r[1],patch:r[2],prerelease:a}}const Me="grafana-assistant-terms-and-conditions-refresh";async function Oe(){var e;const t=(0,s.getBackendSrv)(),n=`/api/plugins/${O}/resources/api/v1/settings/terms`,a=(await(0,M.lastValueFrom)(t.fetch({url:n,method:"GET",showErrorAlert:!1}))).data.data,r=null!==(e=a.acceptedTermsAndConditions)&&void 0!==e&&e,o=a.acceptedVersion,i=a.version,l=a.termsType;if("msa"===l)return{accepted:r,termsType:l};if(!r||!o||!i)return{accepted:!1,termsType:l};const d=1===function(e,t){const n=Fe(e),a=Fe(t);return n&&a?n.major!==a.major?n.major>a.major?1:-1:n.minor!==a.minor?n.minor>a.minor?1:-1:n.patch!==a.patch?n.patch>a.patch?1:-1:n.prerelease&&a.prerelease?n.prerelease===a.prerelease?0:n.prerelease>a.prerelease?1:-1:n.prerelease&&!a.prerelease?-1:!n.prerelease&&a.prerelease?1:0:null}(i,o);return{accepted:r&&!d,termsType:l}}async function Ge(){try{return(await Oe()).accepted}catch(e){throw new Error(`Failed to check terms requirements: ${e instanceof Error?e.message:String(e)}`)}}function ze(){const[e,t]=(0,o.useState)(!1),[n,a]=(0,o.useState)(null),[r,s]=(0,o.useState)(!0),[i,l]=(0,o.useState)(null);return(0,o.useEffect)(()=>{async function e(){try{s(!0),l(null);const e=await Oe();t(e.accepted),a(e.termsType)}catch(e){const n=e instanceof Error?e.message:"Failed to check terms";l(n),t(!1),a(null)}finally{s(!1)}}e();const n=()=>{e()};return document.addEventListener(Me,n),()=>{document.removeEventListener(Me,n)}},[]),{accepted:e,termsType:n,loading:r,error:i}}function We(e,t){var n;const{explainer:a,...r}=null!==(n=t.metadata)&&void 0!==n?n:{},s={name:t.name,description:t.description,inputSchema:t.inputSchema,metadata:a?{...r,explainer:e=>a(e)}:r,responseFormat:t.responseFormat,verboseParsingErrors:t.verboseParsingErrors,async invoke(n,a){var r;try{if(null===(r=a.signal)||void 0===r?void 0:r.aborted)throw new Error(`Tool ${t.name} execution was aborted`);const s=t.validate(n),o=[e(s,a)];return a.signal&&o.push(new Promise((e,n)=>{var r;null===(r=a.signal)||void 0===r||r.addEventListener("abort",()=>{n(new Error(`Tool ${t.name} execution was aborted`))},{once:!0})})),a.timeout&&a.timeout>0&&o.push(new Promise((e,n)=>{setTimeout(()=>{n(new Error(`Tool ${t.name} execution timed out after ${a.timeout}ms`))},a.timeout)})),Promise.race(o)}catch(e){throw t.verboseParsingErrors&&console.error(`Error invoking tool ${t.name}:`,e,n),e}}};return s}const Ve="grafana-assistant-limits-updated";async function Qe(){var e,t,n;const a=(0,s.getBackendSrv)(),r=`/api/plugins/${O}/resources/api/v1/usage/limits/prompt`,o=(await(0,M.lastValueFrom)(a.fetch({url:r,method:"GET",showErrorAlert:!1}))).data.data,i=null!==(e=o.total)&&void 0!==e?e:0,l=null!==(t=o.limit)&&void 0!==t?t:0;return{count:i,limit:l,month:null!==(n=o.month)&&void 0!==n?n:"",isLimitReached:l>0&&i>=l}}async function Ke(){try{return await Qe()}catch(e){throw new Error(`Failed to check limits: ${e instanceof Error?e.message:String(e)}`)}}function He(){const[e,t]=(0,o.useState)(0),[n,a]=(0,o.useState)(0),[r,s]=(0,o.useState)(""),[i,l]=(0,o.useState)(!0),[d,c]=(0,o.useState)(null),u=(0,o.useCallback)(async()=>{try{l(!0),c(null);const e=await Qe();t(e.count),a(e.limit),s(e.month)}catch(e){const n=e instanceof Error?e.message:"Failed to fetch limits";c(n),t(0),a(0),s("")}finally{l(!1)}},[]);return(0,o.useEffect)(()=>{u()},[u]),(0,o.useEffect)(()=>{const e=e=>{const n=e;n.detail&&(t(n.detail.count),a(n.detail.limit),c(null))};return window.addEventListener(Ve,e),()=>{window.removeEventListener(Ve,e)}},[]),{count:e,limit:n,month:r,isLimitReached:n>0&&e>=n,loading:i,error:d,refetch:u}}class Je extends K.BusEventWithPayload{}function Xe(e){const t=(0,s.getAppEvents)().subscribe(Je,t=>{e(t.payload)});return()=>t.unsubscribe()}Je.type="grafana-assistant:k6-set-script-content",module.exports=t})();
|
|
2
2
|
//# sourceMappingURL=index.js.map
|