@grafana/assistant 0.1.31 → 0.1.33
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/dist/esm/components/button/OpenAssistantButton.js +106 -0
- package/dist/esm/components/button/OpenAssistantButton.js.map +1 -0
- package/dist/esm/components/button/OpenAssistantSplitButton.js +135 -0
- package/dist/esm/components/button/OpenAssistantSplitButton.js.map +1 -0
- package/dist/esm/components/button/QueryWithAssistantButton.js +62 -0
- package/dist/esm/components/button/QueryWithAssistantButton.js.map +1 -0
- package/dist/esm/components/index.js +8 -0
- package/dist/esm/components/index.js.map +1 -0
- package/dist/esm/components/input/AITextArea.js +91 -0
- package/dist/esm/components/input/AITextArea.js.map +1 -0
- package/dist/esm/components/input/AITextInput.js +70 -0
- package/dist/esm/components/input/AITextInput.js.map +1 -0
- package/dist/esm/components/input/types.js +2 -0
- package/dist/esm/components/input/types.js.map +1 -0
- package/dist/esm/components/input/useAIGeneration.js +58 -0
- package/dist/esm/components/input/useAIGeneration.js.map +1 -0
- package/dist/esm/components/input/useGeneratingPlaceholder.js +38 -0
- package/dist/esm/components/input/useGeneratingPlaceholder.js.map +1 -0
- package/dist/esm/components/prompt-card/AssistantPromptCard.js +115 -0
- package/dist/esm/components/prompt-card/AssistantPromptCard.js.map +1 -0
- package/dist/esm/components/prompt-card/useAnimatedPlaceholder.js +68 -0
- package/dist/esm/components/prompt-card/useAnimatedPlaceholder.js.map +1 -0
- package/dist/esm/context/base.js +47 -0
- package/dist/esm/context/base.js.map +1 -0
- package/dist/esm/context/chat.js +78 -0
- package/dist/esm/context/chat.js.map +1 -0
- package/dist/esm/context/component.js +141 -0
- package/dist/esm/context/component.js.map +1 -0
- package/dist/esm/context/dashboard.js +49 -0
- package/dist/esm/context/dashboard.js.map +1 -0
- package/dist/esm/context/datasource.js +25 -0
- package/dist/esm/context/datasource.js.map +1 -0
- package/dist/esm/context/entity.js +35 -0
- package/dist/esm/context/entity.js.map +1 -0
- package/dist/esm/context/factory.js +60 -0
- package/dist/esm/context/factory.js.map +1 -0
- package/dist/esm/context/index.js +13 -0
- package/dist/esm/context/index.js.map +1 -0
- package/dist/esm/context/label.js +62 -0
- package/dist/esm/context/label.js.map +1 -0
- package/dist/esm/context/page.js +365 -0
- package/dist/esm/context/page.js.map +1 -0
- package/dist/esm/context/questions.js +111 -0
- package/dist/esm/context/questions.js.map +1 -0
- package/dist/esm/context/skill.js +28 -0
- package/dist/esm/context/skill.js.map +1 -0
- package/dist/esm/context/types.js +2 -0
- package/dist/esm/context/types.js.map +1 -0
- package/dist/esm/extension/extension.js +45 -0
- package/dist/esm/extension/extension.js.map +1 -0
- package/dist/esm/extension/index.js +2 -0
- package/dist/esm/extension/index.js.map +1 -0
- package/dist/esm/functions.js +22 -0
- package/dist/esm/functions.js.map +1 -0
- package/dist/esm/hook.js +23 -0
- package/dist/esm/hook.js.map +1 -0
- package/dist/esm/index.js +16 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/inline/index.js +3 -0
- package/dist/esm/inline/index.js.map +1 -0
- package/dist/esm/inline/inlineAssistant.js +75 -0
- package/dist/esm/inline/inlineAssistant.js.map +1 -0
- package/dist/esm/inline/types.js +2 -0
- package/dist/esm/inline/types.js.map +1 -0
- package/dist/esm/inline/useInlineAssistant.js +158 -0
- package/dist/esm/inline/useInlineAssistant.js.map +1 -0
- package/dist/esm/k6.js +33 -0
- package/dist/esm/k6.js.map +1 -0
- package/dist/esm/lens/index.js +3 -0
- package/dist/esm/lens/index.js.map +1 -0
- package/dist/esm/lens/investigationLens.js +103 -0
- package/dist/esm/lens/investigationLens.js.map +1 -0
- package/dist/esm/lens/types.js +2 -0
- package/dist/esm/lens/types.js.map +1 -0
- package/dist/esm/lens/useInvestigationThroughLens.js +125 -0
- package/dist/esm/lens/useInvestigationThroughLens.js.map +1 -0
- package/dist/esm/limits/index.js +140 -0
- package/dist/esm/limits/index.js.map +1 -0
- package/dist/esm/plugin.js +52 -0
- package/dist/esm/plugin.js.map +1 -0
- package/dist/esm/sidebar.js +81 -0
- package/dist/esm/sidebar.js.map +1 -0
- package/dist/esm/terms/index.js +136 -0
- package/dist/esm/terms/index.js.map +1 -0
- package/dist/esm/terms/settings.gen.js +6 -0
- package/dist/esm/terms/settings.gen.js.map +1 -0
- package/dist/esm/terms/versionCompare.js +83 -0
- package/dist/esm/terms/versionCompare.js.map +1 -0
- package/dist/esm/tools/index.js +2 -0
- package/dist/esm/tools/index.js.map +1 -0
- package/dist/esm/tools/toolFactory.js +64 -0
- package/dist/esm/tools/toolFactory.js.map +1 -0
- package/dist/esm/tools/types.js +2 -0
- package/dist/esm/tools/types.js.map +1 -0
- package/dist/esm/utils/errorHandling.js +95 -0
- package/dist/esm/utils/errorHandling.js.map +1 -0
- package/dist/esm/utils/hash.js +13 -0
- package/dist/esm/utils/hash.js.map +1 -0
- package/dist/esm/utils/theme.js +65 -0
- package/dist/esm/utils/theme.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/utils/errorHandling.d.ts.map +1 -1
- package/package.json +12 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"versionCompare.js","sourceRoot":"","sources":["../../../src/terms/versionCompare.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AASH;;;;GAIG;AACH,SAAS,YAAY,CAAC,OAAe;IACnC,6CAA6C;IAC7C,MAAM,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAE3C,0CAA0C;IAC1C,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACtC,MAAM,WAAW,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC7B,MAAM,UAAU,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAE3E,0BAA0B;IAC1B,MAAM,OAAO,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACnD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAChD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;QACjB,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;QACjB,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;QACjB,UAAU;KACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,eAAe,CAAC,EAAU,EAAE,EAAU;IAC7C,MAAM,OAAO,GAAG,YAAY,CAAC,EAAE,CAAC,CAAC;IACjC,MAAM,OAAO,GAAG,YAAY,CAAC,EAAE,CAAC,CAAC;IAEjC,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,wBAAwB;IACxB,IAAI,OAAO,CAAC,KAAK,KAAK,OAAO,CAAC,KAAK,EAAE,CAAC;QACpC,OAAO,OAAO,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,wBAAwB;IACxB,IAAI,OAAO,CAAC,KAAK,KAAK,OAAO,CAAC,KAAK,EAAE,CAAC;QACpC,OAAO,OAAO,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,wBAAwB;IACxB,IAAI,OAAO,CAAC,KAAK,KAAK,OAAO,CAAC,KAAK,EAAE,CAAC;QACpC,OAAO,OAAO,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,qDAAqD;IACrD,oDAAoD;IACpD,IAAI,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;QAC7C,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,CAAC,UAAU,EAAE,CAAC;YAC9C,OAAO,CAAC,CAAC;QACX,CAAC;QACD,OAAO,OAAO,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1D,CAAC;IAED,IAAI,OAAO,CAAC,UAAU,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;QAC9C,OAAO,CAAC,CAAC,CAAC,CAAC,4CAA4C;IACzD,CAAC;IAED,IAAI,CAAC,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;QAC9C,OAAO,CAAC,CAAC,CAAC,kDAAkD;IAC9D,CAAC;IAED,OAAO,CAAC,CAAC,CAAC,wDAAwD;AACpE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,EAAU,EAAE,EAAU;IACzD,MAAM,MAAM,GAAG,eAAe,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IACvC,OAAO,MAAM,KAAK,CAAC,CAAC;AACtB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates a tool with the given implementation, schema, and metadata.
|
|
3
|
+
* This is a zod-free implementation that accepts JSON Schema directly and a validation function.
|
|
4
|
+
*
|
|
5
|
+
* @param func The function implementation for the tool
|
|
6
|
+
* @param options Tool configuration options
|
|
7
|
+
* @returns A tool object that can be used in the agent
|
|
8
|
+
*/
|
|
9
|
+
export function createTool(func, options) {
|
|
10
|
+
var _a;
|
|
11
|
+
const { explainer, ...metadata } = (_a = options.metadata) !== null && _a !== void 0 ? _a : {};
|
|
12
|
+
const toolObj = {
|
|
13
|
+
name: options.name,
|
|
14
|
+
description: options.description,
|
|
15
|
+
inputSchema: options.inputSchema,
|
|
16
|
+
metadata: explainer
|
|
17
|
+
? {
|
|
18
|
+
...metadata,
|
|
19
|
+
explainer: (input) => explainer(input),
|
|
20
|
+
}
|
|
21
|
+
: metadata,
|
|
22
|
+
responseFormat: options.responseFormat,
|
|
23
|
+
verboseParsingErrors: options.verboseParsingErrors,
|
|
24
|
+
async invoke(input, invokeOptions) {
|
|
25
|
+
var _a;
|
|
26
|
+
try {
|
|
27
|
+
if ((_a = invokeOptions.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
|
|
28
|
+
throw new Error(`Tool ${options.name} execution was aborted`);
|
|
29
|
+
}
|
|
30
|
+
// Use the provided validation function instead of zod.parse()
|
|
31
|
+
const parsedInput = options.validate(input);
|
|
32
|
+
const functionPromise = func(parsedInput, invokeOptions);
|
|
33
|
+
const promises = [functionPromise];
|
|
34
|
+
if (invokeOptions.signal) {
|
|
35
|
+
promises.push(new Promise((_, reject) => {
|
|
36
|
+
var _a;
|
|
37
|
+
(_a = invokeOptions.signal) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', () => {
|
|
38
|
+
reject(new Error(`Tool ${options.name} execution was aborted`));
|
|
39
|
+
}, { once: true });
|
|
40
|
+
}));
|
|
41
|
+
}
|
|
42
|
+
// If we have a timeout, add a promise to handle it
|
|
43
|
+
if (invokeOptions.timeout && invokeOptions.timeout > 0) {
|
|
44
|
+
promises.push(new Promise((_, reject) => {
|
|
45
|
+
setTimeout(() => {
|
|
46
|
+
reject(new Error(`Tool ${options.name} execution timed out after ${invokeOptions.timeout}ms`));
|
|
47
|
+
}, invokeOptions.timeout);
|
|
48
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
// Race the function promise against the abort and timeout promises
|
|
51
|
+
return Promise.race(promises);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
// Handle parsing errors and wrap them in ToolError
|
|
55
|
+
if (options.verboseParsingErrors) {
|
|
56
|
+
console.error(`Error invoking tool ${options.name}:`, error, input);
|
|
57
|
+
}
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
return toolObj;
|
|
63
|
+
}
|
|
64
|
+
//# sourceMappingURL=toolFactory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"toolFactory.js","sourceRoot":"","sources":["../../../src/tools/toolFactory.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,MAAM,UAAU,UAAU,CACxB,IAAmE,EACnE,OAWC;;IAED,MAAM,EAAE,SAAS,EAAE,GAAG,QAAQ,EAAE,GAAG,MAAA,OAAO,CAAC,QAAQ,mCAAI,EAAE,CAAC;IAC1D,MAAM,OAAO,GAAuB;QAClC,IAAI,EAAE,OAAO,CAAC,IAAI;QAClB,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,QAAQ,EAAE,SAAS;YACjB,CAAC,CAAC;gBACE,GAAG,QAAQ;gBACX,SAAS,EAAE,CAAC,KAAiB,EAAE,EAAE,CAAC,SAAS,CAAC,KAAU,CAAC;aACxD;YACH,CAAC,CAAC,QAAQ;QACZ,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,oBAAoB,EAAE,OAAO,CAAC,oBAAoB;QAClD,KAAK,CAAC,MAAM,CAAC,KAAiB,EAAE,aAAgC;;YAC9D,IAAI,CAAC;gBACH,IAAI,MAAA,aAAa,CAAC,MAAM,0CAAE,OAAO,EAAE,CAAC;oBAClC,MAAM,IAAI,KAAK,CAAC,QAAQ,OAAO,CAAC,IAAI,wBAAwB,CAAC,CAAC;gBAChE,CAAC;gBAED,8DAA8D;gBAC9D,MAAM,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;gBAC5C,MAAM,eAAe,GAAG,IAAI,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;gBACzD,MAAM,QAAQ,GAAG,CAAC,eAAe,CAAC,CAAC;gBAEnC,IAAI,aAAa,CAAC,MAAM,EAAE,CAAC;oBACzB,QAAQ,CAAC,IAAI,CACX,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;;wBACxB,MAAA,aAAa,CAAC,MAAM,0CAAE,gBAAgB,CACpC,OAAO,EACP,GAAG,EAAE;4BACH,MAAM,CAAC,IAAI,KAAK,CAAC,QAAQ,OAAO,CAAC,IAAI,wBAAwB,CAAC,CAAC,CAAC;wBAClE,CAAC,EACD,EAAE,IAAI,EAAE,IAAI,EAAE,CACf,CAAC;oBACJ,CAAC,CAAC,CACH,CAAC;gBACJ,CAAC;gBAED,mDAAmD;gBACnD,IAAI,aAAa,CAAC,OAAO,IAAI,aAAa,CAAC,OAAO,GAAG,CAAC,EAAE,CAAC;oBACvD,QAAQ,CAAC,IAAI,CACX,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;wBACxB,UAAU,CAAC,GAAG,EAAE;4BACd,MAAM,CAAC,IAAI,KAAK,CAAC,QAAQ,OAAO,CAAC,IAAI,8BAA8B,aAAa,CAAC,OAAO,IAAI,CAAC,CAAC,CAAC;wBACjG,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC;oBAC5B,CAAC,CAAC,CACH,CAAC;gBACJ,CAAC;gBAED,mEAAmE;gBACnE,OAAO,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAChC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,mDAAmD;gBACnD,IAAI,OAAO,CAAC,oBAAoB,EAAE,CAAC;oBACjC,OAAO,CAAC,KAAK,CAAC,uBAAuB,OAAO,CAAC,IAAI,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;gBACtE,CAAC;gBACD,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;KACF,CAAC;IAEF,OAAO,OAAO,CAAC;AACjB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/tools/types.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
const nestedErrorKeys = ['message', 'error', 'err', 'detail', 'details'];
|
|
2
|
+
function getStringValue(value) {
|
|
3
|
+
if (typeof value !== 'string') {
|
|
4
|
+
return null;
|
|
5
|
+
}
|
|
6
|
+
const trimmedValue = value.trim();
|
|
7
|
+
return trimmedValue === '' ? null : trimmedValue;
|
|
8
|
+
}
|
|
9
|
+
function isUnhelpfulErrorMessage(message) {
|
|
10
|
+
if (!message) {
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
13
|
+
return message === '[object Object]' || message === 'Error' || message === 'Unknown error';
|
|
14
|
+
}
|
|
15
|
+
function extractNestedErrorMessage(error, visited = new Set()) {
|
|
16
|
+
var _a;
|
|
17
|
+
const directString = getStringValue(error);
|
|
18
|
+
if (directString) {
|
|
19
|
+
return directString;
|
|
20
|
+
}
|
|
21
|
+
if (error instanceof Error) {
|
|
22
|
+
const errorMessage = getStringValue(error.message);
|
|
23
|
+
if (!isUnhelpfulErrorMessage(errorMessage)) {
|
|
24
|
+
return errorMessage;
|
|
25
|
+
}
|
|
26
|
+
const nestedErrorMessage = extractNestedErrorMessage(error.cause, visited);
|
|
27
|
+
if (nestedErrorMessage) {
|
|
28
|
+
return nestedErrorMessage;
|
|
29
|
+
}
|
|
30
|
+
const ownPropertiesMessage = extractNestedErrorMessage(Object.fromEntries(Object.entries(error).filter(([key]) => key !== 'message' && key !== 'name')), visited);
|
|
31
|
+
if (ownPropertiesMessage) {
|
|
32
|
+
return ownPropertiesMessage;
|
|
33
|
+
}
|
|
34
|
+
return (_a = errorMessage !== null && errorMessage !== void 0 ? errorMessage : getStringValue(error.name)) !== null && _a !== void 0 ? _a : null;
|
|
35
|
+
}
|
|
36
|
+
if (!error || typeof error !== 'object') {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
if (visited.has(error)) {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
visited.add(error);
|
|
43
|
+
const errorRecord = error;
|
|
44
|
+
if ('data' in errorRecord) {
|
|
45
|
+
const nestedDataMessage = extractNestedErrorMessage(errorRecord.data, visited);
|
|
46
|
+
if (nestedDataMessage) {
|
|
47
|
+
return nestedDataMessage;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
for (const key of nestedErrorKeys) {
|
|
51
|
+
if (key in errorRecord) {
|
|
52
|
+
const nestedMessage = extractNestedErrorMessage(errorRecord[key], visited);
|
|
53
|
+
if (nestedMessage) {
|
|
54
|
+
return nestedMessage;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const status = errorRecord.status;
|
|
59
|
+
const statusText = getStringValue(errorRecord.statusText);
|
|
60
|
+
if ((typeof status === 'number' || typeof status === 'string') && statusText) {
|
|
61
|
+
return `HTTP ${status}: ${statusText}`;
|
|
62
|
+
}
|
|
63
|
+
if (Array.isArray(error)) {
|
|
64
|
+
const nestedMessages = error
|
|
65
|
+
.map((item) => extractNestedErrorMessage(item, visited))
|
|
66
|
+
.filter((message) => Boolean(message));
|
|
67
|
+
if (nestedMessages.length > 0) {
|
|
68
|
+
return nestedMessages.join('; ');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Extract error message from backend errors (handles various error formats).
|
|
75
|
+
*
|
|
76
|
+
* @internal SDK-private helper for useInlineAssistant. Not part of the public
|
|
77
|
+
* `@grafana/assistant` surface — do not re-export from `index.ts`.
|
|
78
|
+
*/
|
|
79
|
+
export function extractErrorMessage(error) {
|
|
80
|
+
const extractedMessage = extractNestedErrorMessage(error);
|
|
81
|
+
if (extractedMessage) {
|
|
82
|
+
return extractedMessage;
|
|
83
|
+
}
|
|
84
|
+
// Objects that expose no message are not serialized: fetch-like errors carry
|
|
85
|
+
// the request URL, headers and body on `config`, which would end up in the
|
|
86
|
+
// messages this helper feeds back to callers.
|
|
87
|
+
if (error && typeof error === 'object') {
|
|
88
|
+
return 'Unknown error';
|
|
89
|
+
}
|
|
90
|
+
if (error == null) {
|
|
91
|
+
return 'Unknown error';
|
|
92
|
+
}
|
|
93
|
+
return String(error);
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=errorHandling.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errorHandling.js","sourceRoot":"","sources":["../../../src/utils/errorHandling.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Simple hash function that generates a deterministic hash for a given input string.
|
|
3
|
+
* Uses the djb2 algorithm for simplicity and good distribution.
|
|
4
|
+
*/
|
|
5
|
+
export function hash(input) {
|
|
6
|
+
let hash = 5381;
|
|
7
|
+
for (let i = 0; i < input.length; i++) {
|
|
8
|
+
hash = (hash << 5) + hash + input.charCodeAt(i);
|
|
9
|
+
}
|
|
10
|
+
// Convert to positive hex string
|
|
11
|
+
return (hash >>> 0).toString(16);
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=hash.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hash.js","sourceRoot":"","sources":["../../../src/utils/hash.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,UAAU,IAAI,CAAC,KAAa;IAChC,IAAI,IAAI,GAAG,IAAI,CAAC;IAEhB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAClD,CAAC;IAED,iCAAiC;IACjC,OAAO,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;AACnC,CAAC"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Default gradient colors for the assistant
|
|
3
|
+
*/
|
|
4
|
+
const GRADIENT_COLORS = {
|
|
5
|
+
PURPLE: 'rgb(168, 85, 247)',
|
|
6
|
+
ORANGE: 'rgb(249, 115, 22)',
|
|
7
|
+
};
|
|
8
|
+
// FIXME: use SDK as single source of truth for these color schemes?
|
|
9
|
+
/**
|
|
10
|
+
* Returns the colors of the background gradient based on the theme.
|
|
11
|
+
*
|
|
12
|
+
* @param theme - The Grafana theme object.
|
|
13
|
+
* @returns The colors of the background gradient as tuple.
|
|
14
|
+
*/
|
|
15
|
+
export const getBackgroundGradientColors = (theme) => {
|
|
16
|
+
const defaultGradientColors = [GRADIENT_COLORS.PURPLE, GRADIENT_COLORS.ORANGE];
|
|
17
|
+
// Check if the theme does not use gradients by default
|
|
18
|
+
if (theme.name.toLowerCase() === 'dark' || theme.name.toLowerCase() === 'light') {
|
|
19
|
+
return defaultGradientColors;
|
|
20
|
+
}
|
|
21
|
+
// If the theme uses gradients, extract the colors from the gradient string
|
|
22
|
+
const gradientString = theme.colors.gradients.brandHorizontal;
|
|
23
|
+
const hexColorRegex = /#[0-9A-Fa-f]{6}/g;
|
|
24
|
+
const matches = gradientString.match(hexColorRegex);
|
|
25
|
+
if (!matches || matches.length < 2) {
|
|
26
|
+
// Fallback to default colors if extraction fails
|
|
27
|
+
return defaultGradientColors;
|
|
28
|
+
}
|
|
29
|
+
return [matches[0], matches[1]];
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Creates animation keyframes for a rotating gradient border effect.
|
|
33
|
+
* This is used for loading states in inputs and other components.
|
|
34
|
+
*
|
|
35
|
+
* @param theme - The Grafana theme object
|
|
36
|
+
* @param backgroundColor - The background color to use in the animation
|
|
37
|
+
* @param color1 - First gradient color (optional, defaults to theme purple)
|
|
38
|
+
* @param color2 - Second gradient color (optional, defaults to theme orange)
|
|
39
|
+
* @returns Animation keyframes object for use with @emotion/css keyframes
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```ts
|
|
43
|
+
* const borderAnimation = keyframes({
|
|
44
|
+
* label: 'border-animation',
|
|
45
|
+
* ...createBorderAnimation(theme, theme.colors.background.primary),
|
|
46
|
+
* });
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export const createBorderAnimation = (theme, backgroundColor, color1, color2) => {
|
|
50
|
+
const animationSteps = Array.from({ length: 101 }, (_, i) => i);
|
|
51
|
+
const animationFrames = {};
|
|
52
|
+
const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);
|
|
53
|
+
const finalColor1 = color1 !== null && color1 !== void 0 ? color1 : gradientColor1;
|
|
54
|
+
const finalColor2 = color2 !== null && color2 !== void 0 ? color2 : gradientColor2;
|
|
55
|
+
for (const step of animationSteps) {
|
|
56
|
+
animationFrames[`${step}%`] = {
|
|
57
|
+
backgroundImage: `
|
|
58
|
+
linear-gradient(${backgroundColor}, ${backgroundColor}),
|
|
59
|
+
conic-gradient(from ${step * 3.6}deg, transparent 60%, ${finalColor1} 80%, ${finalColor2} 100%, transparent 15%)
|
|
60
|
+
`,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
return animationFrames;
|
|
64
|
+
};
|
|
65
|
+
//# sourceMappingURL=theme.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"theme.js","sourceRoot":"","sources":["../../../src/utils/theme.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,eAAe,GAAG;IACtB,MAAM,EAAE,mBAAmB;IAC3B,MAAM,EAAE,mBAAmB;CACnB,CAAC;AAEX,oEAAoE;AAEpE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,KAAoB,EAAoB,EAAE;IACpF,MAAM,qBAAqB,GAAqB,CAAC,eAAe,CAAC,MAAM,EAAE,eAAe,CAAC,MAAM,CAAC,CAAC;IAEjG,uDAAuD;IACvD,IAAI,KAAK,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,OAAO,EAAE,CAAC;QAChF,OAAO,qBAAqB,CAAC;IAC/B,CAAC;IAED,2EAA2E;IAC3E,MAAM,cAAc,GAAG,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,eAAe,CAAC;IAC9D,MAAM,aAAa,GAAG,kBAAkB,CAAC;IACzC,MAAM,OAAO,GAAG,cAAc,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACpD,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACnC,iDAAiD;QACjD,OAAO,qBAAqB,CAAC;IAC/B,CAAC;IAED,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;AAClC,CAAC,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,KAAoB,EACpB,eAAuB,EACvB,MAAe,EACf,MAAe,EAC8B,EAAE;IAC/C,MAAM,cAAc,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;IAChE,MAAM,eAAe,GAAgD,EAAE,CAAC;IACxE,MAAM,CAAC,cAAc,EAAE,cAAc,CAAC,GAAG,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAE5E,MAAM,WAAW,GAAG,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,cAAc,CAAC;IAC7C,MAAM,WAAW,GAAG,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,cAAc,CAAC;IAE7C,KAAK,MAAM,IAAI,IAAI,cAAc,EAAE,CAAC;QAClC,eAAe,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG;YAC5B,eAAe,EAAE;0BACG,eAAe,KAAK,eAAe;8BAC/B,IAAI,GAAG,GAAG,yBAAyB,WAAW,SAAS,WAAW;OACzF;SACF,CAAC;IACJ,CAAC;IAED,OAAO,eAAe,CAAC;AACzB,CAAC,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:()=>$e,AITextInput:()=>_e,ASSISTANT_EXTENSION_POINT:()=>dt,ASSISTANT_PLUGIN_ID:()=>G,ASSISTANT_PLUGIN_TITLE:()=>z,AssistantPromptCard:()=>qe,AssistantPromptCardView:()=>De,CALLBACK_EXTENSION_POINT:()=>B,ComponentNodeData:()=>E,DashboardNodeData:()=>S,DatasourceNodeData:()=>L,EntityNodeData:()=>C,FolderNodeData:()=>A,InvestigationLensRequestError:()=>Fe,K6SetScriptContentEvent:()=>lt,LIMITS_UPDATED_EVENT:()=>rt,LabelNameNodeData:()=>T,LabelValueNodeData:()=>_,OpenAssistantButton:()=>oe,OpenAssistantSplitButton:()=>de,QueryWithAssistantButton:()=>je,SkillNodeData:()=>R,StructuredNodeData:()=>r,TERMS_AND_CONDITIONS_REFRESH_EVENT:()=>Ze,checkLimits:()=>ot,checkTerms:()=>tt,closeAssistant:()=>ee,createAssistantContextItem:()=>P,createTool:()=>at,ensureInlineAssistantInitialized:()=>we,ensureInvestigationLensInitialized:()=>He,getAssistantExtensionConfig:()=>ut,getExposeAssistantFunctionsConfig:()=>M,getInlineAssistantFactory:()=>xe,getInvestigationLensImplementation:()=>Je,isAssistantAvailable:()=>K,newFunctionNamespace:()=>O,onK6SetScriptContent:()=>ct,openAssistant:()=>Z,provideComponents:()=>k,providePageContext:()=>f,provideQuestions:()=>j,setInlineAssistantFactory:()=>ve,setInlineAssistantInitializer:()=>ye,setInvestigationLensImplementation:()=>Qe,setInvestigationLensInitializer:()=>Ke,toInvestigationLensError:()=>Ge,toggleAssistant:()=>te,useAIGeneration:()=>Le,useAssistant:()=>ne,useInlineAssistant:()=>Ae,useInvestigationThroughLens:()=>Xe,useLimits:()=>it,usePageComponents:()=>I,usePageContext:()=>y,useProvidePageContext:()=>b,useProvideQuestions:()=>U,useQuestions:()=>q,useTerms:()=>nt});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",c="grafana-assistant:page-context-update",d="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:w(),urlPattern:e,context:[...t]};m([...p(),a]),window.dispatchEvent(new CustomEvent(c,{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(c,{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(d,{detail:{id:a.id}})))},r}g||(g=!0,window.addEventListener(c,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(d,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){if(!e)return[];const t=[],n=p();for(const a of n)x(e,a.urlPattern)&&t.push(...a.context);return t}function y(e={allowQuestions:!1,allowComponents:!1}){const t=(0,s.useLocationService)(),n=t.getLocation().pathname,[a,r]=(0,o.useState)(()=>v(n)),i=(0,o.useRef)(n);(0,o.useEffect)(()=>{const e=()=>{const e=v(t.getLocation().pathname);r(e)},n=()=>{e()},a=t.getLocationObservable().subscribe(t=>{const n=t.pathname;n!==i.current&&(i.current=n,e())});return window.addEventListener(l,n),window.addEventListener(c,n),window.addEventListener(d,n),window.addEventListener(u,n),e(),()=>{a.unsubscribe(),window.removeEventListener(l,n),window.removeEventListener(c,n),window.removeEventListener(d,n),window.removeEventListener(u,n)}},[t]);let p=a;return e.allowQuestions||(p=p.filter(e=>{var t;return"question"!==(null===(t=e.node.data)||void 0===t?void 0:t.type)})),e.allowComponents||(p=p.filter(e=>{var t;return"component"!==(null===(t=e.node.data)||void 0===t?void 0:t.type)})),p}function w(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 E 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 I(){const e=y({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(/.*/,[P("component",{components:n,prompt:e,namespace:t})]),r=(e,n)=>{a([P("component",{components:e,prompt:n,namespace:t})])};return r.unregister=a.unregister,r}var r;const s=f(/.*/,[P("component",{components:n,prompt:"",namespace:t})]),o=f(a,[P("component",{components:{},prompt:e,namespace:t})]),i=(e,n)=>{s([P("component",{components:e,prompt:"",namespace:t})]),o([P("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 A 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 L 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 _ 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 N(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 $={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 P(e,t){var n,s,o;const i=function(e,t){switch(e){case"datasource":return new L({...t,...N(t.datasourceUid)});case"label_name":return new T({...t,...N(t.datasourceUid)});case"label_value":return new _({...t,...N(t.datasourceUid)});case"dashboard":return new S(t);case"dashboard_folder":return new A(t);case"structured":return new r(t);case"component":return new E({...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),c=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:c,icon:null!==(o=t.icon)&&void 0!==o?o:$[e],navigable:!1,selectable:!0,data:i},occurrences:[]}}class R 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=w("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 U(e,t=[]){const n=(0,o.useMemo)(()=>w("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 q(){const e=y({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)||[]}}),B="grafana-assistant-app/callback/v0-alpha";function O(e,t){return{namespace:e,functions:t}}function M(e){return{title:"callback",targets:[B],fn:()=>e.map(e=>({namespace:e.namespace,functions:e.functions}))}}const F=require("rxjs"),G="grafana-assistant-app",z="Grafana Assistant",W=10,V=100,Q=5e3;function K(){return s.getObservablePluginLinks?(0,F.defer)(()=>{try{return(0,s.getObservablePluginLinks)({extensionPointId:"grafana/extension-sidebar/v0-alpha"}).pipe((0,F.map)(e=>e.some(e=>e.pluginId===G&&e.title===z)))}catch(e){return(0,F.throwError)(()=>e)}}).pipe((0,F.retry)({count:W,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(V*2**(t-1),Q);return(0,F.timer)(r)}}),(0,F.catchError)(()=>(0,F.of)(!1))):(0,F.of)(!1)}const H=require("@grafana/data");class J extends H.BusEventWithPayload{}J.type="open-extension-sidebar";class X extends H.BusEventBase{}X.type="close-extension-sidebar";class Y extends H.BusEventWithPayload{}function Z(e){var t;(0,s.reportInteraction)("grafana_assistant_app_opened_sidebar",{from:e.origin}),function(e,t,n){const a=new J({pluginId:e,componentTitle:t,props:n});(0,s.getAppEvents)().publish(a)}(G,z,{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 ee(){!function(){const e=new X;(0,s.getAppEvents)().publish(e)}()}function te(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 Y({pluginId:e,componentTitle:t,props:n});(0,s.getAppEvents)().publish(a)}(G,z,{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 ne(){const[e,t]=(0,o.useState)(void 0);(0,o.useEffect)(()=>{const e=K().subscribe(t);return()=>e.unsubscribe()},[]);const n=null!=e&&e;return{isLoading:void 0===e,isAvailable:n,openAssistant:n?Z:void 0,closeAssistant:n?ee:void 0,toggleAssistant:n?te:void 0}}Y.type="toggle-extension-sidebar";const ae=require("react/jsx-runtime"),re=require("@grafana/ui"),se=require("@emotion/css");function oe(e){const{isAvailable:t,openAssistant:n}=ne();return t&&n?(0,ae.jsx)(ie,{...e,openAssistant:n}):null}function ie({prompt:e,origin:t,context:n,autoSend:a=!0,title:r="Analyze with Assistant",size:i="sm",iconOnlyButton:l=!1,openAssistant:c,onClick:d}){const u=(0,re.useStyles2)(le);return(0,o.useEffect)(()=>{(0,s.reportInteraction)("grafana_assistant_app_open_sidebar_button_displayed",{from:t})},[t]),(0,ae.jsx)(ae.Fragment,{children:l?(0,ae.jsx)(re.IconButton,{name:"ai-sparkle",onClick:()=>{null==d||d(),c({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,ae.jsx)(re.Button,{icon:"ai-sparkle",onClick:()=>{null==d||d(),c({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 le=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,se.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,se.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}`}})}},ce={sm:32,md:36,lg:40};function de(e){const{isAvailable:t,openAssistant:n}=ne();return t&&n?(0,ae.jsx)(ue,{...e,openAssistant:n}):null}function ue({prompt:e,origin:t,context:n,autoSend:a=!0,title:r="Chat with Assistant",size:i="sm",onClick:l,menuItems:c,tooltip:d,dropdownButtonWidth:u,openAssistant:p}){const m=(0,re.useStyles2)(pe),g=Boolean(c),f="number"==typeof(h=null!=u?u:ce[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,ae.jsx)("div",{className:m.wrapper,children:(0,ae.jsxs)(re.ButtonGroup,{className:m.buttonGroup,children:[(0,ae.jsx)(re.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,se.cx)(m.segmentButton,g?m.mainButtonSplit:m.mainButtonSolo),"data-testid":"assistant-split-button-main",children:r}),c&&(0,ae.jsx)(re.Dropdown,{overlay:c,children:(0,ae.jsx)(re.Button,{variant:"secondary",icon:"angle-down",size:i,"aria-label":"More AI actions",className:(0,se.cx)(m.segmentButton,m.dropdownButton),style:{width:f,minWidth:f},"data-testid":"assistant-split-button-dropdown"})})]})});return d?(0,ae.jsx)(re.Tooltip,{content:d,children:b}):b}const pe=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,se.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,se.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,se.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,se.css)({label:"assistant-split-button-main-solo",borderRadius:o}),mainButtonSplit:(0,se.css)({label:"assistant-split-button-main-split",borderTopLeftRadius:o,borderBottomLeftRadius:o,borderTopRightRadius:0,borderBottomRightRadius:0}),dropdownButton:(0,se.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}})}},me=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]]},ge=(e,t,n,a)=>{const r=Array.from({length:101},(e,t)=>t),s={},[o,i]=me(e),l=null!=n?n:o,c=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%, ${c} 100%, transparent 15%)\n `};return s},fe="__grafanaAssistantInlineFactory__",he="__grafanaAssistantInlineInitializer__",be="__grafanaAssistantInlineInitPromise__";function ve(e){const t=window[fe];t&&t!==e?console.warn("InlineAssistant factory already set; ignoring subsequent setInlineAssistantFactory call"):t||(window[fe]=e)}function ye(e){const t=window[he];t&&t!==e?console.warn("InlineAssistant initializer already set; ignoring subsequent setInlineAssistantInitializer call"):t||(window[he]=e)}async function we(){if(window[fe])return;const e=window[he];if(!e)throw new Error("InlineAssistant not initialized. Make sure the Grafana Assistant plugin is loaded and initialized.");const t=window[be];if(t)return t;const n=(async()=>{try{await e()}catch(e){throw window[be]=null,e}})();return window[be]=n,n}function xe(){const e=window[fe];if(!e)throw new Error("InlineAssistant factory not initialized. Make sure the Grafana Assistant plugin is loaded.");return e}const Ee=["message","error","err","detail","details"];function Ie(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=Ie(e);if(a)return a;if(e instanceof Error){const a=Ie(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:Ie(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 Ee)if(e in s){const n=ke(s[e],t);if(n)return n}const o=s.status,i=Ie(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 Ae(){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("")},[]),c=(0,o.useCallback)(()=>{i.current&&i.current.cancel(),t(!1)},[]),d=(0,o.useCallback)(async e=>{var n;s(null),a(""),t(!0);try{await we();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:d,isGenerating:e,content:n,error:r,cancel:c,reset:l}}function Le({value:e,onChange:t,origin:n,systemPrompt:a,onComplete:r,onError:s,onDelta:i,disabled:l=!1,autoGenerate:c=!1,streaming:d=!1,getUserPrompt:u}){const{generate:p,isGenerating:m,content:g,error:f,reset:h}=Ae(),b=(0,o.useRef)(!1),v=(0,o.useRef)(e),y=(0,o.useRef)(u);y.current=u;const w=m?d?g:"":e,x=!(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]),I=(0,o.useRef)(()=>{});return I.current=()=>{!c||!a||e||b.current||l||(b.current=!0,E(a))},(0,o.useEffect)(()=>{I.current()},[]),{displayValue:w,isSendDisabled:x,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 _e({value:e,onChange:t,placeholder:n,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l=!1,autoGenerate:c=!1,streaming:d=!1,getUserPrompt:u,className:p,"data-testid":m}){const{displayValue:g,isSendDisabled:f,handleGenerate:h,isGenerating:b,error:v}=Le({value:e,onChange:t,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l,autoGenerate:c,streaming:d,getUserPrompt:u}),y=(0,re.useStyles2)(Ne),w=Te(b,null!=n?n:"Ask AI to generate..."),x=(0,ae.jsx)(re.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,ae.jsx)("div",{className:(0,se.cx)(y.wrapper,{[y.animatedWrapper]:b},p),"data-testid":m,children:(0,ae.jsx)(re.Input,{value:g,onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),h())},onChange:e=>t(e.currentTarget.value),placeholder:w,disabled:l||b,suffix:x,invalid:!!v,"data-testid":m?`${m}-input`:void 0})})}const Ne=e=>{const t=e.colors.background.primary,n=(0,se.keyframes)({label:"ai-input-border-animation",...ge(e,t)}),[a,r]=me(e);return{wrapper:(0,se.css)({label:"ai-text-input-wrapper",position:"relative",border:"1px solid transparent",borderRadius:e.shape.radius.default,cornerShape:"squircle"}),animatedWrapper:(0,se.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 $e({value:e,onChange:t,placeholder:n,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l=!1,autoGenerate:c=!1,streaming:d=!1,getUserPrompt:u,rows:p=4,className:m,"data-testid":g}){const{displayValue:f,isSendDisabled:h,handleGenerate:b,isGenerating:v,error:y}=Le({value:e,onChange:t,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l,autoGenerate:c,streaming:d,getUserPrompt:u}),w=(0,re.useStyles2)(Pe),x=Te(v,null!=n?n:"Ask AI to generate... (Cmd/Ctrl+Enter to send)"),E=Math.max(p,2);return(0,ae.jsxs)("div",{className:(0,se.cx)(w.textareaWrapper,{[w.animatedWrapper]:v},m),"data-testid":g,children:[(0,ae.jsx)(re.TextArea,{value:f,onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())},onChange:e=>t(e.currentTarget.value),placeholder:x,disabled:l||v,rows:E,className:w.textarea,invalid:!!y,"data-testid":g?`${g}-textarea`:void 0}),(0,ae.jsx)(re.IconButton,{name:"ai-sparkle",onClick:b,disabled:h,className:w.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 Pe=e=>{const t=e.colors.background.primary,n=(0,se.keyframes)({label:"ai-textarea-border-animation",...ge(e,t)}),[a,r]=me(e);return{textareaWrapper:(0,se.css)({label:"ai-textarea-wrapper",position:"relative",border:"1px solid transparent",borderRadius:e.shape.radius.default,cornerShape:"squircle"}),animatedWrapper:(0,se.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,se.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,se.css)({label:"ai-textarea-send",position:"absolute",right:e.spacing(1),top:e.spacing(1)})}};function Re(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:c}=ne();if(!l||!c)return null;const d=`grafana/query-editor/${a.type}/${null!==(i=null!=r?r:H.CoreApp.Unknown)&&void 0!==i?i:"unknown"}`,u=!Re(t),p=n.filter(e=>e.refId!==t.refId&&!Re(e)),m=[P("datasource",{datasourceUid:a.uid})];u&&m.push(P("structured",{title:"Current query",data:t})),p.length>0&&m.push(P("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,ae.jsx)(ie,{prompt:y,origin:d,context:m,autoSend:!1,title:o,size:e,openAssistant:c})}const Ue=["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 qe(e){const{isAvailable:t,openAssistant:n}=ne();return t&&n?(0,ae.jsx)(De,{...e,openAssistant:n}):null}function De({origin:e,context:t,mode:n,placeholder:a,examplePrompts:r,animated:i=!0,onClose:l,onSubmit:c,onClick:d,className:u,openAssistant:p}){const[m,g]=(0,o.useState)(""),f=(0,o.useRef)(null),h=(0,re.useStyles2)(Oe),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?[]:Ue,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==c||c(r),g(""))},[p,t,e,n,c]);return(0,ae.jsx)("div",{className:(0,se.cx)(i?h.card:h.cardStatic,u),onClick:d,role:"search","aria-label":b,"data-testid":"assistant-prompt-card",children:(0,ae.jsx)("div",{className:h.inputRow,children:(0,ae.jsx)(re.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,ae.jsx)(re.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 Be(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 Oe=e=>{const t=e.colors.background.primary,[n,a]=me(e),r=(0,se.keyframes)({label:"prompt-card-border",...ge(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:Be(e)};return{card:(0,se.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,se.css)({...s,label:"assistant-prompt-card-static",background:e.colors.background.elevated,border:`1px solid ${e.colors.border.weak}`}),inputRow:(0,se.css)({label:"prompt-card-input-row",display:"flex",alignItems:"center",gap:e.spacing(.5),"& input":{border:"none !important"}})}},Me=["unavailable","no_report","permission_denied","validation_failed","llm_error"];class Fe extends Error{constructor(e,t){super(t),this.code=e,this.name="InvestigationLensRequestError"}}function Ge(e){return e&&"object"==typeof e&&"code"in e&&"string"==typeof(t=e.code)&&Me.includes(t)?{code:e.code,message:Se(e)}:{code:"llm_error",message:Se(e)};var t}const ze="__grafanaAssistantLensImplementation__",We="__grafanaAssistantLensInitializer__",Ve="__grafanaAssistantLensInitPromise__";function Qe(e){const t=window[ze];t&&t!==e?console.warn("InvestigationLens implementation already set; ignoring subsequent call"):t||(window[ze]=e)}function Ke(e){const t=window[We];t&&t!==e?console.warn("InvestigationLens initializer already set; ignoring subsequent call"):t||(window[We]=e)}async function He(){if(window[ze])return;const e=window[We];if(!e)throw new Fe("unavailable","Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.");const t=window[Ve];if(t)return t;const n=(async()=>{try{await e()}catch(e){throw window[Ve]=null,e}})();return window[Ve]=n,n}function Je(){const e=window[ze];if(!e)throw new Fe("unavailable","Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.");return e}function Xe(e,t,n){const{origin:a,enabled:r=!0,refreshOnEnable:s=!1}=n,[i,l]=(0,o.useState)({status:"loading"}),c=(0,o.useMemo)(()=>JSON.stringify(e),[e]),[d,u]=(0,o.useState)({id:0,bypassCache:!1}),p=(0,o.useRef)(0),m=(0,o.useRef)(r),g=(0,o.useCallback)(()=>{u(e=>({id:e.id+1,bypassCache:!0}))},[]);return(0,o.useEffect)(()=>{const e=m.current;if(m.current=r,!r)return void l({status:"loading"});let n=!1;const o=d.bypassCache&&p.current!==d.id;p.current=d.id;const i=o||s&&!e;return l({status:"loading"}),(async()=>{try{await He();const e=Je(),r=await e({investigationId:t,schema:JSON.parse(c),origin:a,refresh:i});n||l({status:"success",data:r})}catch(e){n||l({status:"error",error:Ge(e)})}})(),()=>{n=!0}},[c,t,a,r,s,d]),{...i,refresh:g}}function Ye(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 Ze="grafana-assistant-terms-and-conditions-refresh";async function et(){var e;const t=(0,s.getBackendSrv)(),n=`/api/plugins/${G}/resources/api/v1/settings/terms`,a=(await(0,F.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 c=1===function(e,t){const n=Ye(e),a=Ye(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&&!c,termsType:l}}async function tt(){try{return(await et()).accepted}catch(e){throw new Error(`Failed to check terms requirements: ${e instanceof Error?e.message:String(e)}`)}}function nt(){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 et();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(Ze,n),()=>{document.removeEventListener(Ze,n)}},[]),{accepted:e,termsType:n,loading:r,error:i}}function at(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 rt="grafana-assistant-limits-updated";async function st(){var e,t,n;const a=(0,s.getBackendSrv)(),r=`/api/plugins/${G}/resources/api/v1/usage/limits/prompt`,o=(await(0,F.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 ot(){try{return await st()}catch(e){throw new Error(`Failed to check limits: ${e instanceof Error?e.message:String(e)}`)}}function it(){const[e,t]=(0,o.useState)(0),[n,a]=(0,o.useState)(0),[r,s]=(0,o.useState)(""),[i,l]=(0,o.useState)(!0),[c,d]=(0,o.useState)(null),u=(0,o.useCallback)(async()=>{try{l(!0),d(null);const e=await st();t(e.count),a(e.limit),s(e.month)}catch(e){const n=e instanceof Error?e.message:"Failed to fetch limits";d(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),d(null))};return window.addEventListener(rt,e),()=>{window.removeEventListener(rt,e)}},[]),{count:e,limit:n,month:r,isLimitReached:n>0&&e>=n,loading:i,error:c,refetch:u}}class lt extends H.BusEventWithPayload{}function ct(e){const t=(0,s.getAppEvents)().subscribe(lt,t=>{e(t.payload)});return()=>t.unsubscribe()}lt.type="grafana-assistant:k6-set-script-content";const dt="grafana-assistant-app/extension/v1";function ut(e){return{title:"assistant-extension",description:"Contributes chits, starters, artifact kinds, and prompt contributions to the Grafana Assistant.",targets:[dt],fn:()=>e}}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:()=>_e,ASSISTANT_EXTENSION_POINT:()=>dt,ASSISTANT_PLUGIN_ID:()=>G,ASSISTANT_PLUGIN_TITLE:()=>z,AssistantPromptCard:()=>Ue,AssistantPromptCardView:()=>De,CALLBACK_EXTENSION_POINT:()=>B,ComponentNodeData:()=>E,DashboardNodeData:()=>S,DatasourceNodeData:()=>L,EntityNodeData:()=>C,FolderNodeData:()=>A,InvestigationLensRequestError:()=>Fe,K6SetScriptContentEvent:()=>lt,LIMITS_UPDATED_EVENT:()=>rt,LabelNameNodeData:()=>T,LabelValueNodeData:()=>_,OpenAssistantButton:()=>oe,OpenAssistantSplitButton:()=>de,QueryWithAssistantButton:()=>je,SkillNodeData:()=>R,StructuredNodeData:()=>r,TERMS_AND_CONDITIONS_REFRESH_EVENT:()=>Ze,checkLimits:()=>ot,checkTerms:()=>tt,closeAssistant:()=>ee,createAssistantContextItem:()=>P,createTool:()=>at,ensureInlineAssistantInitialized:()=>we,ensureInvestigationLensInitialized:()=>He,getAssistantExtensionConfig:()=>ut,getExposeAssistantFunctionsConfig:()=>O,getInlineAssistantFactory:()=>xe,getInvestigationLensImplementation:()=>Je,isAssistantAvailable:()=>K,newFunctionNamespace:()=>M,onK6SetScriptContent:()=>ct,openAssistant:()=>Z,provideComponents:()=>k,providePageContext:()=>f,provideQuestions:()=>j,setInlineAssistantFactory:()=>ve,setInlineAssistantInitializer:()=>ye,setInvestigationLensImplementation:()=>Qe,setInvestigationLensInitializer:()=>Ke,toInvestigationLensError:()=>Ge,toggleAssistant:()=>te,useAIGeneration:()=>Le,useAssistant:()=>ne,useInlineAssistant:()=>Ae,useInvestigationThroughLens:()=>Xe,useLimits:()=>it,usePageComponents:()=>I,usePageContext:()=>y,useProvidePageContext:()=>b,useProvideQuestions:()=>q,useQuestions:()=>U,useTerms:()=>nt});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",c="grafana-assistant:page-context-update",d="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:w(),urlPattern:e,context:[...t]};m([...p(),a]),window.dispatchEvent(new CustomEvent(c,{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(c,{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(d,{detail:{id:a.id}})))},r}g||(g=!0,window.addEventListener(c,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(d,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){if(!e)return[];const t=[],n=p();for(const a of n)x(e,a.urlPattern)&&t.push(...a.context);return t}function y(e={allowQuestions:!1,allowComponents:!1}){const t=(0,s.useLocationService)(),n=t.getLocation().pathname,[a,r]=(0,o.useState)(()=>v(n)),i=(0,o.useRef)(n);(0,o.useEffect)(()=>{const e=()=>{const e=v(t.getLocation().pathname);r(e)},n=()=>{e()},a=t.getLocationObservable().subscribe(t=>{const n=t.pathname;n!==i.current&&(i.current=n,e())});return window.addEventListener(l,n),window.addEventListener(c,n),window.addEventListener(d,n),window.addEventListener(u,n),e(),()=>{a.unsubscribe(),window.removeEventListener(l,n),window.removeEventListener(c,n),window.removeEventListener(d,n),window.removeEventListener(u,n)}},[t]);let p=a;return e.allowQuestions||(p=p.filter(e=>{var t;return"question"!==(null===(t=e.node.data)||void 0===t?void 0:t.type)})),e.allowComponents||(p=p.filter(e=>{var t;return"component"!==(null===(t=e.node.data)||void 0===t?void 0:t.type)})),p}function w(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 E 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 I(){const e=y({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(/.*/,[P("component",{components:n,prompt:e,namespace:t})]),r=(e,n)=>{a([P("component",{components:e,prompt:n,namespace:t})])};return r.unregister=a.unregister,r}var r;const s=f(/.*/,[P("component",{components:n,prompt:"",namespace:t})]),o=f(a,[P("component",{components:{},prompt:e,namespace:t})]),i=(e,n)=>{s([P("component",{components:e,prompt:"",namespace:t})]),o([P("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 A 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 L 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 _ 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 P(e,t){var n,s,o;const i=function(e,t){switch(e){case"datasource":return new L({...t,...$(t.datasourceUid)});case"label_name":return new T({...t,...$(t.datasourceUid)});case"label_value":return new _({...t,...$(t.datasourceUid)});case"dashboard":return new S(t);case"dashboard_folder":return new A(t);case"structured":return new r(t);case"component":return new E({...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),c=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:c,icon:null!==(o=t.icon)&&void 0!==o?o:N[e],navigable:!1,selectable:!0,data:i},occurrences:[]}}class R 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=w("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 q(e,t=[]){const n=(0,o.useMemo)(()=>w("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=y({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)||[]}}),B="grafana-assistant-app/callback/v0-alpha";function M(e,t){return{namespace:e,functions:t}}function O(e){return{title:"callback",targets:[B],fn:()=>e.map(e=>({namespace:e.namespace,functions:e.functions}))}}const F=require("rxjs"),G="grafana-assistant-app",z="Grafana Assistant",W=10,V=100,Q=5e3;function K(){return s.getObservablePluginLinks?(0,F.defer)(()=>{try{return(0,s.getObservablePluginLinks)({extensionPointId:"grafana/extension-sidebar/v0-alpha"}).pipe((0,F.map)(e=>e.some(e=>e.pluginId===G&&e.title===z)))}catch(e){return(0,F.throwError)(()=>e)}}).pipe((0,F.retry)({count:W,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(V*2**(t-1),Q);return(0,F.timer)(r)}}),(0,F.catchError)(()=>(0,F.of)(!1))):(0,F.of)(!1)}const H=require("@grafana/data");class J extends H.BusEventWithPayload{}J.type="open-extension-sidebar";class X extends H.BusEventBase{}X.type="close-extension-sidebar";class Y extends H.BusEventWithPayload{}function Z(e){var t;(0,s.reportInteraction)("grafana_assistant_app_opened_sidebar",{from:e.origin}),function(e,t,n){const a=new J({pluginId:e,componentTitle:t,props:n});(0,s.getAppEvents)().publish(a)}(G,z,{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 ee(){!function(){const e=new X;(0,s.getAppEvents)().publish(e)}()}function te(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 Y({pluginId:e,componentTitle:t,props:n});(0,s.getAppEvents)().publish(a)}(G,z,{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 ne(){const[e,t]=(0,o.useState)(void 0);(0,o.useEffect)(()=>{const e=K().subscribe(t);return()=>e.unsubscribe()},[]);const n=null!=e&&e;return{isLoading:void 0===e,isAvailable:n,openAssistant:n?Z:void 0,closeAssistant:n?ee:void 0,toggleAssistant:n?te:void 0}}Y.type="toggle-extension-sidebar";const ae=require("react/jsx-runtime"),re=require("@grafana/ui"),se=require("@emotion/css");function oe(e){const{isAvailable:t,openAssistant:n}=ne();return t&&n?(0,ae.jsx)(ie,{...e,openAssistant:n}):null}function ie({prompt:e,origin:t,context:n,autoSend:a=!0,title:r="Analyze with Assistant",size:i="sm",iconOnlyButton:l=!1,openAssistant:c,onClick:d}){const u=(0,re.useStyles2)(le);return(0,o.useEffect)(()=>{(0,s.reportInteraction)("grafana_assistant_app_open_sidebar_button_displayed",{from:t})},[t]),(0,ae.jsx)(ae.Fragment,{children:l?(0,ae.jsx)(re.IconButton,{name:"ai-sparkle",onClick:()=>{null==d||d(),c({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,ae.jsx)(re.Button,{icon:"ai-sparkle",onClick:()=>{null==d||d(),c({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 le=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,se.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,se.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}`}})}},ce={sm:32,md:36,lg:40};function de(e){const{isAvailable:t,openAssistant:n}=ne();return t&&n?(0,ae.jsx)(ue,{...e,openAssistant:n}):null}function ue({prompt:e,origin:t,context:n,autoSend:a=!0,title:r="Chat with Assistant",size:i="sm",onClick:l,menuItems:c,tooltip:d,dropdownButtonWidth:u,openAssistant:p}){const m=(0,re.useStyles2)(pe),g=Boolean(c),f="number"==typeof(h=null!=u?u:ce[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,ae.jsx)("div",{className:m.wrapper,children:(0,ae.jsxs)(re.ButtonGroup,{className:m.buttonGroup,children:[(0,ae.jsx)(re.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,se.cx)(m.segmentButton,g?m.mainButtonSplit:m.mainButtonSolo),"data-testid":"assistant-split-button-main",children:r}),c&&(0,ae.jsx)(re.Dropdown,{overlay:c,children:(0,ae.jsx)(re.Button,{variant:"secondary",icon:"angle-down",size:i,"aria-label":"More AI actions",className:(0,se.cx)(m.segmentButton,m.dropdownButton),style:{width:f,minWidth:f},"data-testid":"assistant-split-button-dropdown"})})]})});return d?(0,ae.jsx)(re.Tooltip,{content:d,children:b}):b}const pe=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,se.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,se.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,se.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,se.css)({label:"assistant-split-button-main-solo",borderRadius:o}),mainButtonSplit:(0,se.css)({label:"assistant-split-button-main-split",borderTopLeftRadius:o,borderBottomLeftRadius:o,borderTopRightRadius:0,borderBottomRightRadius:0}),dropdownButton:(0,se.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}})}},me=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]]},ge=(e,t,n,a)=>{const r=Array.from({length:101},(e,t)=>t),s={},[o,i]=me(e),l=null!=n?n:o,c=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%, ${c} 100%, transparent 15%)\n `};return s},fe="__grafanaAssistantInlineFactory__",he="__grafanaAssistantInlineInitializer__",be="__grafanaAssistantInlineInitPromise__";function ve(e){const t=window[fe];t&&t!==e?console.warn("InlineAssistant factory already set; ignoring subsequent setInlineAssistantFactory call"):t||(window[fe]=e)}function ye(e){const t=window[he];t&&t!==e?console.warn("InlineAssistant initializer already set; ignoring subsequent setInlineAssistantInitializer call"):t||(window[he]=e)}async function we(){if(window[fe])return;const e=window[he];if(!e)throw new Error("InlineAssistant not initialized. Make sure the Grafana Assistant plugin is loaded and initialized.");const t=window[be];if(t)return t;const n=(async()=>{try{await e()}catch(e){throw window[be]=null,e}})();return window[be]=n,n}function xe(){const e=window[fe];if(!e)throw new Error("InlineAssistant factory not initialized. Make sure the Grafana Assistant plugin is loaded.");return e}const Ee=["message","error","err","detail","details"];function Ie(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=Ie(e);if(a)return a;if(e instanceof Error){const a=Ie(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:Ie(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 Ee)if(e in s){const n=ke(s[e],t);if(n)return n}const o=s.status,i=Ie(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){return ke(e)||(e&&"object"==typeof e||null==e?"Unknown error":String(e))}function Ae(){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("")},[]),c=(0,o.useCallback)(()=>{i.current&&i.current.cancel(),t(!1)},[]),d=(0,o.useCallback)(async e=>{var n;s(null),a(""),t(!0);try{await we();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:d,isGenerating:e,content:n,error:r,cancel:c,reset:l}}function Le({value:e,onChange:t,origin:n,systemPrompt:a,onComplete:r,onError:s,onDelta:i,disabled:l=!1,autoGenerate:c=!1,streaming:d=!1,getUserPrompt:u}){const{generate:p,isGenerating:m,content:g,error:f,reset:h}=Ae(),b=(0,o.useRef)(!1),v=(0,o.useRef)(e),y=(0,o.useRef)(u);y.current=u;const w=m?d?g:"":e,x=!(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]),I=(0,o.useRef)(()=>{});return I.current=()=>{!c||!a||e||b.current||l||(b.current=!0,E(a))},(0,o.useEffect)(()=>{I.current()},[]),{displayValue:w,isSendDisabled:x,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 _e({value:e,onChange:t,placeholder:n,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l=!1,autoGenerate:c=!1,streaming:d=!1,getUserPrompt:u,className:p,"data-testid":m}){const{displayValue:g,isSendDisabled:f,handleGenerate:h,isGenerating:b,error:v}=Le({value:e,onChange:t,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l,autoGenerate:c,streaming:d,getUserPrompt:u}),y=(0,re.useStyles2)($e),w=Te(b,null!=n?n:"Ask AI to generate..."),x=(0,ae.jsx)(re.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,ae.jsx)("div",{className:(0,se.cx)(y.wrapper,{[y.animatedWrapper]:b},p),"data-testid":m,children:(0,ae.jsx)(re.Input,{value:g,onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),h())},onChange:e=>t(e.currentTarget.value),placeholder:w,disabled:l||b,suffix:x,invalid:!!v,"data-testid":m?`${m}-input`:void 0})})}const $e=e=>{const t=e.colors.background.primary,n=(0,se.keyframes)({label:"ai-input-border-animation",...ge(e,t)}),[a,r]=me(e);return{wrapper:(0,se.css)({label:"ai-text-input-wrapper",position:"relative",border:"1px solid transparent",borderRadius:e.shape.radius.default,cornerShape:"squircle"}),animatedWrapper:(0,se.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:c=!1,streaming:d=!1,getUserPrompt:u,rows:p=4,className:m,"data-testid":g}){const{displayValue:f,isSendDisabled:h,handleGenerate:b,isGenerating:v,error:y}=Le({value:e,onChange:t,origin:a,systemPrompt:r,onComplete:s,onError:o,onDelta:i,disabled:l,autoGenerate:c,streaming:d,getUserPrompt:u}),w=(0,re.useStyles2)(Pe),x=Te(v,null!=n?n:"Ask AI to generate... (Cmd/Ctrl+Enter to send)"),E=Math.max(p,2);return(0,ae.jsxs)("div",{className:(0,se.cx)(w.textareaWrapper,{[w.animatedWrapper]:v},m),"data-testid":g,children:[(0,ae.jsx)(re.TextArea,{value:f,onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())},onChange:e=>t(e.currentTarget.value),placeholder:x,disabled:l||v,rows:E,className:w.textarea,invalid:!!y,"data-testid":g?`${g}-textarea`:void 0}),(0,ae.jsx)(re.IconButton,{name:"ai-sparkle",onClick:b,disabled:h,className:w.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 Pe=e=>{const t=e.colors.background.primary,n=(0,se.keyframes)({label:"ai-textarea-border-animation",...ge(e,t)}),[a,r]=me(e);return{textareaWrapper:(0,se.css)({label:"ai-textarea-wrapper",position:"relative",border:"1px solid transparent",borderRadius:e.shape.radius.default,cornerShape:"squircle"}),animatedWrapper:(0,se.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,se.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,se.css)({label:"ai-textarea-send",position:"absolute",right:e.spacing(1),top:e.spacing(1)})}};function Re(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:c}=ne();if(!l||!c)return null;const d=`grafana/query-editor/${a.type}/${null!==(i=null!=r?r:H.CoreApp.Unknown)&&void 0!==i?i:"unknown"}`,u=!Re(t),p=n.filter(e=>e.refId!==t.refId&&!Re(e)),m=[P("datasource",{datasourceUid:a.uid})];u&&m.push(P("structured",{title:"Current query",data:t})),p.length>0&&m.push(P("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,ae.jsx)(ie,{prompt:y,origin:d,context:m,autoSend:!1,title:o,size:e,openAssistant:c})}const qe=["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}=ne();return t&&n?(0,ae.jsx)(De,{...e,openAssistant:n}):null}function De({origin:e,context:t,mode:n,placeholder:a,examplePrompts:r,animated:i=!0,onClose:l,onSubmit:c,onClick:d,className:u,openAssistant:p}){const[m,g]=(0,o.useState)(""),f=(0,o.useRef)(null),h=(0,re.useStyles2)(Me),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?[]:qe,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==c||c(r),g(""))},[p,t,e,n,c]);return(0,ae.jsx)("div",{className:(0,se.cx)(i?h.card:h.cardStatic,u),onClick:d,role:"search","aria-label":b,"data-testid":"assistant-prompt-card",children:(0,ae.jsx)("div",{className:h.inputRow,children:(0,ae.jsx)(re.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,ae.jsx)(re.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 Be(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 Me=e=>{const t=e.colors.background.primary,[n,a]=me(e),r=(0,se.keyframes)({label:"prompt-card-border",...ge(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:Be(e)};return{card:(0,se.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,se.css)({...s,label:"assistant-prompt-card-static",background:e.colors.background.elevated,border:`1px solid ${e.colors.border.weak}`}),inputRow:(0,se.css)({label:"prompt-card-input-row",display:"flex",alignItems:"center",gap:e.spacing(.5),"& input":{border:"none !important"}})}},Oe=["unavailable","no_report","permission_denied","validation_failed","llm_error"];class Fe extends Error{constructor(e,t){super(t),this.code=e,this.name="InvestigationLensRequestError"}}function Ge(e){return e&&"object"==typeof e&&"code"in e&&"string"==typeof(t=e.code)&&Oe.includes(t)?{code:e.code,message:Se(e)}:{code:"llm_error",message:Se(e)};var t}const ze="__grafanaAssistantLensImplementation__",We="__grafanaAssistantLensInitializer__",Ve="__grafanaAssistantLensInitPromise__";function Qe(e){const t=window[ze];t&&t!==e?console.warn("InvestigationLens implementation already set; ignoring subsequent call"):t||(window[ze]=e)}function Ke(e){const t=window[We];t&&t!==e?console.warn("InvestigationLens initializer already set; ignoring subsequent call"):t||(window[We]=e)}async function He(){if(window[ze])return;const e=window[We];if(!e)throw new Fe("unavailable","Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.");const t=window[Ve];if(t)return t;const n=(async()=>{try{await e()}catch(e){throw window[Ve]=null,e}})();return window[Ve]=n,n}function Je(){const e=window[ze];if(!e)throw new Fe("unavailable","Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.");return e}function Xe(e,t,n){const{origin:a,enabled:r=!0,refreshOnEnable:s=!1}=n,[i,l]=(0,o.useState)({status:"loading"}),c=(0,o.useMemo)(()=>JSON.stringify(e),[e]),[d,u]=(0,o.useState)({id:0,bypassCache:!1}),p=(0,o.useRef)(0),m=(0,o.useRef)(r),g=(0,o.useCallback)(()=>{u(e=>({id:e.id+1,bypassCache:!0}))},[]);return(0,o.useEffect)(()=>{const e=m.current;if(m.current=r,!r)return void l({status:"loading"});let n=!1;const o=d.bypassCache&&p.current!==d.id;p.current=d.id;const i=o||s&&!e;return l({status:"loading"}),(async()=>{try{await He();const e=Je(),r=await e({investigationId:t,schema:JSON.parse(c),origin:a,refresh:i});n||l({status:"success",data:r})}catch(e){n||l({status:"error",error:Ge(e)})}})(),()=>{n=!0}},[c,t,a,r,s,d]),{...i,refresh:g}}function Ye(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 Ze="grafana-assistant-terms-and-conditions-refresh";async function et(){var e;const t=(0,s.getBackendSrv)(),n=`/api/plugins/${G}/resources/api/v1/settings/terms`,a=(await(0,F.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 c=1===function(e,t){const n=Ye(e),a=Ye(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&&!c,termsType:l}}async function tt(){try{return(await et()).accepted}catch(e){throw new Error(`Failed to check terms requirements: ${e instanceof Error?e.message:String(e)}`)}}function nt(){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 et();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(Ze,n),()=>{document.removeEventListener(Ze,n)}},[]),{accepted:e,termsType:n,loading:r,error:i}}function at(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 rt="grafana-assistant-limits-updated";async function st(){var e,t,n;const a=(0,s.getBackendSrv)(),r=`/api/plugins/${G}/resources/api/v1/usage/limits/prompt`,o=(await(0,F.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 ot(){try{return await st()}catch(e){throw new Error(`Failed to check limits: ${e instanceof Error?e.message:String(e)}`)}}function it(){const[e,t]=(0,o.useState)(0),[n,a]=(0,o.useState)(0),[r,s]=(0,o.useState)(""),[i,l]=(0,o.useState)(!0),[c,d]=(0,o.useState)(null),u=(0,o.useCallback)(async()=>{try{l(!0),d(null);const e=await st();t(e.count),a(e.limit),s(e.month)}catch(e){const n=e instanceof Error?e.message:"Failed to fetch limits";d(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),d(null))};return window.addEventListener(rt,e),()=>{window.removeEventListener(rt,e)}},[]),{count:e,limit:n,month:r,isLimitReached:n>0&&e>=n,loading:i,error:c,refetch:u}}class lt extends H.BusEventWithPayload{}function ct(e){const t=(0,s.getAppEvents)().subscribe(lt,t=>{e(t.payload)});return()=>t.unsubscribe()}lt.type="grafana-assistant:k6-set-script-content";const dt="grafana-assistant-app/extension/v1";function ut(e){return{title:"assistant-extension",description:"Contributes chits, starters, artifact kinds, and prompt contributions to the Grafana Assistant.",targets:[dt],fn:()=>e}}module.exports=t})();
|
|
2
2
|
//# sourceMappingURL=index.js.map
|