@grafana/assistant 0.1.30 → 0.1.32

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","mappings":"mBACA,IAAIA,EAAsB,CCA1BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3EH,EAAwB,CAACS,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFV,EAAyBC,IACH,oBAAXa,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeL,EAASa,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeL,EAAS,aAAc,CAAEe,OAAO,M,KCDhD,SAASC,EAAKC,GACnB,IAAID,EAAO,KAEX,IAAK,IAAIE,EAAI,EAAGA,EAAID,EAAME,OAAQD,IAChCF,GAAQA,GAAQ,GAAKA,EAAOC,EAAMG,WAAWF,GAI/C,OAAQF,IAAS,GAAGK,SAAS,GAC/B,C,yiDCuBO,MAAMC,EAKX,WAAAC,CAAmBC,GAAA,KAAAA,OAAAA,EAHZ,KAAAC,KAAO,GAIZC,KAAKC,GAAKX,EAAKQ,EAAOG,IACtBD,KAAKE,KAAOJ,EAAOI,IACrB,CAGA,gBAAIC,G,MACF,OAA+B,QAAxB,EAAAH,KAAKF,OAAOK,oBAAY,QACjC,CAEA,YAAAC,CAAaC,G,QACX,MAAO,CACLH,KAAMF,KAAKE,KACXG,iBACAF,aAAcH,KAAKG,aACnBG,KAAM,CACJC,KAAsB,QAAhB,EAAAP,KAAKF,OAAOC,YAAI,QAAI,GAC1BA,KAAsB,QAAhB,EAAAC,KAAKF,OAAOC,YAAI,QAAI,IAGhC,CAEA,MAAAS,C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D,EAAaljB,aAC5B,CAZS,GAAAhG,KAAO,0C","sources":["webpack://@grafana/assistant/webpack/bootstrap","webpack://@grafana/assistant/webpack/runtime/define property getters","webpack://@grafana/assistant/webpack/runtime/hasOwnProperty shorthand","webpack://@grafana/assistant/webpack/runtime/make namespace object","webpack://@grafana/assistant/./src/utils/hash.ts","webpack://@grafana/assistant/./src/context/base.ts","webpack://@grafana/assistant/external commonjs2 \"@grafana/runtime\"","webpack://@grafana/assistant/external commonjs2 \"react\"","webpack://@grafana/assistant/./src/context/page.ts","webpack://@grafana/assistant/./src/context/component.ts","webpack://@grafana/assistant/./src/context/dashboard.ts","webpack://@grafana/assistant/./src/context/datasource.ts","webpack://@grafana/assistant/./src/context/entity.ts","webpack://@grafana/assistant/./src/context/label.ts","webpack://@grafana/assistant/./src/context/factory.ts","webpack://@grafana/assistant/./src/context/chat.ts","webpack://@grafana/assistant/./src/context/skill.ts","webpack://@grafana/assistant/./src/context/questions.ts","webpack://@grafana/assistant/./src/functions.ts","webpack://@grafana/assistant/external commonjs2 \"rxjs\"","webpack://@grafana/assistant/./src/plugin.ts","webpack://@grafana/assistant/external commonjs2 \"@grafana/data\"","webpack://@grafana/assistant/./src/sidebar.ts","webpack://@grafana/assistant/./src/hook.ts","webpack://@grafana/assistant/external commonjs2 \"react/jsx-runtime\"","webpack://@grafana/assistant/external commonjs2 \"@grafana/ui\"","webpack://@grafana/assistant/external commonjs2 \"@emotion/css\"","webpack://@grafana/assistant/./src/components/button/OpenAssistantButton.tsx","webpack://@grafana/assistant/./src/components/button/OpenAssistantSplitButton.tsx","webpack://@grafana/assistant/./src/utils/theme.ts","webpack://@grafana/assistant/./src/inline/inlineAssistant.ts","webpack://@grafana/assistant/./src/utils/errorHandling.ts","webpack://@grafana/assistant/./src/inline/useInlineAssistant.ts","webpack://@grafana/assistant/./src/components/input/useAIGeneration.ts","webpack://@grafana/assistant/./src/components/input/useGeneratingPlaceholder.ts","webpack://@grafana/assistant/./src/components/input/AITextInput.tsx","webpack://@grafana/assistant/./src/components/input/AITextArea.tsx","webpack://@grafana/assistant/./src/components/button/QueryWithAssistantButton.tsx","webpack://@grafana/assistant/./src/components/prompt-card/useAnimatedPlaceholder.ts","webpack://@grafana/assistant/./src/components/prompt-card/AssistantPromptCard.tsx","webpack://@grafana/assistant/./src/lens/investigationLens.ts","webpack://@grafana/assistant/./src/lens/useInvestigationThroughLens.ts","webpack://@grafana/assistant/./src/terms/versionCompare.ts","webpack://@grafana/assistant/./src/terms/index.ts","webpack://@grafana/assistant/./src/tools/toolFactory.ts","webpack://@grafana/assistant/./src/limits/index.ts","webpack://@grafana/assistant/./src/k6.ts"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Simple hash function that generates a deterministic hash for a given input string.\n * Uses the djb2 algorithm for simplicity and good distribution.\n */\nexport function hash(input: string): string {\n let hash = 5381;\n\n for (let i = 0; i < input.length; i++) {\n hash = (hash << 5) + hash + input.charCodeAt(i);\n }\n\n // Convert to positive hex string\n return (hash >>> 0).toString(16);\n}\n","import type { IconName } from '@grafana/ui';\nimport type { ItemDataType, ContextItemData, UnknownItemData } from './types';\nimport { hash } from '../utils/hash';\n\nexport interface BaseParams {\n title?: string;\n // If true, the context item will not be shown in the context pills\n hidden?: boolean;\n // Image to display, if not selected, we fallback to icon\n img?: string;\n // Icon to display, if img is provided, icon is ignored\n icon?: IconName;\n /**\n * When true, bypasses size limits for fixed-size content that doesn't need truncation.\n *\n * Set `bypassLimits: true` for fixed-size content like:\n * - Static instructions or prompts\n * - Configuration that doesn't change\n * - Small, bounded metadata\n *\n * Keep `bypassLimits: false` (default) for variable-size content like:\n * - Query results, data tables, graphs\n * - User-generated content, logs\n * - Any content that could grow unexpectedly large\n *\n * @default false\n */\n bypassLimits?: boolean;\n}\n\nexport interface NodeDataParams extends BaseParams {\n id: string;\n type: ItemDataType;\n text?: string;\n}\n\nexport class NodeData {\n public id: string;\n public text = '';\n public type: ItemDataType;\n\n constructor(public params: NodeDataParams) {\n this.id = hash(params.id);\n this.type = params.type;\n }\n\n /** Whether size limits should be bypassed for this context item. Defaults to false. */\n get bypassLimits(): boolean {\n return this.params.bypassLimits ?? false;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.params.text ?? '',\n text: this.params.text ?? '',\n } satisfies UnknownItemData,\n };\n }\n\n equals(other: unknown): boolean {\n if (!(other instanceof NodeData)) {\n return false;\n }\n return this.id === other.id && this.type === other.type;\n }\n}\n\nexport interface StructuredNodeDataParams extends BaseParams {\n data: Record<string, any>;\n}\n\nexport class StructuredNodeData extends NodeData {\n public data: Record<string, any>;\n constructor(params: StructuredNodeDataParams) {\n super({ ...params, id: hash(JSON.stringify(params.data)), type: 'structured' });\n this.data = params.data;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: this.data,\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/runtime\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"react\");","import { useLocationService } from '@grafana/runtime';\nimport type { ChatContextItem } from './types';\nimport { useEffect, useState, useRef, useCallback } from 'react';\n\n// Extend window interface for global registry\ndeclare global {\n interface Window {\n [key: string]: any;\n }\n}\n\nexport interface PageContextRegistration {\n id: string;\n urlPattern: string | RegExp;\n context: ChatContextItem[];\n}\n\n// Global registry key\nconst GLOBAL_REGISTRY_KEY = '__grafanaAssistantPageContextRegistry__';\n\n// Custom event for registry changes\nconst REGISTRY_CHANGE_EVENT = 'grafana-assistant:page-context-registry-changed';\n\n/**\n * Legacy event names for backward compatibility with the previous implementation.\n * These events are emitted alongside the new REGISTRY_CHANGE_EVENT to ensure\n * any existing code listening to the old events continues to work.\n *\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_UPDATE_EVENT = 'grafana-assistant:page-context-update';\n/**\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_REMOVE_EVENT = 'grafana-assistant:page-context-remove';\n/**\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_SYNC_EVENT = 'grafana-assistant:page-context-sync';\n\n// Ensure global registry exists on window\nif (!window[GLOBAL_REGISTRY_KEY]) {\n window[GLOBAL_REGISTRY_KEY] = [];\n}\n\n// Get reference to the global registry\nfunction getPageContextRegistry(): PageContextRegistration[] {\n return window[GLOBAL_REGISTRY_KEY];\n}\n\n// TODO: Remove skipLegacyEvents parameter after old event-based approach is fully deprecated\nfunction setPageContextRegistry(newRegistry: PageContextRegistration[], skipLegacyEvents = false): void {\n window[GLOBAL_REGISTRY_KEY] = newRegistry;\n // Notify all listeners that the registry has changed\n window.dispatchEvent(new CustomEvent(REGISTRY_CHANGE_EVENT));\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy sync event for backward compatibility (unless we're processing a legacy event)\n if (!skipLegacyEvents) {\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_SYNC_EVENT, {\n detail: { registry: newRegistry },\n })\n );\n }\n}\n\n/**\n * Bridge to handle legacy events from external apps using old versions of @grafana/assistant.\n * This ensures that registrations from external apps get synced into our window registry.\n *\n * TODO: Remove this entire bridge after old event-based approach is fully deprecated\n */\nlet legacyBridgeInitialized = false;\n\nfunction initializeLegacyEventBridge(): void {\n if (legacyBridgeInitialized) {\n return;\n }\n legacyBridgeInitialized = true;\n\n // Handle legacy update events (registration added or updated)\n window.addEventListener(LEGACY_REGISTRY_UPDATE_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const registration = customEvent.detail as PageContextRegistration;\n\n if (!registration?.id) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const existingIndex = currentRegistry.findIndex((r) => r.id === registration.id);\n\n if (existingIndex !== -1) {\n // Update existing registration\n const newRegistry = [...currentRegistry];\n newRegistry[existingIndex] = registration;\n setPageContextRegistry(newRegistry, true); // Skip legacy events to avoid loops\n } else {\n // Add new registration\n setPageContextRegistry([...currentRegistry, registration], true); // Skip legacy events to avoid loops\n }\n });\n\n // Handle legacy remove events (registration removed)\n window.addEventListener(LEGACY_REGISTRY_REMOVE_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const id = customEvent.detail?.id;\n\n if (!id) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((r) => r.id === id);\n\n if (index !== -1) {\n const newRegistry = currentRegistry.filter((_, i) => i !== index);\n setPageContextRegistry(newRegistry, true); // Skip legacy events to avoid loops\n }\n });\n\n // Handle legacy sync events (entire registry sync from external app)\n window.addEventListener(LEGACY_REGISTRY_SYNC_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const incomingRegistry = customEvent.detail?.registry as PageContextRegistration[];\n\n if (!Array.isArray(incomingRegistry)) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const currentIds = new Set(currentRegistry.map((r) => r.id));\n\n // Merge: add any registrations from external app that we don't have\n const newRegistrations = incomingRegistry.filter((r) => !currentIds.has(r.id));\n\n if (newRegistrations.length > 0) {\n setPageContextRegistry([...currentRegistry, ...newRegistrations], true); // Skip legacy events to avoid loops\n }\n });\n}\n\n// TODO: Remove this initialization after old event-based approach is fully deprecated\n// Initialize the bridge on module load\ninitializeLegacyEventBridge();\n\n/**\n * Registers context items for specific pages based on URL patterns.\n * Returns a setter function to update the context dynamically, similar to useState.\n *\n * Multiple registrations with the same URL pattern are allowed and will all be merged\n * when the pattern matches. Each call creates a new independent registration.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialContext - *Initial* array of ContextItems to provide when the pattern matches. IMPORTANT: will be overwritten when setContext is used to update the context.\n * @returns A setter function to update the context, with an unregister method attached\n */\nexport function providePageContext(\n urlPattern: string | RegExp,\n initialContext: ChatContextItem[]\n): ((context: ChatContextItem[]) => void) & { unregister: () => void } {\n // Validate URL pattern at registration time (only warn once, not on every match)\n validateUrlPattern(urlPattern);\n\n // Always create a new registration to allow multiple providers with the same URL pattern\n const registration: PageContextRegistration = {\n id: generateRegistrationId(),\n urlPattern,\n context: [...initialContext],\n };\n\n const registry = getPageContextRegistry();\n setPageContextRegistry([...registry, registration]);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy update event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_UPDATE_EVENT, {\n detail: registration,\n })\n );\n\n // Create setter function that can update the context\n const setContext = (newContext: ChatContextItem[]) => {\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((reg) => reg.id === registration.id);\n if (index !== -1) {\n const newRegistry = [...currentRegistry];\n newRegistry[index] = { ...newRegistry[index], context: [...newContext] };\n setPageContextRegistry(newRegistry);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy update event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_UPDATE_EVENT, {\n detail: newRegistry[index],\n })\n );\n }\n };\n\n // Add unregister method to the setter\n setContext.unregister = () => {\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((reg) => reg.id === registration.id);\n if (index !== -1) {\n const newRegistry = currentRegistry.filter((_, i) => i !== index);\n setPageContextRegistry(newRegistry);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy remove event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_REMOVE_EVENT, {\n detail: { id: registration.id },\n })\n );\n }\n };\n\n return setContext;\n}\n\nconst empty: ChatContextItem[] = [];\n\n/**\n * React hook for providing page context that automatically cleans up on unmount.\n * This is the recommended way to use page context in React components.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialContext - Initial array of ContextItems to provide when the pattern matches. IMPORTANT: will be overwritten when setContext is used to update the context.\n * @returns A setter function to update the context\n */\nexport function useProvidePageContext(\n urlPattern: string | RegExp,\n initialContext: ChatContextItem[] = empty\n): (context: ChatContextItem[]) => void {\n const setContextRef = useRef<ReturnType<typeof providePageContext> | undefined>(undefined);\n const pendingUpdate = useRef<ChatContextItem[] | undefined>(undefined);\n const isModified = useRef(false);\n\n // Create or update the registration when dependencies change\n // biome-ignore lint/correctness/useExhaustiveDependencies: initialContext is intentionally excluded to prevent re-registering on every render; updates are handled by the second effect\n useEffect(() => {\n // Reset isModified flag when urlPattern changes so that initialContext updates\n // are applied to the new registration until manually modified again\n isModified.current = false;\n\n // If we have pending updates, prefer those over initialContext as they represent\n // newer state from child components\n const contextToUse = pendingUpdate.current !== undefined ? pendingUpdate.current : initialContext;\n setContextRef.current = providePageContext(urlPattern, contextToUse);\n\n // Clear pending update as it's now applied\n if (pendingUpdate.current !== undefined) {\n pendingUpdate.current = undefined;\n }\n\n // Cleanup on unmount or dependency change\n return () => {\n setContextRef.current?.unregister();\n setContextRef.current = undefined;\n };\n // We intentionally exclude initialContext from deps to prevent re-registering on every render\n // Updates to initialContext are handled by the second effect\n }, [urlPattern]);\n\n // Update context when initialContext changes, BUT only if we haven't manually modified it.\n // This prevents unstable initialContext props (e.g. passing [] inline) from overwriting\n // updates made via setContext by child components.\n useEffect(() => {\n if (!isModified.current && setContextRef.current) {\n setContextRef.current(initialContext);\n }\n }, [initialContext]);\n\n // Return a stable setter function\n const setContext = useCallback((newContext: ChatContextItem[]) => {\n isModified.current = true;\n if (setContextRef.current) {\n setContextRef.current(newContext);\n } else {\n pendingUpdate.current = newContext;\n }\n }, []);\n\n return setContext;\n}\n\n/**\n * Gets all context items that match the current URL.\n *\n * @param currentUrl - The current page URL to match against\n * @param registrations - Array of registrations to match against\n * @returns Array of ChatContextItem from all matching registrations\n */\nfunction getActivePageContext(currentUrl: string): ChatContextItem[] {\n if (!currentUrl) {\n return [];\n }\n\n const activeContext: ChatContextItem[] = [];\n const registry = getPageContextRegistry();\n\n for (const registration of registry) {\n if (matchesUrlPattern(currentUrl, registration.urlPattern)) {\n activeContext.push(...registration.context);\n }\n }\n\n return activeContext;\n}\n\nexport function usePageContext(\n options: { allowQuestions: boolean; allowComponents: boolean } = { allowQuestions: false, allowComponents: false }\n): ChatContextItem[] {\n const location = useLocationService();\n const initialPathname = location.getLocation().pathname;\n const [pageContext, setPageContext] = useState<ChatContextItem[]>(() => getActivePageContext(initialPathname));\n const currentPathnameRef = useRef(initialPathname);\n\n useEffect(() => {\n // Function to update context based on current location and registry\n const updateContext = () => {\n const pathname = location.getLocation().pathname;\n const context = getActivePageContext(pathname);\n setPageContext(context);\n };\n\n // Handle registry changes\n const handleRegistryChange = () => {\n updateContext();\n };\n\n // Subscribe to location changes\n const locationSub = location.getLocationObservable().subscribe((loc: { pathname: string }) => {\n const pathname = loc.pathname;\n if (pathname !== currentPathnameRef.current) {\n currentPathnameRef.current = pathname;\n updateContext();\n }\n });\n\n // Listen for registry changes\n window.addEventListener(REGISTRY_CHANGE_EVENT, handleRegistryChange);\n\n // TODO: Remove these legacy event listeners after old event-based approach is fully deprecated\n // Listen for legacy events for backward compatibility\n window.addEventListener(LEGACY_REGISTRY_UPDATE_EVENT, handleRegistryChange);\n window.addEventListener(LEGACY_REGISTRY_REMOVE_EVENT, handleRegistryChange);\n window.addEventListener(LEGACY_REGISTRY_SYNC_EVENT, handleRegistryChange);\n\n // Initial update\n updateContext();\n\n return () => {\n locationSub.unsubscribe();\n window.removeEventListener(REGISTRY_CHANGE_EVENT, handleRegistryChange);\n // TODO: Remove these legacy event listener removals after old event-based approach is fully deprecated\n window.removeEventListener(LEGACY_REGISTRY_UPDATE_EVENT, handleRegistryChange);\n window.removeEventListener(LEGACY_REGISTRY_REMOVE_EVENT, handleRegistryChange);\n window.removeEventListener(LEGACY_REGISTRY_SYNC_EVENT, handleRegistryChange);\n };\n }, [location]);\n\n let filteredContext = pageContext;\n\n if (!options.allowQuestions) {\n filteredContext = filteredContext.filter((item) => item.node.data?.type !== 'question');\n }\n\n if (!options.allowComponents) {\n filteredContext = filteredContext.filter((item) => item.node.data?.type !== 'component');\n }\n\n return filteredContext;\n}\n\nexport function generateRegistrationId(prefix = 'page-context'): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Validates the URL pattern at registration time and logs warnings for problematic patterns.\n * This is called once during registration, not on every URL match.\n */\nfunction validateUrlPattern(pattern: string | RegExp): void {\n if (pattern instanceof RegExp) {\n // Check if RegExp pattern matches everything (e.g., /.*/, /^.*$/)\n // This is intentional for global contexts (e.g., components), so we use a scoped warning\n const source = pattern.source;\n if (source === '.*' || source === '^.*$' || source === '^.*' || source === '.*$') {\n // Note: This is expected for global contexts like provideComponents.\n // The warning is intentionally omitted here since it's a valid use case.\n // If you want to warn for specific cases, filter them here.\n }\n return;\n }\n\n if (typeof pattern === 'string') {\n // Validate urlPattern - log error if empty string is passed\n if (!pattern || pattern.trim() === '') {\n console.warn(\n 'useProvidePageContext: Empty string passed as urlPattern. This will cause the context to not match any pages.'\n );\n return;\n }\n\n // Check if the pattern matches everything (e.g., ** becomes ^.*$)\n if (pattern === '**') {\n // Note: This is expected for global contexts.\n // The warning is intentionally omitted here since it's a valid use case.\n }\n }\n}\n\nfunction matchesUrlPattern(url: string, pattern: string | RegExp): boolean {\n if (pattern instanceof RegExp) {\n return pattern.test(url);\n }\n\n // For string patterns, support simple wildcards\n if (typeof pattern === 'string') {\n // Empty pattern never matches\n if (!pattern || pattern.trim() === '') {\n return false;\n }\n\n // Convert simple wildcard pattern to regex\n // * matches any characters except /, ** matches any path segments\n // Handle ** first with a placeholder to avoid conflicts\n const regexPattern = pattern\n .replace(/\\*\\*/g, '\\u0000DOUBLE_STAR\\u0000') // Temporary placeholder for **\n .replace(/\\*/g, '[^/]*') // * becomes [^/]*\n // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional \\u0000 null byte used as placeholder to avoid glob pattern conflicts\n .replace(/\\u0000DOUBLE_STAR\\u0000/g, '.*') // Replace placeholder with .*\n .replace(/\\?/g, '.'); // ? becomes .\n\n const finalRegex = `^${regexPattern}$`;\n const regex = new RegExp(finalRegex);\n return regex.test(url);\n }\n\n return false;\n}\n\n/**\n * Test utility function to clear all registrations from the registry.\n * This should only be used in tests to ensure a clean slate between test runs.\n *\n * @internal This is for testing purposes only\n */\nexport function __clearPageContextRegistryForTesting(): void {\n setPageContextRegistry([]);\n}\n","import { type ComponentType, useMemo } from 'react';\nimport { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, ComponentItemData } from './types';\nimport { providePageContext, usePageContext } from './page';\nimport { createAssistantContextItem } from './chat';\n\nexport type ComponentImplementation = ComponentType<any>;\nexport type NamedComponents = Record<string, ComponentImplementation>;\n\n/**\n * Type used to create a component context item.\n */\nexport interface CreateComponentContextParams extends BaseParams {\n components: Record<string, ComponentType<any>>;\n prompt: string;\n namespace?: string;\n}\n\nexport class ComponentNodeData extends NodeData {\n public components: Record<string, ComponentType<any>>;\n public prompt: string;\n public namespace: string;\n\n constructor(params: CreateComponentContextParams) {\n const namespace = params.namespace || 'components';\n super({ ...params, id: `${namespace}-${Object.keys(params.components).join('-')}`, type: 'component' });\n this.components = params.components;\n this.prompt = params.prompt;\n this.namespace = namespace;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n data: {\n name: `Custom UI components (${this.namespace})`,\n prompt: this.prompt\n ? this.prompt +\n '\\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.'\n : '',\n } satisfies Omit<ComponentItemData, 'components' | 'text' | 'namespace'>,\n };\n }\n}\n\n/**\n * React hook that provides all components available globally.\n * Components are available everywhere, regardless of URL patterns.\n *\n * @returns Object containing all components available globally, keyed by namespace.componentName\n */\nexport function usePageComponents(): Record<string, ComponentImplementation> {\n const pageContext = usePageContext({ allowComponents: true, allowQuestions: false });\n\n // Use useMemo to avoid recreating the components object on every render\n const components = useMemo(() => {\n const allComponents: Record<string, ComponentImplementation> = {};\n\n // Filter for component context items and extract their components\n for (const item of pageContext.filter((item) => item.node.data?.components)) {\n const componentData = item.node.data;\n if (componentData?.components && Object.keys(componentData.components).length > 0) {\n const namespace = componentData.namespace || componentData.name || 'components';\n\n // Add each component with namespace_componentName format\n for (const [componentName, component] of Object.entries(componentData.components)) {\n allComponents[`${namespace}_${componentName}`] = component as ComponentImplementation;\n }\n }\n }\n\n return allComponents;\n }, [pageContext]);\n\n return components;\n}\n\n/**\n * Provide components to the assistant.\n *\n * Components are always available globally, but the prompt is only applied when the URL pattern matches.\n *\n * For catch-all URL patterns, returns a setter that takes a context array.\n * For specific URL patterns, returns a setter that takes components and prompt separately.\n *\n * @param prompt - The prompt to use for the components (only applied when URL matches).\n * @param namespace - The namespace to use for the components.\n * @param components - The components to provide (always available).\n * @param urlPattern - The URL pattern to match for the prompt (components are always available).\n * @returns A setter function to update the context, with an unregister method attached\n */\nexport function provideComponents(\n prompt: string,\n namespace: string,\n components: Record<string, ComponentImplementation>,\n urlPattern: string | RegExp = /.*/\n): ((newComponents: Record<string, ComponentImplementation>, newPrompt: string) => void) & { unregister: () => void } {\n // Check if the URL pattern is catch-all (.*) - if so, register everything together\n const isCatchAll = (pattern: string | RegExp) => {\n if (pattern instanceof RegExp) {\n return pattern.source === '.*' && pattern.flags === '';\n }\n return pattern === '.*' || pattern === '/.*/';\n };\n\n if (isCatchAll(urlPattern)) {\n // If pattern is catch-all, register components and prompt together globally\n const setContext = providePageContext(/.*/, [\n createAssistantContextItem('component', {\n components,\n prompt,\n namespace,\n }),\n ]);\n\n // Create a wrapper setter that matches the expected signature\n const setter = (newComponents: Record<string, ComponentImplementation>, newPrompt: string) => {\n setContext([\n createAssistantContextItem('component', {\n components: newComponents,\n prompt: newPrompt,\n namespace,\n }),\n ]);\n };\n\n // Attach unregister method\n setter.unregister = setContext.unregister;\n\n return setter;\n }\n\n // For specific URL patterns, separate components (global) from prompt (URL-specific)\n const globalComponents = providePageContext(/.*/, [\n createAssistantContextItem('component', {\n components,\n prompt: '', // No prompt for global components\n namespace,\n }),\n ]);\n\n // Only register prompt for specific URL pattern\n const promptContext = providePageContext(urlPattern, [\n createAssistantContextItem('component', {\n components: {}, // No components, just prompt\n prompt,\n namespace,\n }),\n ]);\n\n // Return a setter that properly separates components and prompt\n // When updating, we extract components and prompt from the new data and update each registration appropriately\n const setter = (newComponents: Record<string, ComponentImplementation>, newPrompt: string) => {\n // Update global components registration with new components (but empty prompt)\n globalComponents([\n createAssistantContextItem('component', {\n components: newComponents,\n prompt: '', // No prompt for global components\n namespace,\n }),\n ]);\n\n // Update URL-specific registration with new prompt (but empty components)\n promptContext([\n createAssistantContextItem('component', {\n components: {}, // No components, just prompt\n prompt: newPrompt,\n namespace,\n }),\n ]);\n };\n\n // Attach unregister method that cleans up both registrations\n setter.unregister = () => {\n globalComponents.unregister();\n promptContext.unregister();\n };\n\n return setter;\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, DashboardItemData, FolderItemData } from './types';\n\nexport interface CreateDashboardContextParams extends BaseParams {\n dashboardUid: string;\n dashboardTitle: string;\n folderUid?: string;\n folderTitle?: string;\n}\n\nexport interface CreateFolderContextParams extends BaseParams {\n folderUid: string;\n folderTitle: string;\n}\n\nexport class DashboardNodeData extends NodeData {\n public dashboardUid: string;\n public dashboardTitle: string;\n public folderUid?: string;\n public folderTitle?: string;\n\n constructor(params: CreateDashboardContextParams) {\n super({ ...params, id: params.dashboardUid, type: 'dashboard' });\n this.dashboardUid = params.dashboardUid;\n this.dashboardTitle = params.dashboardTitle;\n this.folderUid = params.folderUid;\n this.folderTitle = params.folderTitle;\n this.text = params.dashboardTitle;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.dashboardTitle,\n dashboardUid: this.dashboardUid,\n dashboardTitle: this.dashboardTitle,\n folderUid: this.folderUid,\n folderTitle: this.folderTitle,\n text: this.text,\n } satisfies DashboardItemData,\n };\n }\n}\n\nexport class FolderNodeData extends NodeData {\n public folderUid: string;\n public folderTitle: string;\n public text = '';\n\n constructor(params: CreateFolderContextParams) {\n super({ ...params, id: params.folderUid, type: 'dashboard_folder' });\n this.folderUid = params.folderUid;\n this.folderTitle = params.folderTitle;\n this.text = params.folderTitle;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.folderTitle,\n folderUid: this.folderUid,\n folderTitle: this.folderTitle,\n text: this.text,\n } satisfies FolderItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { DatasourceMeta } from './factory';\nimport type { ContextItemData, DatasourceItemData } from './types';\n\n/**\n * Type used to create a datasource context item.\n *\n * All required attributes will be inferred from the datasources uid.\n */\nexport interface CreateDatasourceContextParams extends BaseParams {\n datasourceUid: string;\n}\n\nexport class DatasourceNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public img?: string;\n\n constructor(params: CreateDatasourceContextParams & DatasourceMeta) {\n super({ ...params, id: params.datasourceUid, type: 'datasource' });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.img = params.img;\n this.text = params.datasourceName;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.datasourceName,\n uid: this.datasourceUid,\n type: this.datasourceType,\n text: this.text,\n } satisfies DatasourceItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, EntityItemData } from './types';\n\n/**\n * Type used to create an entity context item.\n */\nexport interface CreateEntityContextParams extends BaseParams {\n type: string;\n name: string;\n scope?: {\n env?: string;\n site?: string;\n namespace?: string;\n };\n properties?: Record<string, any>;\n}\n\nexport class EntityNodeData extends NodeData {\n public entityType: string;\n public name: string;\n public scope?: {\n env?: string;\n site?: string;\n namespace?: string;\n };\n public properties?: Record<string, any>;\n\n constructor(params: CreateEntityContextParams) {\n super({\n id: `${params.type}-${params.name}-${[params.scope?.env, params.scope?.site, params.scope?.namespace].filter(Boolean).join('-')}`,\n type: 'entity',\n title: params.title,\n hidden: params.hidden,\n img: params.img,\n icon: params.icon,\n text: params.name,\n });\n this.entityType = params.type;\n this.name = params.name;\n this.scope = params.scope;\n this.properties = params.properties;\n this.text = params.name;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: 'entity',\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.name,\n text: this.text,\n type: this.entityType,\n scope: this.scope,\n properties: this.properties,\n } satisfies EntityItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { DatasourceMeta } from './factory';\nimport type { ContextItemData, LabelNameItemData, LabelValueItemData } from './types';\n\nexport interface CreateLabelNameContextParams extends BaseParams {\n datasourceUid: string;\n labelName: string;\n}\n\nexport interface CreateLabelValueContextParams extends CreateLabelNameContextParams {\n labelValue: string;\n /** Filter operator (e.g., '=', '!=', '=~', '!~'). Defaults to '=' if not specified */\n operator?: string;\n}\n\nexport class LabelNameNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public labelName: string;\n public img?: string;\n\n constructor(params: CreateLabelNameContextParams & DatasourceMeta) {\n super({ ...params, id: `${params.datasourceUid}-${params.labelName}`, type: 'label_name' });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.labelName = params.labelName;\n this.text = params.labelName;\n this.img = params.img;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.labelName,\n datasourceUid: this.datasourceUid,\n datasourceType: this.datasourceType,\n datasourceName: this.datasourceName,\n labelName: this.labelName,\n text: this.text,\n } satisfies LabelNameItemData,\n };\n }\n}\n\nexport class LabelValueNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public labelName: string;\n public labelValue: string;\n public img?: string;\n public operator: string;\n\n constructor(params: CreateLabelValueContextParams & DatasourceMeta) {\n super({\n ...params,\n id: `${params.datasourceUid}-${params.labelName}-${params.labelValue}-${params.operator || '='}`,\n type: 'label_value',\n });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.labelName = params.labelName;\n this.labelValue = params.labelValue;\n this.text = params.labelValue;\n this.img = params.img;\n this.operator = params.operator || '=';\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.labelValue,\n datasourceUid: this.datasourceUid,\n datasourceType: this.datasourceType,\n datasourceName: this.datasourceName,\n labelName: this.labelName,\n labelValue: this.labelValue,\n text: this.text,\n operator: this.operator,\n } satisfies LabelValueItemData,\n };\n }\n}\n","import { getDataSourceSrv } from '@grafana/runtime';\nimport { NodeData, type NodeDataParams, StructuredNodeData, type StructuredNodeDataParams } from './base';\nimport { ComponentNodeData, type CreateComponentContextParams } from './component';\nimport {\n DashboardNodeData,\n FolderNodeData,\n type CreateDashboardContextParams,\n type CreateFolderContextParams,\n} from './dashboard';\nimport { DatasourceNodeData, type CreateDatasourceContextParams } from './datasource';\nimport { EntityNodeData, type CreateEntityContextParams } from './entity';\nimport {\n LabelNameNodeData,\n LabelValueNodeData,\n type CreateLabelNameContextParams,\n type CreateLabelValueContextParams,\n} from './label';\n\n/**\n * registry to handle the type mappings between ItemData type, params and node data\n */\nexport type ContextTypeRegistry = {\n datasource: { params: CreateDatasourceContextParams; node: DatasourceNodeData };\n label_name: { params: CreateLabelNameContextParams; node: LabelNameNodeData };\n label_value: { params: CreateLabelValueContextParams; node: LabelValueNodeData };\n dashboard: { params: CreateDashboardContextParams; node: DashboardNodeData };\n dashboard_folder: { params: CreateFolderContextParams; node: FolderNodeData };\n structured: { params: StructuredNodeDataParams; node: StructuredNodeData };\n component: { params: CreateComponentContextParams; node: ComponentNodeData };\n entity: { params: CreateEntityContextParams; node: EntityNodeData };\n unknown: { params: NodeDataParams; node: NodeData };\n};\n\nexport type DatasourceMeta = {\n datasourceType: string;\n datasourceName: string;\n img?: string;\n};\n\n/**\n * Helper function to get datasource type from datasource UID\n */\nfunction getDatasourceMeta(datasourceUid: string): DatasourceMeta {\n const datasourceInstance = getDataSourceSrv().getInstanceSettings(datasourceUid);\n return {\n datasourceType: datasourceInstance?.type ?? 'unknown',\n datasourceName: datasourceInstance?.name ?? datasourceUid,\n img: datasourceInstance?.meta?.info?.logos?.small,\n };\n}\n\n/**\n * Creates context nodes based on type with full type safety using generics\n */\nexport function createContextByType<T extends keyof ContextTypeRegistry>(\n type: T,\n params: ContextTypeRegistry[T]['params']\n): ContextTypeRegistry[T]['node'] {\n switch (type) {\n case 'datasource':\n return new DatasourceNodeData({\n ...(params as CreateDatasourceContextParams),\n ...getDatasourceMeta((params as CreateDatasourceContextParams).datasourceUid),\n });\n case 'label_name':\n return new LabelNameNodeData({\n ...(params as CreateLabelNameContextParams),\n ...getDatasourceMeta((params as CreateLabelNameContextParams).datasourceUid),\n });\n case 'label_value':\n return new LabelValueNodeData({\n ...(params as CreateLabelValueContextParams),\n ...getDatasourceMeta((params as CreateLabelValueContextParams).datasourceUid),\n });\n case 'dashboard':\n return new DashboardNodeData(params as CreateDashboardContextParams);\n case 'dashboard_folder':\n return new FolderNodeData(params as CreateFolderContextParams);\n case 'structured':\n return new StructuredNodeData(params as StructuredNodeDataParams);\n case 'component':\n return new ComponentNodeData({\n ...(params as CreateComponentContextParams),\n hidden: true,\n });\n case 'entity':\n return new EntityNodeData(params as CreateEntityContextParams);\n case 'unknown':\n return new NodeData(params as NodeDataParams);\n default:\n console.error(`Unknown context type: ${type}`);\n return new NodeData(params as NodeDataParams);\n }\n}\n","import type { IconName } from '@grafana/ui';\nimport { type NodeData, StructuredNodeData } from './base';\nimport { createContextByType, type ContextTypeRegistry } from './factory';\nimport type { ChatContextItem, ItemDataType } from './types';\n\nconst defaultIcons: Record<ItemDataType, IconName> = {\n datasource: 'database',\n label_name: 'database',\n label_value: 'database',\n dashboard: 'dashboard',\n dashboard_folder: 'folder',\n unknown: 'circle-mono',\n structured: 'gf-grid',\n component: 'gf-grid',\n entity: 'asserts',\n skill: 'play',\n};\n\nfunction getTitleFromContextNode(nodeData: NodeData | StructuredNodeData): string {\n return nodeData instanceof StructuredNodeData\n ? nodeData.formatForLLM().data.name\n : (nodeData.text ?? 'Given Context');\n}\n\nfunction getImgFromContextNode(nodeData: NodeData | StructuredNodeData): string | undefined {\n if ('img' in nodeData) {\n return (nodeData as { img?: string }).img;\n }\n return undefined;\n}\n\n/**\n * Creates a new chat context item that can be added to conversations.\n *\n * This function creates structured context items that provide additional information\n * to the AI assistant during conversations. Context items can include:\n * - Datasources (metrics, logs, traces)\n * - Labels and their values\n * - Dashboards and folders\n * - Structured data objects\n *\n * The created context item includes display metadata (title, icon, image) and\n * the underlying data that will be formatted and sent to the LLM when the\n * context is included in a conversation.\n *\n * @param type - The type of context to create (Datasource, Label, Dashboard etc.)\n * @param params - Type-specific parameters for creating the context item\n * @returns A ChatContextItem that can be added to conversation context\n *\n * @example\n * ```typescript\n * // Create a context that will be passed into the function triggering an assistant open\n * openAssistant({\n * ...\n * origin: 'my-feature',\n * context: [\n * createAssistantContextItem('datasource', {\n * datasourceUid: datasource.uid,\n * img: datasource.meta?.info?.logos?.small,\n * }),\n * ],\n * });\n * ```\n */\nexport function createAssistantContextItem<T extends keyof ContextTypeRegistry>(\n type: T,\n params: ContextTypeRegistry[T]['params']\n): ChatContextItem {\n const nodeData = createContextByType(type, params);\n const defaultTitle = params.title ?? getTitleFromContextNode(nodeData);\n const img = params.img ?? getImgFromContextNode(nodeData);\n return {\n node: {\n id: nodeData.id,\n name: defaultTitle,\n img,\n icon: params.icon ?? defaultIcons[type],\n navigable: false,\n selectable: true,\n data: nodeData,\n },\n occurrences: [],\n };\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, SkillItemData } from './types';\n\nexport interface CreateSkillContextParams extends BaseParams {\n skillId: string;\n skillName: string;\n}\n\nexport class SkillNodeData extends NodeData {\n public skillId: string;\n public skillName: string;\n\n constructor(params: CreateSkillContextParams) {\n super({\n ...params,\n id: params.skillId,\n type: 'skill',\n text: params.skillName,\n });\n this.skillId = params.skillId;\n this.skillName = params.skillName;\n this.text = params.skillName;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.skillName,\n skillId: this.skillId,\n skillName: this.skillName,\n text: this.text,\n } satisfies SkillItemData,\n };\n }\n}\n","import { useMemo } from 'react';\nimport type { ChatContextItem } from './types';\nimport { providePageContext, useProvidePageContext, usePageContext, generateRegistrationId } from './page';\n\nexport interface Question {\n prompt: string;\n title?: string;\n context?: ChatContextItem[];\n}\n\nexport interface QuestionRegistration {\n id: string;\n urlPattern: string | RegExp;\n questions: Question[];\n}\n\n/**\n * Registers questions for specific pages based on URL patterns.\n * Returns a setter function to update the questions dynamically, similar to useState.\n *\n * Multiple registrations with the same URL pattern are allowed and will all be merged\n * when the pattern matches. Each call creates a new independent registration.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialQuestions - Initial array of questions to provide when the pattern matches\n * @returns A setter function to update the questions, with an unregister method attached\n */\nexport function provideQuestions(\n urlPattern: string | RegExp,\n initialQuestions: Question[]\n): ((questions: Question[]) => void) & { unregister: () => void } {\n // Generate a unique registration ID to prevent collisions when multiple registrations exist\n const registrationId = generateRegistrationId('question');\n\n // Convert questions to ChatContextItem format for the underlying system\n const convertQuestionsToContext = (questions: Question[]): ChatContextItem[] => {\n return questions.map((question, index) => ({\n node: {\n id: `question-${registrationId}-${index}`,\n name: question.title || question.prompt,\n navigable: false,\n selectable: true,\n icon: 'question-circle',\n data: {\n type: 'question',\n prompt: question.prompt,\n title: question.title,\n context: question.context || [],\n },\n },\n occurrences: [],\n }));\n };\n\n // Use the existing providePageContext system\n const setContext = providePageContext(urlPattern, convertQuestionsToContext(initialQuestions));\n\n // Create a wrapper that converts between questions and context\n const setQuestions = (newQuestions: Question[]) => {\n setContext(convertQuestionsToContext(newQuestions));\n };\n\n // Add unregister method\n setQuestions.unregister = setContext.unregister;\n\n return setQuestions;\n}\n\n/**\n * React hook for providing questions that automatically cleans up on unmount.\n * This is the recommended way to use questions in React components.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialQuestions - Initial array of questions to provide when the pattern matches\n * @returns A setter function to update the questions\n */\nexport function useProvideQuestions(\n urlPattern: string | RegExp,\n initialQuestions: Question[] = []\n): (questions: Question[]) => void {\n // Generate a stable unique registration ID per component instance to prevent collisions\n const registrationId = useMemo(\n () => generateRegistrationId('question'),\n [] // Empty deps = generated once per component instance\n );\n\n // Convert questions to ChatContextItem format for the underlying system\n const convertQuestionsToContext = (questions: Question[]): ChatContextItem[] => {\n return questions.map((question, index) => ({\n node: {\n id: `question-${registrationId}-${index}`,\n name: question.title ?? question.prompt,\n navigable: false,\n selectable: true,\n icon: 'question-circle',\n data: {\n type: 'question',\n prompt: question.prompt,\n title: question.title,\n context: question.context || [],\n },\n },\n occurrences: [],\n }));\n };\n\n // Use the existing useProvidePageContext system\n const setContext = useProvidePageContext(urlPattern, convertQuestionsToContext(initialQuestions));\n\n // Create a wrapper that converts between questions and context\n const setQuestions = (newQuestions: Question[]) => {\n setContext(convertQuestionsToContext(newQuestions));\n };\n\n return setQuestions;\n}\n\n/**\n * React hook to get all questions that match the current URL.\n * This filters the page context to only return question-type items.\n *\n * @returns Array of questions from all matching registrations\n */\nexport function useQuestions(): Question[] {\n const pageContext = usePageContext({ allowQuestions: true, allowComponents: false });\n\n // Filter and convert context items to questions\n return convertContextToQuestions(pageContext);\n}\n\nconst convertContextToQuestions = (contextItems: ChatContextItem[]): Question[] => {\n return contextItems\n .filter((item) => item.node.data?.type === 'question')\n .map((item) => ({\n prompt: item.node.data?.prompt || item.node.name,\n title: item.node.data?.title,\n context: item.node.data?.context || [],\n }));\n};\n","import type { PluginExtensionAddedFunctionConfig } from '@grafana/data';\n\nexport type CallbackFunction = () => FunctionNamespace[];\nexport type FunctionImplementation = (...args: any[]) => any;\nexport const CALLBACK_EXTENSION_POINT = 'grafana-assistant-app/callback/v0-alpha';\n\nexport type NamedFunctions = Record<string, FunctionImplementation>;\nexport type FunctionNamespace = {\n namespace: string;\n functions: NamedFunctions;\n};\n\nexport function newFunctionNamespace(namespace: string, functions: NamedFunctions): FunctionNamespace {\n return {\n namespace,\n functions,\n };\n}\n\nexport function getExposeAssistantFunctionsConfig(\n namespaces: FunctionNamespace[]\n): PluginExtensionAddedFunctionConfig<() => FunctionNamespace[]> {\n return {\n title: 'callback',\n targets: [CALLBACK_EXTENSION_POINT],\n fn: () => {\n return namespaces.map((namespace) => {\n return {\n namespace: namespace.namespace,\n functions: namespace.functions,\n };\n });\n },\n };\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs\");","import { getObservablePluginLinks } from '@grafana/runtime';\n// biome-ignore lint/suspicious/noDeprecatedImports: throwError and timer have deprecated overloads but we use the non-deprecated factory/single-arg forms\nimport { catchError, defer, map, type Observable, of, retry, throwError, timer } from 'rxjs';\n\nexport const ASSISTANT_PLUGIN_ID = 'grafana-assistant-app';\nexport const ASSISTANT_PLUGIN_TITLE = 'Grafana Assistant';\n\nconst MAX_RETRY_ATTEMPTS = 10;\nconst INITIAL_RETRY_DELAY = 100; // 100ms\nconst MAX_RETRY_DELAY = 5000; // 5 seconds\n\n/**\n * Check if the assistant is available.\n * @returns An observable that emits true if the assistant is available, false otherwise.\n */\nexport function isAssistantAvailable(): Observable<boolean> {\n // this is to avoid crashing in older Grafana versions\n if (!getObservablePluginLinks) {\n return of(false);\n }\n\n // Use defer to make the call lazy and handle both sync and async errors\n return defer(() => {\n try {\n const links = getObservablePluginLinks({\n extensionPointId: 'grafana/extension-sidebar/v0-alpha',\n });\n return links.pipe(\n map((links: Array<{ pluginId: string; title: string }>) =>\n links.some((link) => link.pluginId === ASSISTANT_PLUGIN_ID && link.title === ASSISTANT_PLUGIN_TITLE)\n )\n );\n } catch (error) {\n // If getObservablePluginLinks throws synchronously, convert to observable error\n return throwError(() => error);\n }\n }).pipe(\n retry({\n count: MAX_RETRY_ATTEMPTS,\n delay: (error, retryCount) => {\n // Check if error indicates Grafana hasn't started yet\n const errorMessage = error?.message?.toLowerCase() || '';\n const isGrafanaNotReady =\n errorMessage.includes('can only be used after') ||\n errorMessage.includes('grafana instance has started') ||\n errorMessage.includes('not started');\n\n // Don't retry for non-race-condition errors\n if (!isGrafanaNotReady) {\n throw error;\n }\n\n // Exponential backoff: delay = INITIAL_RETRY_DELAY * 2^retryCount, capped at MAX_RETRY_DELAY\n const delayMs = Math.min(INITIAL_RETRY_DELAY * 2 ** (retryCount - 1), MAX_RETRY_DELAY);\n return timer(delayMs);\n },\n }),\n catchError(() => {\n // After all retries exhausted, return false\n return of(false);\n })\n );\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/data\");","import { BusEventBase, BusEventWithPayload } from '@grafana/data';\nimport { getAppEvents, reportInteraction } from '@grafana/runtime';\nimport type { ChatContextItem } from './context/types';\nimport { ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE } from './plugin';\n\ninterface OpenExtensionSidebarPayload {\n props?: Record<string, unknown>;\n pluginId: string;\n componentTitle: string;\n}\n\nclass OpenExtensionSidebarEvent extends BusEventWithPayload<OpenExtensionSidebarPayload> {\n static type = 'open-extension-sidebar';\n}\n\nclass CloseExtensionSidebarEvent extends BusEventBase {\n static type = 'close-extension-sidebar';\n}\n\nclass ToggleExtensionSidebarEvent extends BusEventWithPayload<OpenExtensionSidebarPayload> {\n static type = 'toggle-extension-sidebar';\n}\n\nfunction openExtensionSidebar(pluginId: string, componentTitle: string, props?: Record<string, unknown>) {\n const event = new OpenExtensionSidebarEvent({\n pluginId,\n componentTitle,\n props,\n });\n getAppEvents().publish(event);\n}\n\nfunction closeExtensionSidebar() {\n const event = new CloseExtensionSidebarEvent();\n getAppEvents().publish(event);\n}\n\nfunction toggleExtensionSidebar(pluginId: string, componentTitle: string, props?: Record<string, unknown>) {\n const event = new ToggleExtensionSidebarEvent({\n pluginId,\n componentTitle,\n props,\n });\n getAppEvents().publish(event);\n}\n\nexport type OpenAssistantProps = {\n origin: string;\n\n prompt?: string;\n context?: ChatContextItem[];\n autoSend?: boolean;\n /** Mode to open the assistant in. Built-in modes: 'assistant', 'investigation', 'dashboarding'. Can also be a backend agent ID. */\n mode?: string;\n /** When set, sends the prompt as a follow-up into this existing conversation instead of creating a new one. */\n chatId?: string;\n /** When true, append context to the chat instead of replacing it. */\n appendContext?: boolean;\n};\n\n/**\n * Open the Grafana Assistant sidebar with a given initial prompt.\n *\n * @param props - The props to pass to the assistant.\n * @param props.origin - The origin of the request that opened the assistant. This is used to track the source of the request. Should be a structured string using forward slashes, with the first part as a namespace. Examples: 'grafana-datasources/prometheus/query-builder', 'grafana-slo-app/slo-editor-overview', 'grafana/trace-view-analyzer`.\n * @param props.prompt - The initial prompt to display in the assistant.\n * @param props.context - The initial context to display in the assistant. Created with `createContext`.\n * @param props.autoSend - Whether to automatically send the initial prompt. When true, opens a chat and sends the initial prompt right away. When false, opens chat and updates user message without sending it. Defaults to true.\n * @param props.mode - The mode to open the assistant in. Built-in modes: 'assistant', 'investigation', 'dashboarding'. Can also be a backend agent ID. Defaults to 'assistant'.\n * @param props.chatId - When set, sends the prompt as a follow-up into this existing conversation instead of creating a new one.\n */\nexport function openAssistant(props: OpenAssistantProps) {\n reportInteraction('grafana_assistant_app_opened_sidebar', {\n from: props.origin,\n });\n\n openExtensionSidebar(ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE, {\n initialPrompt: props.prompt,\n initialContext: props.context,\n initialAutoSend: props.autoSend ?? true,\n origin: props.origin,\n initialMode: props.mode,\n chatId: props.chatId,\n appendContext: props.appendContext,\n });\n}\n\n/**\n * Close the Grafana Assistant sidebar.\n */\nexport function closeAssistant() {\n closeExtensionSidebar();\n}\n\nexport function toggleAssistant(props: OpenAssistantProps) {\n reportInteraction('grafana_assistant_app_toggled_sidebar', {\n from: props.origin,\n prompt: props.prompt ?? '',\n });\n\n toggleExtensionSidebar(ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE, {\n initialPrompt: props.prompt,\n initialContext: props.context,\n initialAutoSend: props.autoSend ?? true,\n origin: props.origin,\n initialMode: props.mode,\n chatId: props.chatId,\n appendContext: props.appendContext,\n });\n}\n","import { useEffect, useState } from 'react';\nimport { isAssistantAvailable } from './plugin';\nimport { closeAssistant, openAssistant, toggleAssistant, type OpenAssistantProps } from './sidebar';\n\nexport type AssistantHook = {\n /** Whether the availability check is still in progress. */\n isLoading: boolean;\n isAvailable: boolean;\n openAssistant: ((props: OpenAssistantProps) => void) | undefined;\n closeAssistant: (() => void) | undefined;\n toggleAssistant: ((props: OpenAssistantProps) => void) | undefined;\n};\n/**\n * Hook to check if the assistant is available and return the open, close, and toggle functions.\n * @returns {AssistantHook}\n */\nexport function useAssistant(): AssistantHook {\n const [available, setAvailable] = useState<boolean | undefined>(undefined);\n\n useEffect(() => {\n const sub = isAssistantAvailable().subscribe(setAvailable);\n return () => sub.unsubscribe();\n }, []);\n\n const isAvailable = available ?? false;\n\n return {\n isLoading: available === undefined,\n isAvailable,\n openAssistant: isAvailable ? openAssistant : undefined,\n closeAssistant: isAvailable ? closeAssistant : undefined,\n toggleAssistant: isAvailable ? toggleAssistant : undefined,\n };\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"react/jsx-runtime\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/ui\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@emotion/css\");","import { useEffect } from 'react';\nimport { Button, IconButton, useStyles2 } from '@grafana/ui';\nimport { css } from '@emotion/css';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { reportInteraction } from '@grafana/runtime';\n\nexport interface OpenAssistantButtonProps {\n /** Prompt to pass to the openAssistant function. */\n prompt: string;\n /** Origin of the request that opened the assistant. This is used to track the source of the request. Should be a structured string using forward slashes, with the first part as a namespace. Examples: 'grafana-datasources/prometheus/query-builder', 'grafana-slo-app/slo-editor-overview', 'grafana/trace-view-analyzer`. */\n origin: string;\n /** Context to pass to the openAssistant function. Optional, defaults to undefined. Created with `createAssistantContextItem`. */\n context?: ChatContextItem[];\n /** Whether to automatically send the prompt. Optional, defaults to true. */\n autoSend?: boolean;\n /** Text to display on the button. Optional, defaults to 'Analyze with Assistant' */\n title?: string;\n /** Button size, defaults to sm */\n size?: 'xs' | 'sm' | 'md' | 'lg';\n /** If true, the button will be Assistant icon only with name as title. Defaults to false. */\n iconOnlyButton?: boolean;\n /** Function to call when the button is clicked. Optional, defaults to undefined. */\n onClick?: () => void;\n}\n\n/**\n * A button component that opens the Grafana Assistant with configurable prompt and context.\n */\nexport function OpenAssistantButton(props: OpenAssistantButtonProps) {\n // If the assistant is not available, return empty\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <OpenAssistantButtonView {...props} openAssistant={openAssistant} />;\n}\n\n/**\n * Presentational component separated from OpenAssistantButton to avoid hook dependencies in Storybook.\n * It is not exported for users of the package.\n */\nexport function OpenAssistantButtonView({\n prompt,\n origin,\n context,\n autoSend = true,\n title = 'Analyze with Assistant',\n size = 'sm',\n iconOnlyButton = false,\n openAssistant,\n onClick,\n}: OpenAssistantButtonProps & {\n openAssistant: (props: OpenAssistantProps) => void;\n}) {\n const styles = useStyles2(getStyles);\n\n useEffect(() => {\n reportInteraction('grafana_assistant_app_open_sidebar_button_displayed', {\n from: origin,\n });\n }, [origin]);\n\n return (\n <>\n {iconOnlyButton ? (\n <IconButton\n name=\"ai-sparkle\"\n onClick={() => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n }}\n variant=\"secondary\"\n size={size}\n aria-label={title}\n className={styles.icon}\n tooltip={title}\n data-testid=\"assistant-icon-button\"\n />\n ) : (\n <Button\n icon=\"ai-sparkle\"\n onClick={() => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n }}\n variant=\"secondary\"\n fill=\"solid\"\n size={size}\n title={title}\n aria-label={title}\n className={styles.button}\n data-testid=\"assistant-button\"\n >\n {title}\n </Button>\n )}\n </>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const baseBackground = theme.colors.secondary.main;\n const elevatedBackground = theme.colors.emphasize(baseBackground, 0.05);\n\n // Canvas is what's typically underneath buttons\n const underlyingColor = theme.colors.background.canvas;\n\n const borderWidth = 1;\n const outerRadius = theme.shape.radius.default;\n // inner radius = outer radius - border width, but take at least 1px\n const innerRadius = `max(calc(${outerRadius} - ${borderWidth}px), 1px)`;\n\n // Gradient border layer (::before)\n const gradientBorderLayer = {\n content: '\"\"',\n position: 'absolute' as const,\n inset: 0,\n borderRadius: outerRadius,\n cornerShape: 'squircle',\n background: 'linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))',\n zIndex: -2,\n pointerEvents: 'none' as const,\n };\n\n // Solid background layer factory (::after)\n // Layer transparent color over canvas to make it opaque and mask the gradient properly\n const solidBackgroundLayer = (background: string) => ({\n content: '\"\"',\n position: 'absolute' as const,\n inset: `${borderWidth}px`,\n borderRadius: innerRadius,\n cornerShape: 'squircle',\n background: `linear-gradient(${background}, ${background}), ${underlyingColor}`,\n zIndex: -1,\n transition: 'none',\n pointerEvents: 'none' as const,\n });\n\n return {\n button: css({\n label: 'assistant-button',\n width: 'fit-content',\n maxWidth: '100%',\n position: 'relative',\n isolation: 'isolate',\n border: 'none',\n transition: 'none !important',\n '&::before': gradientBorderLayer,\n '&::after': {\n ...solidBackgroundLayer(baseBackground),\n transition: 'none',\n },\n '&:hover': {\n transition: 'none !important',\n },\n '&:hover::after': {\n background: `linear-gradient(${elevatedBackground}, ${elevatedBackground}), ${underlyingColor}`,\n },\n }),\n icon: css({\n label: 'assistant-icon',\n position: 'relative',\n isolation: 'isolate',\n border: 'none',\n background: 'none',\n padding: theme.spacing(0.5),\n '&::before': { ...gradientBorderLayer, transition: 'background 0.1s ease' },\n '&:hover::after': {\n ...solidBackgroundLayer(baseBackground),\n background: `linear-gradient(${elevatedBackground}, ${elevatedBackground}), ${underlyingColor}`,\n },\n }),\n };\n};\n","import { type ReactElement, useEffect } from 'react';\nimport { Button, ButtonGroup, Dropdown, Tooltip, useStyles2 } from '@grafana/ui';\nimport { css, cx } from '@emotion/css';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { reportInteraction } from '@grafana/runtime';\n\nexport interface OpenAssistantSplitButtonProps {\n /** Prompt to pass to the openAssistant function. */\n prompt: string;\n /** Origin of the request that opened the assistant. */\n origin: string;\n /** Context to pass to the openAssistant function. Optional, defaults to undefined. */\n context?: ChatContextItem[];\n /** Whether to automatically send the prompt. Optional, defaults to true. */\n autoSend?: boolean;\n /** Text to display on the button. Optional, defaults to 'Chat with Assistant' */\n title?: string;\n /** Button size, defaults to sm */\n size?: 'sm' | 'md' | 'lg';\n /** Function to call when the main button is clicked. Optional. */\n onClick?: () => void;\n /** Additional menu items to show in the dropdown. Optional. */\n menuItems?: ReactElement;\n /** Tooltip text to display on hover. Optional. */\n tooltip?: string;\n /** Width for the dropdown/chevron segment. Accepts pixels as number or any CSS width value. */\n dropdownButtonWidth?: number | string;\n}\n\ntype AssistantButtonSize = NonNullable<OpenAssistantSplitButtonProps['size']>;\n\nconst defaultDropdownButtonWidths: Record<AssistantButtonSize, number> = {\n sm: 32,\n md: 36,\n lg: 40,\n};\n\n/**\n * A split button component that opens the Grafana Assistant with a dropdown for additional actions.\n * The gradient border wraps around both buttons as a unified control.\n */\nexport function OpenAssistantSplitButton(props: OpenAssistantSplitButtonProps) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <OpenAssistantSplitButtonView {...props} openAssistant={openAssistant} />;\n}\n\nexport function OpenAssistantSplitButtonView({\n prompt,\n origin,\n context,\n autoSend = true,\n title = 'Chat with Assistant',\n size = 'sm',\n onClick,\n menuItems,\n tooltip,\n dropdownButtonWidth,\n openAssistant,\n}: OpenAssistantSplitButtonProps & {\n openAssistant: (props: OpenAssistantProps) => void;\n}) {\n const styles = useStyles2(getStyles);\n const hasMenuItems = Boolean(menuItems);\n const resolvedDropdownButtonWidth = toCssWidth(dropdownButtonWidth ?? defaultDropdownButtonWidths[size]);\n\n useEffect(() => {\n reportInteraction('grafana_assistant_app_open_sidebar_split_button_displayed', {\n from: origin,\n });\n }, [origin]);\n\n const handleMainClick = () => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n };\n\n const wrapperContent = (\n <div className={styles.wrapper}>\n <ButtonGroup className={styles.buttonGroup}>\n <Button\n icon=\"ai-sparkle\"\n onClick={handleMainClick}\n variant=\"secondary\"\n fill=\"solid\"\n size={size}\n aria-label={title}\n className={cx(styles.segmentButton, hasMenuItems ? styles.mainButtonSplit : styles.mainButtonSolo)}\n data-testid=\"assistant-split-button-main\"\n >\n {title}\n </Button>\n {menuItems && (\n <Dropdown overlay={menuItems}>\n <Button\n variant=\"secondary\"\n icon=\"angle-down\"\n size={size}\n aria-label=\"More AI actions\"\n className={cx(styles.segmentButton, styles.dropdownButton)}\n style={{ width: resolvedDropdownButtonWidth, minWidth: resolvedDropdownButtonWidth }}\n data-testid=\"assistant-split-button-dropdown\"\n />\n </Dropdown>\n )}\n </ButtonGroup>\n </div>\n );\n\n return tooltip ? <Tooltip content={tooltip}>{wrapperContent}</Tooltip> : wrapperContent;\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const baseBackground = theme.colors.secondary.main;\n const elevatedBackground = theme.colors.emphasize(baseBackground, 0.05);\n const underlyingColor = theme.colors.background.canvas;\n const dividerColor = theme.colors.border.weak;\n const borderWidth = 1;\n const outerRadius = theme.shape.radius.default;\n const innerRadius = `max(calc(${outerRadius} - ${borderWidth}px), 1px)`;\n\n return {\n wrapper: css({\n label: 'assistant-split-button-wrapper',\n position: 'relative',\n isolation: 'isolate',\n display: 'inline-block',\n // Gradient border around the entire button group\n '&::before': {\n content: '\"\"',\n position: 'absolute',\n inset: 0,\n borderRadius: outerRadius,\n cornerShape: 'squircle',\n background: 'linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))',\n zIndex: -1,\n pointerEvents: 'none',\n },\n // Solid background layer\n '&::after': {\n content: '\"\"',\n position: 'absolute',\n inset: `${borderWidth}px`,\n borderRadius: innerRadius,\n cornerShape: 'squircle',\n background: `linear-gradient(${baseBackground}, ${baseBackground}), ${underlyingColor}`,\n zIndex: -1,\n pointerEvents: 'none',\n },\n }),\n buttonGroup: css({\n label: 'assistant-split-button-group',\n gap: 0,\n position: 'relative',\n zIndex: 1,\n borderRadius: innerRadius,\n overflow: 'hidden',\n // Make buttons transparent to show the wrapper's gradient\n '& button': {\n border: 'none',\n boxShadow: 'none',\n background: 'transparent !important',\n },\n }),\n segmentButton: css({\n label: 'assistant-split-button-segment',\n position: 'relative',\n '&:hover': {\n background: `${elevatedBackground} !important`,\n },\n '&:focus-visible': {\n background: `${elevatedBackground} !important`,\n },\n '&[aria-expanded=\"true\"]': {\n background: `${elevatedBackground} !important`,\n },\n }),\n mainButtonSolo: css({\n label: 'assistant-split-button-main-solo',\n borderRadius: innerRadius,\n }),\n mainButtonSplit: css({\n label: 'assistant-split-button-main-split',\n borderTopLeftRadius: innerRadius,\n borderBottomLeftRadius: innerRadius,\n borderTopRightRadius: 0,\n borderBottomRightRadius: 0,\n }),\n dropdownButton: css({\n label: 'assistant-split-button-dropdown',\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n gap: 0,\n borderTopLeftRadius: 0,\n borderBottomLeftRadius: 0,\n borderTopRightRadius: innerRadius,\n borderBottomRightRadius: innerRadius,\n padding: '0 !important',\n boxShadow: `inset 1px 0 0 ${dividerColor}`,\n '& svg': {\n margin: 0,\n },\n }),\n };\n};\n\nfunction toCssWidth(width: number | string): string {\n return typeof width === 'number' ? `${width}px` : width;\n}\n","import type { GrafanaTheme2 } from '@grafana/data';\n\n/**\n * Default gradient colors for the assistant\n */\nconst GRADIENT_COLORS = {\n PURPLE: 'rgb(168, 85, 247)',\n ORANGE: 'rgb(249, 115, 22)',\n} as const;\n\n// FIXME: use SDK as single source of truth for these color schemes?\n\n/**\n * Returns the colors of the background gradient based on the theme.\n *\n * @param theme - The Grafana theme object.\n * @returns The colors of the background gradient as tuple.\n */\nexport const getBackgroundGradientColors = (theme: GrafanaTheme2): [string, string] => {\n const defaultGradientColors: [string, string] = [GRADIENT_COLORS.PURPLE, GRADIENT_COLORS.ORANGE];\n\n // Check if the theme does not use gradients by default\n if (theme.name.toLowerCase() === 'dark' || theme.name.toLowerCase() === 'light') {\n return defaultGradientColors;\n }\n\n // If the theme uses gradients, extract the colors from the gradient string\n const gradientString = theme.colors.gradients.brandHorizontal;\n const hexColorRegex = /#[0-9A-Fa-f]{6}/g;\n const matches = gradientString.match(hexColorRegex);\n if (!matches || matches.length < 2) {\n // Fallback to default colors if extraction fails\n return defaultGradientColors;\n }\n\n return [matches[0], matches[1]];\n};\n\n/**\n * Creates animation keyframes for a rotating gradient border effect.\n * This is used for loading states in inputs and other components.\n *\n * @param theme - The Grafana theme object\n * @param backgroundColor - The background color to use in the animation\n * @param color1 - First gradient color (optional, defaults to theme purple)\n * @param color2 - Second gradient color (optional, defaults to theme orange)\n * @returns Animation keyframes object for use with @emotion/css keyframes\n *\n * @example\n * ```ts\n * const borderAnimation = keyframes({\n * label: 'border-animation',\n * ...createBorderAnimation(theme, theme.colors.background.primary),\n * });\n * ```\n */\nexport const createBorderAnimation = (\n theme: GrafanaTheme2,\n backgroundColor: string,\n color1?: string,\n color2?: string\n): Record<string, { backgroundImage: string }> => {\n const animationSteps = Array.from({ length: 101 }, (_, i) => i);\n const animationFrames: Record<string, { backgroundImage: string }> = {};\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n const finalColor1 = color1 ?? gradientColor1;\n const finalColor2 = color2 ?? gradientColor2;\n\n for (const step of animationSteps) {\n animationFrames[`${step}%`] = {\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from ${step * 3.6}deg, transparent 60%, ${finalColor1} 80%, ${finalColor2} 100%, transparent 15%)\n `,\n };\n }\n\n return animationFrames;\n};\n","import type { InlineToolRunnable } from '../tools/types';\n\nexport interface InlineAssistantPromptOptions {\n prompt: string;\n agentName?: string;\n agentId?: string;\n systemPrompt?: string;\n tools?: InlineToolRunnable[];\n onStart?: () => void;\n onDelta?: (delta: string) => void;\n onComplete?: (text: string) => void;\n onError?: (error: Error) => void;\n}\n\nexport interface InlineAssistant {\n sendPrompt(options: InlineAssistantPromptOptions): Promise<void>;\n cancel(): void;\n dispose(): void;\n}\n\n// Extend window interface for global registry\ndeclare global {\n interface Window {\n [key: string]: any;\n }\n}\n\nexport type InlineAssistantFactory = (origin: string) => Promise<InlineAssistant>;\nexport type InlineAssistantInitializer = () => Promise<void>;\n\n// Global registry keys for cross-plugin sharing\nconst GLOBAL_FACTORY_KEY = '__grafanaAssistantInlineFactory__';\nconst GLOBAL_INITIALIZER_KEY = '__grafanaAssistantInlineInitializer__';\nconst GLOBAL_INITIALIZATION_PROMISE_KEY = '__grafanaAssistantInlineInitPromise__';\n\nexport function setInlineAssistantFactory(fn: InlineAssistantFactory): void {\n const existing = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (existing && existing !== fn) {\n console.warn('InlineAssistant factory already set; ignoring subsequent setInlineAssistantFactory call');\n return;\n }\n if (!existing) {\n window[GLOBAL_FACTORY_KEY] = fn;\n }\n}\n\n/**\n * Register a lazy initializer that will be called on first use.\n * The plugin code should register this to enable lazy loading of the inline assistant.\n *\n * This uses global storage (window) so that all plugins share the same initializer,\n * regardless of which plugin instance or package version loads first.\n */\nexport function setInlineAssistantInitializer(fn: InlineAssistantInitializer): void {\n const existing = window[GLOBAL_INITIALIZER_KEY] as InlineAssistantInitializer | undefined;\n if (existing && existing !== fn) {\n console.warn('InlineAssistant initializer already set; ignoring subsequent setInlineAssistantInitializer call');\n return;\n }\n if (!existing) {\n window[GLOBAL_INITIALIZER_KEY] = fn;\n }\n}\n\n/**\n * Ensure the inline assistant is initialized. If an initializer is registered,\n * it will be called on first use. Otherwise, checks if factory is already registered.\n *\n * Uses global storage (window) so that initialization is shared across all plugins.\n */\nexport async function ensureInlineAssistantInitialized(): Promise<void> {\n // If factory is already set, we're good\n const factory = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (factory) {\n return;\n }\n\n // If no initializer is registered, throw error\n const initializer = window[GLOBAL_INITIALIZER_KEY] as InlineAssistantInitializer | undefined;\n if (!initializer) {\n throw new Error(\n 'InlineAssistant not initialized. Make sure the Grafana Assistant plugin is loaded and initialized.'\n );\n }\n\n // If initialization is in progress, wait for it\n const existingPromise = window[GLOBAL_INITIALIZATION_PROMISE_KEY] as Promise<void> | null | undefined;\n if (existingPromise) {\n return existingPromise;\n }\n\n // Start initialization\n const initPromise = (async () => {\n try {\n await initializer();\n } catch (err) {\n // Reset on error so retry is possible\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = null;\n throw err;\n }\n })();\n\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = initPromise;\n return initPromise;\n}\n\nexport function getInlineAssistantFactory(): InlineAssistantFactory {\n const factory = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (!factory) {\n throw new Error('InlineAssistant factory not initialized. Make sure the Grafana Assistant plugin is loaded.');\n }\n return factory;\n}\n","const nestedErrorKeys = ['message', 'error', 'err', 'detail', 'details'] as const;\n\nfunction getStringValue(value: unknown): string | null {\n if (typeof value !== 'string') {\n return null;\n }\n\n const trimmedValue = value.trim();\n return trimmedValue === '' ? null : trimmedValue;\n}\n\nfunction isUnhelpfulErrorMessage(message: string | null): boolean {\n if (!message) {\n return true;\n }\n\n return message === '[object Object]' || message === 'Error' || message === 'Unknown error';\n}\n\nfunction extractNestedErrorMessage(error: unknown, visited = new Set<object>()): string | null {\n const directString = getStringValue(error);\n if (directString) {\n return directString;\n }\n\n if (error instanceof Error) {\n const errorMessage = getStringValue(error.message);\n if (!isUnhelpfulErrorMessage(errorMessage)) {\n return errorMessage;\n }\n\n const nestedErrorMessage = extractNestedErrorMessage(error.cause, visited);\n if (nestedErrorMessage) {\n return nestedErrorMessage;\n }\n\n const ownPropertiesMessage = extractNestedErrorMessage(\n Object.fromEntries(\n Object.entries(error as Error & Record<string, unknown>).filter(([key]) => key !== 'message' && key !== 'name')\n ),\n visited\n );\n if (ownPropertiesMessage) {\n return ownPropertiesMessage;\n }\n\n return errorMessage ?? getStringValue(error.name) ?? null;\n }\n\n if (!error || typeof error !== 'object') {\n return null;\n }\n\n if (visited.has(error)) {\n return null;\n }\n visited.add(error);\n\n const errorRecord = error as Record<string, unknown>;\n\n if ('data' in errorRecord) {\n const nestedDataMessage = extractNestedErrorMessage(errorRecord.data, visited);\n if (nestedDataMessage) {\n return nestedDataMessage;\n }\n }\n\n for (const key of nestedErrorKeys) {\n if (key in errorRecord) {\n const nestedMessage = extractNestedErrorMessage(errorRecord[key], visited);\n if (nestedMessage) {\n return nestedMessage;\n }\n }\n }\n\n const status = errorRecord.status;\n const statusText = getStringValue(errorRecord.statusText);\n if ((typeof status === 'number' || typeof status === 'string') && statusText) {\n return `HTTP ${status}: ${statusText}`;\n }\n\n if (Array.isArray(error)) {\n const nestedMessages = error\n .map((item) => extractNestedErrorMessage(item, visited))\n .filter((message): message is string => Boolean(message));\n\n if (nestedMessages.length > 0) {\n return nestedMessages.join('; ');\n }\n }\n\n return null;\n}\n\n/**\n * Extract error message from backend errors (handles various error formats).\n *\n * @internal SDK-private helper for useInlineAssistant. Not part of the public\n * `@grafana/assistant` surface — do not re-export from `index.ts`.\n */\nexport function extractErrorMessage(error: unknown): string {\n const extractedMessage = extractNestedErrorMessage(error);\n if (extractedMessage) {\n return extractedMessage;\n }\n\n if (error && typeof error === 'object') {\n try {\n return JSON.stringify(error);\n } catch {\n return 'Unknown error (could not serialize error object)';\n }\n }\n\n if (error == null) {\n return 'Unknown error';\n }\n\n return String(error);\n}\n","import { useState, useCallback, useRef, useEffect } from 'react';\nimport type { InlineAssistantOptions, InlineAssistantResult } from './types';\nimport { getInlineAssistantFactory, type InlineAssistant, ensureInlineAssistantInitialized } from './inlineAssistant';\nimport { extractErrorMessage } from '../utils/errorHandling';\n\n/**\n * React hook for inline assistant generation with streaming support.\n *\n * This hook enables generating content (like panel titles or descriptions) inline\n * without opening the assistant sidebar. Each hook instance creates its own chat\n * conversation, so all generations from the same instance are grouped together.\n * Generated content is ephemeral - it won't appear in the user's chat history\n * but will be tracked in the admin UI for analytics.\n *\n * Uses the full BaseMultiStepAgent infrastructure for tool execution and multi-step workflows.\n *\n * The implementation is lazy-loaded on first use to reduce initial bundle size.\n *\n * @example\n * ```typescript\n * function PanelEditor() {\n * const { generate, isGenerating, content, error, reset } = useInlineAssistant();\n * const [title, setTitle] = useState('');\n *\n * const handleGenerate = () => {\n * generate({\n * prompt: 'Generate a panel title for CPU metrics',\n * origin: 'grafana/panel-editor/title',\n * systemPrompt: 'Generate only the title text, no explanation',\n * onComplete: (text) => setTitle(text.trim()),\n * onError: (err) => console.error(err)\n * });\n * };\n *\n * return (\n * <div>\n * <input value={title} onChange={(e) => setTitle(e.target.value)} />\n * <button onClick={handleGenerate} disabled={isGenerating}>\n * {isGenerating ? 'Generating...' : 'Generate with Assistant'}\n * </button>\n * {isGenerating && <div>{content}</div>}\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Using tools with inline assistant\n * import { lokiQueryHandlerTool } from 'agent/tools';\n *\n * function ComponentWithTools() {\n * const { generate } = useInlineAssistant();\n *\n * const handleGenerate = async () => {\n * await generate({\n * prompt: 'Query Loki for error logs from the last hour',\n * origin: 'my-app/component',\n * tools: [lokiQueryHandlerTool],\n * onComplete: (text) => console.log('Generated:', text),\n * });\n * };\n *\n * return <button onClick={handleGenerate}>Generate</button>;\n * }\n * ```\n */\nexport function useInlineAssistant(): InlineAssistantResult {\n const [isGenerating, setIsGenerating] = useState(false);\n const [content, setContent] = useState('');\n const [error, setError] = useState<Error | null>(null);\n const assistantRef = useRef<InlineAssistant | null>(null);\n\n /**\n * Reset error and content state\n */\n const reset = useCallback(() => {\n setError(null);\n setContent('');\n }, []);\n\n /**\n * Cancel the current generation\n */\n const cancel = useCallback(() => {\n if (assistantRef.current) {\n assistantRef.current.cancel();\n }\n setIsGenerating(false);\n }, []);\n\n /**\n * Generate content with the given options\n */\n const generate = useCallback(async (options: InlineAssistantOptions): Promise<void> => {\n // Reset state\n setError(null);\n setContent('');\n setIsGenerating(true);\n\n try {\n // Ensure the inline assistant is initialized (lazy-loads on first use)\n await ensureInlineAssistantInitialized();\n\n const factory = getInlineAssistantFactory();\n\n // Create or reuse assistant for this origin\n if (!assistantRef.current) {\n assistantRef.current = await factory(options.origin);\n }\n\n await assistantRef.current.sendPrompt({\n prompt: options.prompt,\n agentName: options.agentName,\n agentId: options.agentId,\n systemPrompt: options.systemPrompt,\n tools: options.tools,\n onStart: () => {\n setIsGenerating(true);\n },\n onDelta: (delta) => {\n setContent((prev) => prev + delta);\n options.onDelta?.(delta);\n },\n onComplete: (text) => {\n setContent(text);\n setIsGenerating(false);\n options.onComplete?.(text);\n },\n onError: (err) => {\n setError(err);\n setIsGenerating(false);\n options.onError?.(err);\n },\n });\n } catch (err) {\n const error = new Error(extractErrorMessage(err), { cause: err });\n setError(error);\n setIsGenerating(false);\n options.onError?.(error);\n }\n }, []);\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n if (assistantRef.current) {\n assistantRef.current.cancel();\n assistantRef.current.dispose();\n assistantRef.current = null;\n }\n };\n }, []);\n\n return {\n generate,\n isGenerating,\n content,\n error,\n cancel,\n reset,\n };\n}\n","import { useCallback, useEffect, useRef } from 'react';\nimport { useInlineAssistant } from '../../inline/useInlineAssistant';\n\nexport interface UseAIGenerationOptions {\n value: string;\n onChange: (value: string) => void;\n origin: string;\n systemPrompt?: string;\n onComplete?: (text: string) => void;\n onError?: (error: Error) => void;\n onDelta?: (delta: string) => void;\n disabled?: boolean;\n autoGenerate?: boolean;\n streaming?: boolean;\n getUserPrompt?: (textInput: string) => string;\n}\n\nexport function useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n}: UseAIGenerationOptions) {\n const { generate, isGenerating, content, error, reset } = useInlineAssistant();\n const hasAutoGenerated = useRef(false);\n const valueBeforeGeneration = useRef(value);\n const getUserPromptRef = useRef(getUserPrompt);\n getUserPromptRef.current = getUserPrompt;\n\n const displayValue = isGenerating ? (streaming ? content : '') : value;\n const resolvedPrompt = getUserPrompt ? getUserPrompt(value.trim()) : value.trim();\n const isSendDisabled = !resolvedPrompt || disabled || isGenerating;\n\n const doGenerate = useCallback(\n (prompt: string) => {\n valueBeforeGeneration.current = value;\n onChange('');\n reset();\n\n generate({\n prompt,\n origin,\n systemPrompt,\n onDelta,\n onComplete: (text) => {\n onChange(text);\n onComplete?.(text);\n },\n onError: (err) => {\n onChange(valueBeforeGeneration.current);\n onError?.(err);\n },\n });\n },\n [value, onChange, origin, systemPrompt, onDelta, onComplete, onError, generate, reset]\n );\n\n // Auto-generate at most once, on mount, evaluating the props as they are at mount.\n const maybeAutoGenerateRef = useRef<() => void>(() => {});\n maybeAutoGenerateRef.current = () => {\n if (autoGenerate && systemPrompt && !value && !hasAutoGenerated.current && !disabled) {\n hasAutoGenerated.current = true;\n doGenerate(systemPrompt);\n }\n };\n useEffect(() => {\n maybeAutoGenerateRef.current();\n }, []);\n\n const handleGenerate = useCallback(() => {\n const fn = getUserPromptRef.current;\n const prompt = fn ? fn(value.trim()) : value.trim();\n if (!prompt || disabled || isGenerating) {\n return;\n }\n doGenerate(prompt);\n }, [value, disabled, isGenerating, doGenerate]);\n\n return {\n displayValue,\n isSendDisabled,\n handleGenerate,\n isGenerating,\n error,\n };\n}\n","import { useRef, useState } from 'react';\n\nconst GENERATING_PHRASES = [\n 'Generating...',\n 'Brewing...',\n 'Cooking...',\n 'Crunching...',\n 'Phrasing...',\n 'Wording...',\n 'Crafting...',\n 'Composing...',\n 'Drafting...',\n 'Shaping...',\n 'Forming...',\n 'Molding...',\n 'Sketching...',\n 'Whipping up...',\n 'Conjuring...',\n 'Stirring...',\n];\n\n/**\n * Returns a random placeholder phrase while generating, or the provided\n * default placeholder when idle. A new phrase is picked each time generation starts.\n */\nexport function useGeneratingPlaceholder(isGenerating: boolean, defaultPlaceholder: string): string {\n const [phrase, setPhrase] = useState('');\n const wasGenerating = useRef(false);\n\n if (isGenerating && !wasGenerating.current) {\n const next = GENERATING_PHRASES[Math.floor(Math.random() * GENERATING_PHRASES.length)];\n setPhrase(next);\n wasGenerating.current = true;\n return next;\n }\n\n if (!isGenerating) {\n wasGenerating.current = false;\n }\n\n return isGenerating ? phrase : defaultPlaceholder;\n}\n","import type { KeyboardEvent } from 'react';\nimport { Input, IconButton, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport type { AIInputProps } from './types';\nimport { useAIGeneration } from './useAIGeneration';\nimport { useGeneratingPlaceholder } from './useGeneratingPlaceholder';\n\nexport interface AITextInputProps extends AIInputProps {}\n\n/**\n * An AI-powered controlled text input component that uses the Grafana Assistant engine to generate content.\n * Features an integrated send button as well as a gradient border animation while generating.\n */\nexport function AITextInput({\n value,\n onChange,\n placeholder,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n className,\n 'data-testid': dataTestId,\n}: AITextInputProps) {\n const { displayValue, isSendDisabled, handleGenerate, isGenerating, error } = useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled,\n autoGenerate,\n streaming,\n getUserPrompt,\n });\n const styles = useStyles2(getStyles);\n const activePlaceholder = useGeneratingPlaceholder(isGenerating, placeholder ?? 'Ask AI to generate...');\n\n const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n // Cmd/Ctrl + Enter to send\n if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {\n e.preventDefault();\n handleGenerate();\n }\n };\n\n const addonAfter = (\n <IconButton\n name=\"ai-sparkle\"\n onClick={handleGenerate}\n disabled={isSendDisabled}\n tooltip={isSendDisabled ? 'Enter text to generate' : 'Generate with AI'}\n data-testid={dataTestId ? `${dataTestId}-send` : undefined}\n />\n );\n\n return (\n <div className={cx(styles.wrapper, { [styles.animatedWrapper]: isGenerating }, className)} data-testid={dataTestId}>\n <Input\n value={displayValue}\n onKeyDown={handleKeyDown}\n onChange={(e) => onChange(e.currentTarget.value)}\n placeholder={activePlaceholder}\n disabled={disabled || isGenerating}\n suffix={addonAfter}\n invalid={!!error}\n data-testid={dataTestId ? `${dataTestId}-input` : undefined}\n />\n </div>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const borderAnimation = keyframes({\n label: 'ai-input-border-animation',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n return {\n wrapper: css({\n label: 'ai-text-input-wrapper',\n position: 'relative',\n border: '1px solid transparent',\n borderRadius: theme.shape.radius.default,\n cornerShape: 'squircle',\n }),\n animatedWrapper: css({\n label: 'ai-text-input-animated',\n border: '1px solid transparent',\n // Set initial backgroundImage with both gradients so Chrome can animate properly\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n animation: `${borderAnimation} 2s linear infinite`,\n '& input': {\n // Remove the default border from the input when animated wrapper is active\n border: 'none !important',\n },\n }),\n };\n};\n","import type { KeyboardEvent } from 'react';\nimport { TextArea, IconButton, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport type { AIInputProps } from './types';\nimport { useAIGeneration } from './useAIGeneration';\nimport { useGeneratingPlaceholder } from './useGeneratingPlaceholder';\n\nexport interface AITextAreaProps extends AIInputProps {\n /** Number of rows for the textarea */\n rows?: number;\n}\n\n/**\n * An AI-powered controlled textarea component that uses the Grafana Assistant engine to generate content.\n * Features an integrated send button as well as a gradient border animation while generating.\n */\nexport function AITextArea({\n value,\n onChange,\n placeholder,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n rows = 4,\n className,\n 'data-testid': dataTestId,\n}: AITextAreaProps) {\n const { displayValue, isSendDisabled, handleGenerate, isGenerating, error } = useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled,\n autoGenerate,\n streaming,\n getUserPrompt,\n });\n const styles = useStyles2(getStyles);\n const activePlaceholder = useGeneratingPlaceholder(\n isGenerating,\n placeholder ?? 'Ask AI to generate... (Cmd/Ctrl+Enter to send)'\n );\n const effectiveRows = Math.max(rows, 2);\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n // Cmd/Ctrl + Enter to send\n if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {\n e.preventDefault();\n handleGenerate();\n }\n };\n\n return (\n <div\n className={cx(styles.textareaWrapper, { [styles.animatedWrapper]: isGenerating }, className)}\n data-testid={dataTestId}\n >\n <TextArea\n value={displayValue}\n onKeyDown={handleKeyDown}\n onChange={(e) => onChange(e.currentTarget.value)}\n placeholder={activePlaceholder}\n disabled={disabled || isGenerating}\n rows={effectiveRows}\n className={styles.textarea}\n invalid={!!error}\n data-testid={dataTestId ? `${dataTestId}-textarea` : undefined}\n />\n <IconButton\n name=\"ai-sparkle\"\n onClick={handleGenerate}\n disabled={isSendDisabled}\n className={styles.sendButton}\n aria-label=\"Generate with AI\"\n tooltip={isSendDisabled ? 'Enter text to generate' : 'Generate with AI (Cmd/Ctrl+Enter)'}\n data-testid={dataTestId ? `${dataTestId}-send` : undefined}\n />\n </div>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const borderAnimation = keyframes({\n label: 'ai-textarea-border-animation',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n return {\n textareaWrapper: css({\n label: 'ai-textarea-wrapper',\n position: 'relative',\n border: '1px solid transparent',\n borderRadius: theme.shape.radius.default,\n cornerShape: 'squircle',\n }),\n animatedWrapper: css({\n label: 'ai-textarea-animated',\n border: '1px solid transparent',\n // Set initial backgroundImage with both gradients so Chrome can animate properly\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n animation: `${borderAnimation} 2s linear infinite`,\n '& textarea': {\n // Remove the default border from the textarea when animated wrapper is active\n border: 'none !important',\n },\n }),\n textarea: css({\n label: 'ai-textarea',\n // ensures the text does not \"underflow\" the send button\n paddingRight: theme.spacing(4),\n // Keep at least a 2-row visual height even if outer styles try to shrink the control\n minHeight: theme.spacing(6),\n '& textarea': {\n minHeight: theme.spacing(6),\n },\n // Hide scrollbar\n scrollbarWidth: 'none', // Firefox\n '&::-webkit-scrollbar': {\n display: 'none', // Chrome, Safari, Edge\n },\n }),\n sendButton: css({\n label: 'ai-textarea-send',\n position: 'absolute',\n right: theme.spacing(1),\n top: theme.spacing(1),\n }),\n };\n};\n","import { CoreApp, type DataSourceApi, type DataSourceInstanceSettings } from '@grafana/data';\nimport type { DataQuery, DataSourceJsonData } from '@grafana/schema';\nimport type { ComponentSize } from '@grafana/ui';\nimport { createAssistantContextItem } from '../../context';\nimport { useAssistant } from '../../hook';\nimport { OpenAssistantButtonView } from './OpenAssistantButton';\n\nfunction queryIsEmpty(query: DataQuery): boolean {\n const dataQueryProps = ['refId', 'hide', 'key', 'queryType', 'datasource'];\n\n for (const key in query) {\n if (key === 'label') {\n continue;\n }\n if (!dataQueryProps.includes(key)) {\n return false;\n }\n }\n\n return true;\n}\n\nexport interface QueryWithAssistantButtonProps<TQuery extends DataQuery = DataQuery> {\n size?: ComponentSize;\n currentQuery: TQuery;\n queries: TQuery[];\n dataSourceInstanceSettings: DataSourceInstanceSettings;\n app?: CoreApp;\n datasourceApi: DataSourceApi<TQuery, DataSourceJsonData, {}> | null;\n title?: string;\n}\n\nexport function QueryWithAssistantButton<TQuery extends DataQuery = DataQuery>({\n size,\n currentQuery,\n queries,\n dataSourceInstanceSettings,\n app,\n datasourceApi,\n title = 'Query with Assistant',\n}: QueryWithAssistantButtonProps<TQuery>) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n\n const origin = `grafana/query-editor/${dataSourceInstanceSettings.type}/${app ?? CoreApp.Unknown ?? 'unknown'}`;\n\n const hasCurrentQuery = !queryIsEmpty(currentQuery);\n const otherQueries = queries.filter((q) => q.refId !== currentQuery.refId && !queryIsEmpty(q));\n\n const context = [\n createAssistantContextItem('datasource', {\n datasourceUid: dataSourceInstanceSettings.uid,\n }),\n ];\n\n if (hasCurrentQuery) {\n context.push(\n createAssistantContextItem('structured', {\n title: 'Current query',\n data: currentQuery,\n })\n );\n }\n\n if (otherQueries.length > 0) {\n context.push(\n createAssistantContextItem('structured', {\n title: 'Other queries',\n data: {\n queries: otherQueries,\n },\n })\n );\n }\n\n const queryDisplayText =\n hasCurrentQuery && datasourceApi?.getQueryDisplayText ? datasourceApi.getQueryDisplayText(currentQuery) : null;\n\n const isUpdating = !!queryDisplayText;\n const actionText = isUpdating\n ? 'Help me update the current query to answer my questions and provide the insights I need.'\n : 'Help me create a new query to answer my questions and provide the insights I need.';\n\n const codeBlockLines: string[] = [];\n\n if (queryDisplayText) {\n codeBlockLines.push(`Current query: ${queryDisplayText}`);\n }\n\n codeBlockLines.push(`Selected data source: ${dataSourceInstanceSettings.name}`);\n\n const actionableSentence = isUpdating\n ? 'Please describe what you want to change or improve in this query.'\n : \"Please describe what you want to query and what insights you're looking for.\";\n\n const prompt = [actionText, '```', ...codeBlockLines, '```', actionableSentence].join('\\n');\n\n return (\n <OpenAssistantButtonView\n prompt={prompt}\n origin={origin}\n context={context}\n autoSend={false}\n title={title}\n size={size}\n openAssistant={openAssistant}\n />\n );\n}\n","import { useState, useRef, useEffect } from 'react';\n\nconst DEFAULT_EXAMPLE_PROMPTS = [\n 'What does this panel show?',\n 'Explain the trend in this data',\n 'Why is there a spike?',\n 'Add a threshold at 80%',\n 'Change the legend to table mode',\n];\n\nexport { DEFAULT_EXAMPLE_PROMPTS };\n\nexport function useAnimatedPlaceholder(staticPlaceholder: string, prompts: string[], hasUserInput: boolean): string {\n const [display, setDisplay] = useState('');\n const indexRef = useRef(0);\n const charRef = useRef(0);\n const phaseRef = useRef<'typing' | 'pause' | 'erasing'>('typing');\n\n useEffect(() => {\n indexRef.current = 0;\n charRef.current = 0;\n phaseRef.current = 'typing';\n setDisplay('');\n\n if (hasUserInput || prompts.length === 0) {\n return;\n }\n\n const tick = () => {\n const currentPrompt = prompts[indexRef.current];\n\n if (phaseRef.current === 'typing') {\n charRef.current++;\n setDisplay(currentPrompt.slice(0, charRef.current));\n if (charRef.current >= currentPrompt.length) {\n phaseRef.current = 'pause';\n }\n } else if (phaseRef.current === 'pause') {\n phaseRef.current = 'erasing';\n } else if (phaseRef.current === 'erasing') {\n charRef.current--;\n setDisplay(currentPrompt.slice(0, charRef.current));\n if (charRef.current <= 0) {\n phaseRef.current = 'typing';\n indexRef.current = (indexRef.current + 1) % prompts.length;\n }\n }\n };\n\n const getDelay = () => {\n if (phaseRef.current === 'pause') {\n return 800;\n }\n if (phaseRef.current === 'erasing') {\n return 15;\n }\n return 30 + Math.random() * 20;\n };\n\n let timeoutId: ReturnType<typeof setTimeout>;\n const schedule = () => {\n timeoutId = setTimeout(() => {\n tick();\n schedule();\n }, getDelay());\n };\n schedule();\n\n return () => clearTimeout(timeoutId);\n }, [hasUserInput, prompts]);\n\n if (hasUserInput || prompts.length === 0) {\n return staticPlaceholder;\n }\n\n return display;\n}\n","import { type KeyboardEvent, useRef, useState, useEffect, useCallback } from 'react';\nimport { IconButton, Input, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { reportInteraction } from '@grafana/runtime';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport { useAnimatedPlaceholder, DEFAULT_EXAMPLE_PROMPTS } from './useAnimatedPlaceholder';\n\nexport interface AssistantPromptCardProps {\n /** Origin of the request for analytics tracking. Should be a structured string using forward slashes. */\n origin: string;\n /** Context items passed to the assistant on submit. Created with `createAssistantContextItem`. */\n context?: ChatContextItem[];\n /** Assistant mode (e.g. 'dashboarding'). Defaults to 'assistant'. */\n mode?: string;\n /** Placeholder text for the input. */\n placeholder?: string;\n /** Example prompts to cycle through as animated placeholder text. Pass an empty array to disable. */\n examplePrompts?: string[];\n /** Called when the card should close (Escape key, close button). */\n onClose?: () => void;\n /** Called after a prompt is submitted, receives the prompt string. */\n onSubmit?: (prompt: string) => void;\n /** Called when the user clicks the card body. */\n onClick?: () => void;\n /** Whether the card border is animated. Defaults to true. */\n animated?: boolean;\n /** Extra CSS class for the root element. */\n className?: string;\n}\n\n/**\n * A prompt card component that opens the Grafana Assistant with a user-typed prompt and context.\n * Renders nothing if the assistant is not available. Positioning is the consumer's responsibility.\n */\nexport function AssistantPromptCard(props: AssistantPromptCardProps) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <AssistantPromptCardView {...props} openAssistant={openAssistant} />;\n}\n\nexport interface AssistantPromptCardViewProps extends AssistantPromptCardProps {\n openAssistant: (props: OpenAssistantProps) => void;\n}\n\nexport function AssistantPromptCardView({\n origin,\n context,\n mode,\n placeholder,\n examplePrompts,\n animated = true,\n onClose,\n onSubmit,\n onClick,\n className,\n openAssistant,\n}: AssistantPromptCardViewProps) {\n const [prompt, setPrompt] = useState('');\n const inputRef = useRef<HTMLInputElement>(null);\n const styles = useStyles2(getStyles);\n const resolvedPrompts = examplePrompts ?? (placeholder !== undefined ? [] : DEFAULT_EXAMPLE_PROMPTS);\n const staticPlaceholder = placeholder ?? 'Ask Assistant...';\n const animatedPlaceholder = useAnimatedPlaceholder(staticPlaceholder, resolvedPrompts, prompt.length > 0);\n\n useEffect(() => {\n reportInteraction('grafana_assistant_app_prompt_card_displayed', { from: origin });\n }, [origin]);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: context is an intentional re-trigger to re-focus the input when the context changes\n useEffect(() => {\n const rafId = requestAnimationFrame(() => inputRef.current?.focus());\n return () => cancelAnimationFrame(rafId);\n }, [context]);\n\n const submit = useCallback(\n (text: string) => {\n const trimmed = text.trim();\n if (!trimmed) {\n return;\n }\n\n openAssistant({ prompt: trimmed, context, autoSend: true, origin, mode });\n onSubmit?.(trimmed);\n setPrompt('');\n },\n [openAssistant, context, origin, mode, onSubmit]\n );\n\n const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n submit(prompt);\n }\n\n if (e.key === 'Escape') {\n e.preventDefault();\n onClose?.();\n }\n };\n\n return (\n <div\n className={cx(animated ? styles.card : styles.cardStatic, className)}\n onClick={onClick}\n role=\"search\"\n aria-label={staticPlaceholder}\n data-testid=\"assistant-prompt-card\"\n >\n <div className={styles.inputRow}>\n <Input\n ref={inputRef}\n value={prompt}\n onChange={(e) => setPrompt(e.currentTarget.value)}\n onKeyDown={handleKeyDown}\n placeholder={animatedPlaceholder}\n suffix={\n <IconButton\n name=\"ai-sparkle\"\n onClick={() => submit(prompt)}\n disabled={!prompt.trim()}\n tooltip=\"Send to assistant\"\n aria-label=\"Send to assistant\"\n data-testid=\"assistant-prompt-card-send\"\n />\n }\n data-testid=\"assistant-prompt-card-input\"\n />\n </div>\n </div>\n );\n}\n\nfunction getGlowShadow(theme: GrafanaTheme2) {\n const baseShadow = theme.isDark ? 'rgb(17 18 23)' : 'rgb(245 245 245)';\n return [\n 'rgba(168, 85, 247, 0.25) 3px -1px 20px',\n 'rgba(249, 115, 22, 0.18) -5px 3px 40px',\n 'rgba(168, 85, 247, 0.12) 7px 4px 60px',\n `${baseShadow} 0 6px 30px`,\n ].join(', ');\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n const borderAnimation = keyframes({\n label: 'prompt-card-border',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const cardBase = {\n label: 'assistant-prompt-card',\n position: 'relative' as const,\n display: 'flex',\n flexDirection: 'column' as const,\n gap: theme.spacing(1),\n padding: theme.spacing(1),\n borderRadius: theme.shape.radius.lg,\n boxShadow: getGlowShadow(theme),\n };\n\n return {\n card: css({\n ...cardBase,\n cornerShape: 'squircle',\n background: backgroundColor,\n border: '1px solid transparent',\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n [theme.transitions.handleMotion('no-preference')]: {\n animation: `${borderAnimation} 2s linear infinite`,\n },\n }),\n cardStatic: css({\n ...cardBase,\n label: 'assistant-prompt-card-static',\n background: theme.colors.background.elevated,\n border: `1px solid ${theme.colors.border.weak}`,\n }),\n inputRow: css({\n label: 'prompt-card-input-row',\n display: 'flex',\n alignItems: 'center',\n gap: theme.spacing(0.5),\n '& input': {\n border: 'none !important',\n },\n }),\n };\n};\n","import { extractErrorMessage } from '../utils/errorHandling';\nimport type { InvestigationLensError, InvestigationLensErrorCode } from './types';\n\n/**\n * Request passed to the lens implementation registered by the Grafana\n * Assistant plugin.\n */\nexport interface InvestigationLensRequest {\n investigationId: string;\n /** JSON Schema describing the shape of the desired structured view. */\n schema: unknown;\n /** Attribution for the generation, e.g. `'grafana-irm/incident-detail'`. */\n origin: string;\n /** When true, bypass the cached result and regenerate. */\n refresh?: boolean;\n}\n\n/**\n * The lens implementation provided by the Grafana Assistant plugin. Resolves\n * with data conforming to the request's schema, or rejects with an error\n * carrying an {@link InvestigationLensErrorCode} `code` property.\n */\nexport type InvestigationLensImplementation = (request: InvestigationLensRequest) => Promise<unknown>;\nexport type InvestigationLensInitializer = () => Promise<void>;\n\nconst LENS_ERROR_CODES: readonly InvestigationLensErrorCode[] = [\n 'unavailable',\n 'no_report',\n 'permission_denied',\n 'validation_failed',\n 'llm_error',\n];\n\nfunction isLensErrorCode(value: unknown): value is InvestigationLensErrorCode {\n return typeof value === 'string' && (LENS_ERROR_CODES as readonly string[]).includes(value);\n}\n\n/**\n * Typed error the lens implementation throws to signal a specific failure\n * mode. Consumers should not need this class — the hook converts failures to\n * plain {@link InvestigationLensError} values. Conversion is structural (it\n * reads the `code` property), so it works even when the host plugin and the\n * assistant plugin bundle different copies of this package.\n */\nexport class InvestigationLensRequestError extends Error {\n constructor(\n public readonly code: InvestigationLensErrorCode,\n message: string\n ) {\n super(message);\n this.name = 'InvestigationLensRequestError';\n }\n}\n\n/** Converts any thrown value into a plain, typed lens error. */\nexport function toInvestigationLensError(err: unknown): InvestigationLensError {\n if (err && typeof err === 'object' && 'code' in err && isLensErrorCode(err.code)) {\n return { code: err.code, message: extractErrorMessage(err) };\n }\n return { code: 'llm_error', message: extractErrorMessage(err) };\n}\n\n// Extend window interface for global registry\ndeclare global {\n interface Window {\n [key: string]: any;\n }\n}\n\n// Global registry keys for cross-plugin sharing: all plugins (and all copies\n// of this package) must observe the same implementation, regardless of which\n// bundle loads first.\nconst GLOBAL_IMPLEMENTATION_KEY = '__grafanaAssistantLensImplementation__';\nconst GLOBAL_INITIALIZER_KEY = '__grafanaAssistantLensInitializer__';\nconst GLOBAL_INITIALIZATION_PROMISE_KEY = '__grafanaAssistantLensInitPromise__';\n\nexport function setInvestigationLensImplementation(fn: InvestigationLensImplementation): void {\n const existing = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (existing && existing !== fn) {\n console.warn('InvestigationLens implementation already set; ignoring subsequent call');\n return;\n }\n if (!existing) {\n window[GLOBAL_IMPLEMENTATION_KEY] = fn;\n }\n}\n\n/**\n * Register a lazy initializer that is called on first use. The Grafana\n * Assistant plugin registers this at bootstrap so the heavy implementation\n * loads only when a consumer actually requests a lens view.\n */\nexport function setInvestigationLensInitializer(fn: InvestigationLensInitializer): void {\n const existing = window[GLOBAL_INITIALIZER_KEY] as InvestigationLensInitializer | undefined;\n if (existing && existing !== fn) {\n console.warn('InvestigationLens initializer already set; ignoring subsequent call');\n return;\n }\n if (!existing) {\n window[GLOBAL_INITIALIZER_KEY] = fn;\n }\n}\n\n/**\n * Ensure the lens implementation is initialized, invoking the registered\n * initializer on first use. Throws an `unavailable` lens error when no\n * initializer is registered (assistant plugin missing or too old).\n */\nexport async function ensureInvestigationLensInitialized(): Promise<void> {\n const implementation = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (implementation) {\n return;\n }\n\n const initializer = window[GLOBAL_INITIALIZER_KEY] as InvestigationLensInitializer | undefined;\n if (!initializer) {\n throw new InvestigationLensRequestError(\n 'unavailable',\n 'Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.'\n );\n }\n\n // If initialization is in progress, wait for it\n const existingPromise = window[GLOBAL_INITIALIZATION_PROMISE_KEY] as Promise<void> | null | undefined;\n if (existingPromise) {\n return existingPromise;\n }\n\n const initPromise = (async () => {\n try {\n await initializer();\n } catch (err) {\n // Reset on error so retry is possible\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = null;\n throw err;\n }\n })();\n\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = initPromise;\n return initPromise;\n}\n\nexport function getInvestigationLensImplementation(): InvestigationLensImplementation {\n const implementation = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (!implementation) {\n throw new InvestigationLensRequestError(\n 'unavailable',\n 'Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.'\n );\n }\n return implementation;\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { FromSchema, JSONSchema } from 'json-schema-to-ts';\n\nimport {\n ensureInvestigationLensInitialized,\n getInvestigationLensImplementation,\n toInvestigationLensError,\n} from './investigationLens';\nimport type {\n InvestigationLensState,\n UseInvestigationThroughLensOptions,\n UseInvestigationThroughLensResult,\n} from './types';\n\n/**\n * Derives a structured, LLM-generated view of an investigation's report,\n * shaped by a caller-provided JSON Schema. Declarative: generation runs on\n * mount and whenever the schema or investigation changes; results are cached\n * by the Grafana Assistant plugin per (investigation, schema, report\n * content), so remounts don't regenerate for an unchanged report.\n *\n * Field `description`s are per-field instructions to the model — that is the\n * steering mechanism. Deterministic facts (ids, titles, statuses, timestamps,\n * links) are provided to the model verbatim and copied through rather than\n * generated, so reserve schema fields for genuine synthesis from the report.\n *\n * Declare the schema with `as const` to get a fully typed `data` inferred\n * from the schema (via `json-schema-to-ts`):\n *\n * @example\n * ```typescript\n * const schema = {\n * type: 'object',\n * properties: {\n * headline: {\n * type: 'string',\n * description: 'One sentence describing the incident for an executive audience, max 80 characters.',\n * },\n * followUps: {\n * type: 'array',\n * description: 'Concrete follow-up actions to prevent recurrence.',\n * items: {\n * type: 'object',\n * properties: {\n * action: { type: 'string' },\n * urgency: { type: 'string', enum: ['now', 'this-week', 'backlog'] },\n * },\n * required: ['action', 'urgency'],\n * additionalProperties: false,\n * },\n * },\n * },\n * required: ['headline', 'followUps'],\n * additionalProperties: false,\n * } as const;\n *\n * function IncidentReview({ investigationId }: { investigationId: string }) {\n * const lens = useInvestigationThroughLens(schema, investigationId, {\n * origin: 'grafana-irm/incident-review',\n * });\n *\n * if (lens.status === 'loading') return <Spinner />;\n * if (lens.status === 'error') return <span>{lens.error.message}</span>;\n * // lens.data.followUps[0].urgency is 'now' | 'this-week' | 'backlog'\n * return <h3>{lens.data.headline}</h3>;\n * }\n * ```\n *\n * Requires the Grafana Assistant plugin; when it is missing or outdated the\n * hook resolves to an `error` state with code `unavailable` — it never throws\n * into the host's render.\n *\n * Note on `enabled` gating: re-enabling serves cached results by default. If\n * the report may have changed while the hook was disabled — e.g. `enabled`\n * gates on the report streaming — set `refreshOnEnable: true` so the fetch\n * triggered by the false → true transition bypasses the caches once.\n */\nexport function useInvestigationThroughLens<S extends JSONSchema, T = FromSchema<S>>(\n schema: S,\n investigationId: string,\n options: UseInvestigationThroughLensOptions\n): UseInvestigationThroughLensResult<T> {\n const { origin, enabled = true, refreshOnEnable = false } = options;\n const [state, setState] = useState<InvestigationLensState<T>>({ status: 'loading' });\n\n // Key generation on the schema's content, not its identity: consumers\n // typically declare the schema inline, so the object is recreated every\n // render even though it never changes.\n const schemaJson = useMemo(() => JSON.stringify(schema), [schema]);\n\n // refresh() bumps the generation to re-run generation with a cache bypass.\n // The bypass is one-shot: the ref records which generation already consumed\n // it, so a later run triggered by a schema/investigation change (same\n // generation, different deps) does not inherit `refresh: true`.\n const [generation, setGeneration] = useState({ id: 0, bypassCache: false });\n const consumedGenerationRef = useRef(0);\n\n // For refreshOnEnable: tracks whether the previous effect run was enabled,\n // so the run triggered by a false → true transition bypasses caches exactly\n // once. Initialized to the mount-time value so a first mount with\n // `enabled: true` takes the normal cached path.\n const wasEnabledRef = useRef(enabled);\n\n const refresh = useCallback(() => {\n setGeneration((g) => ({ id: g.id + 1, bypassCache: true }));\n }, []);\n\n useEffect(() => {\n const wasEnabled = wasEnabledRef.current;\n wasEnabledRef.current = enabled;\n\n if (!enabled) {\n setState({ status: 'loading' });\n return;\n }\n\n let cancelled = false;\n const bypassFromRefresh = generation.bypassCache && consumedGenerationRef.current !== generation.id;\n consumedGenerationRef.current = generation.id;\n const bypassCache = bypassFromRefresh || (refreshOnEnable && !wasEnabled);\n setState({ status: 'loading' });\n\n (async () => {\n try {\n await ensureInvestigationLensInitialized();\n const implementation = getInvestigationLensImplementation();\n const data = await implementation({\n investigationId,\n schema: JSON.parse(schemaJson),\n origin,\n refresh: bypassCache,\n });\n if (!cancelled) {\n setState({ status: 'success', data: data as T });\n }\n } catch (err) {\n if (!cancelled) {\n setState({ status: 'error', error: toInvestigationLensError(err) });\n }\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [schemaJson, investigationId, origin, enabled, refreshOnEnable, generation]);\n\n return { ...state, refresh };\n}\n","/**\n * Lightweight semantic version comparison utility.\n * Replaces semver library to reduce bundle size.\n *\n * Supports standard semver format: major.minor.patch[-prerelease][+build]\n * Pre-release versions are considered lower than release versions.\n * Build metadata is ignored for comparison purposes.\n */\n\ninterface ParsedVersion {\n major: number;\n minor: number;\n patch: number;\n prerelease?: string;\n}\n\n/**\n * Parses a semantic version string into its components.\n * @param version - Version string (e.g., \"1.2.3\", \"0.0.2-ga\", \"1.2.3+build\")\n * @returns Parsed version object or null if invalid\n */\nfunction parseVersion(version: string): ParsedVersion | null {\n // Remove build metadata (everything after +)\n const withoutBuild = version.split('+')[0];\n\n // Split into version and prerelease parts\n const parts = withoutBuild.split('-');\n const versionPart = parts[0];\n const prerelease = parts.length > 1 ? parts.slice(1).join('-') : undefined;\n\n // Parse major.minor.patch\n const numbers = versionPart.split('.').map(Number);\n if (numbers.length !== 3 || numbers.some(isNaN)) {\n return null;\n }\n\n return {\n major: numbers[0],\n minor: numbers[1],\n patch: numbers[2],\n prerelease,\n };\n}\n\n/**\n * Compares two semantic versions.\n * @param v1 - First version string\n * @param v2 - Second version string\n * @returns -1 if v1 < v2, 0 if v1 === v2, 1 if v1 > v2, or null if either version is invalid\n */\nfunction compareVersions(v1: string, v2: string): number | null {\n const parsed1 = parseVersion(v1);\n const parsed2 = parseVersion(v2);\n\n if (!parsed1 || !parsed2) {\n return null;\n }\n\n // Compare major version\n if (parsed1.major !== parsed2.major) {\n return parsed1.major > parsed2.major ? 1 : -1;\n }\n\n // Compare minor version\n if (parsed1.minor !== parsed2.minor) {\n return parsed1.minor > parsed2.minor ? 1 : -1;\n }\n\n // Compare patch version\n if (parsed1.patch !== parsed2.patch) {\n return parsed1.patch > parsed2.patch ? 1 : -1;\n }\n\n // If both have prerelease, compare lexicographically\n // If only one has prerelease, it's considered lower\n if (parsed1.prerelease && parsed2.prerelease) {\n if (parsed1.prerelease === parsed2.prerelease) {\n return 0;\n }\n return parsed1.prerelease > parsed2.prerelease ? 1 : -1;\n }\n\n if (parsed1.prerelease && !parsed2.prerelease) {\n return -1; // v1 has prerelease, v2 doesn't, so v1 < v2\n }\n\n if (!parsed1.prerelease && parsed2.prerelease) {\n return 1; // v1 doesn't have prerelease, v2 does, so v1 > v2\n }\n\n return 0; // Both are release versions with same major.minor.patch\n}\n\n/**\n * Checks if version v1 is greater than version v2.\n * @param v1 - First version string\n * @param v2 - Second version string\n * @returns true if v1 > v2, false otherwise (including if either version is invalid)\n */\nexport function isVersionGreaterThan(v1: string, v2: string): boolean {\n const result = compareVersions(v1, v2);\n return result === 1;\n}\n","import { getBackendSrv } from '@grafana/runtime';\nimport { lastValueFrom } from 'rxjs';\nimport { useState, useEffect } from 'react';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\nimport { isVersionGreaterThan } from './versionCompare';\nimport type { components } from './settings.gen';\n\n/**\n * The type of terms that apply to a tenant.\n * - 'msa': Master Service Agreement - only requires acceptance, no version checking\n * - 'termsAndConditions': Full terms and conditions - requires acceptance AND version checking\n */\nexport type TermsType = components['schemas']['TermsAndConditionsResponse']['termsType'];\n\n/**\n * Internal result type for fetching terms data.\n */\ninterface TermsCheckResult {\n accepted: boolean;\n termsType: TermsType;\n}\n\n/**\n * Event name that is dispatched when terms and conditions are accepted.\n * Other components can listen to this event to refresh their UI.\n */\nexport const TERMS_AND_CONDITIONS_REFRESH_EVENT = 'grafana-assistant-terms-and-conditions-refresh';\n\n/**\n * Internal function that fetches and evaluates terms data.\n * Returns both the acceptance status and the terms type.\n */\nasync function fetchTermsData(): Promise<TermsCheckResult> {\n const backendSrv = getBackendSrv();\n // No appSubUrl prefix: BackendSrv strips the leading `/` so Grafana's\n // `<base href>` adds the subpath (see grafana-assistant-app/issues/6109).\n const apiUrl = `/api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v1/settings/terms`;\n\n const response = await lastValueFrom(\n backendSrv.fetch({\n url: apiUrl,\n method: 'GET',\n showErrorAlert: false,\n })\n );\n\n // The API returns { status: \"success\", data: { ... } }, so we need to access response.data.data\n const responseBody = response.data as { data: components['schemas']['TermsAndConditionsResponse'] };\n const termsData = responseBody.data;\n\n const termsAccepted = termsData.acceptedTermsAndConditions ?? false;\n const acceptedVersion = termsData.acceptedVersion;\n const currentVersion = termsData.version;\n const termsType = termsData.termsType;\n\n // For MSA, we only check if terms are accepted\n if (termsType === 'msa') {\n return { accepted: termsAccepted, termsType };\n }\n\n // Check if terms are not accepted, or if no version was recorded or current version is missing\n if (!termsAccepted || !acceptedVersion || !currentVersion) {\n return { accepted: false, termsType };\n }\n\n // Check if the current version is newer than the accepted version\n const needsAcceptance = isVersionGreaterThan(currentVersion, acceptedVersion);\n return { accepted: termsAccepted && !needsAcceptance, termsType };\n}\n\n/**\n * Checks whether terms and conditions are accepted and up-to-date.\n * This function verifies that:\n * 1. Terms have been accepted\n * 2. The accepted version matches or exceeds the current version\n *\n * @returns A promise that resolves to `true` if terms are accepted and up-to-date, `false` otherwise\n * @throws Error if the API call fails\n *\n * @example\n * ```typescript\n * import { checkTerms } from '@grafana/assistant';\n *\n * const accepted = await checkTerms();\n * if (!accepted) {\n * // Show terms acceptance UI\n * console.log('Terms need to be accepted');\n * }\n * ```\n */\nexport async function checkTerms(): Promise<boolean> {\n try {\n const result = await fetchTermsData();\n return result.accepted;\n } catch (error) {\n // If API call fails, throw the error so callers can handle it\n throw new Error(`Failed to check terms requirements: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\n * React hook to check terms and conditions acceptance status.\n * Automatically fetches terms data on mount and re-fetches when terms change\n * (via TERMS_AND_CONDITIONS_REFRESH_EVENT).\n *\n * @returns An object containing whether terms are accepted, the terms type, loading state, and error state\n *\n * @example\n * ```typescript\n * import { useTerms } from '@grafana/assistant';\n *\n * function MyComponent() {\n * const { accepted, termsType, loading, error } = useTerms();\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return <div>Terms accepted</div>;\n * }\n * ```\n */\nexport function useTerms() {\n const [accepted, setAccepted] = useState<boolean>(false);\n const [termsType, setTermsType] = useState<TermsType | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n async function fetchTerms() {\n try {\n setLoading(true);\n setError(null);\n const result = await fetchTermsData();\n setAccepted(result.accepted);\n setTermsType(result.termsType);\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'Failed to check terms';\n setError(errorMessage);\n setAccepted(false);\n setTermsType(null);\n } finally {\n setLoading(false);\n }\n }\n\n fetchTerms();\n\n // Listen for the refresh event to re-fetch when terms change\n const handleTermsRefresh = () => {\n fetchTerms();\n };\n document.addEventListener(TERMS_AND_CONDITIONS_REFRESH_EVENT, handleTermsRefresh);\n return () => {\n document.removeEventListener(TERMS_AND_CONDITIONS_REFRESH_EVENT, handleTermsRefresh);\n };\n }, []);\n\n return {\n accepted,\n termsType,\n loading,\n error,\n };\n}\n","import type { ToolInvokeOptions, ToolOutput, JSONSchema, JsonObject, InlineToolRunnable } from './types';\n\n/**\n * Creates a tool with the given implementation, schema, and metadata.\n * This is a zod-free implementation that accepts JSON Schema directly and a validation function.\n *\n * @param func The function implementation for the tool\n * @param options Tool configuration options\n * @returns A tool object that can be used in the agent\n */\nexport function createTool<T>(\n func: (input: T, options: ToolInvokeOptions) => Promise<ToolOutput>,\n options: {\n name: string;\n description: string;\n inputSchema: JSONSchema; // JSON Schema directly - no zod dependency!\n validate: (input: JsonObject) => T; // Validation function - replaces zod.parse()\n metadata?: {\n explainer?: (input?: T) => string;\n [key: string]: any;\n };\n verboseParsingErrors?: boolean;\n responseFormat?: 'content_and_artifact' | string;\n }\n): InlineToolRunnable {\n const { explainer, ...metadata } = options.metadata ?? {};\n const toolObj: InlineToolRunnable = {\n name: options.name,\n description: options.description,\n inputSchema: options.inputSchema,\n metadata: explainer\n ? {\n ...metadata,\n explainer: (input: JsonObject) => explainer(input as T),\n }\n : metadata,\n responseFormat: options.responseFormat,\n verboseParsingErrors: options.verboseParsingErrors,\n async invoke(input: JsonObject, invokeOptions: ToolInvokeOptions): Promise<ToolOutput> {\n try {\n if (invokeOptions.signal?.aborted) {\n throw new Error(`Tool ${options.name} execution was aborted`);\n }\n\n // Use the provided validation function instead of zod.parse()\n const parsedInput = options.validate(input);\n const functionPromise = func(parsedInput, invokeOptions);\n const promises = [functionPromise];\n\n if (invokeOptions.signal) {\n promises.push(\n new Promise((_, reject) => {\n invokeOptions.signal?.addEventListener(\n 'abort',\n () => {\n reject(new Error(`Tool ${options.name} execution was aborted`));\n },\n { once: true }\n );\n })\n );\n }\n\n // If we have a timeout, add a promise to handle it\n if (invokeOptions.timeout && invokeOptions.timeout > 0) {\n promises.push(\n new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error(`Tool ${options.name} execution timed out after ${invokeOptions.timeout}ms`));\n }, invokeOptions.timeout);\n })\n );\n }\n\n // Race the function promise against the abort and timeout promises\n return Promise.race(promises);\n } catch (error) {\n // Handle parsing errors and wrap them in ToolError\n if (options.verboseParsingErrors) {\n console.error(`Error invoking tool ${options.name}:`, error, input);\n }\n throw error;\n }\n },\n };\n\n return toolObj;\n}\n","import { getBackendSrv } from '@grafana/runtime';\nimport { lastValueFrom } from 'rxjs';\nimport { useState, useEffect, useCallback } from 'react';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\n\n/**\n * Event name dispatched when limits are updated via SSE.\n * Other components can listen to this event to get real-time updates.\n */\nexport const LIMITS_UPDATED_EVENT = 'grafana-assistant-limits-updated';\n\n/**\n * Detail payload for the LIMITS_UPDATED_EVENT custom event.\n */\nexport interface LimitsUpdatedEventDetail {\n count: number;\n limit: number;\n}\n\n/**\n * Result type for limits data.\n */\nexport interface LimitsData {\n /** Current prompt count for the month */\n count: number;\n /** Monthly prompt limit (0 = unlimited) */\n limit: number;\n /** Current month in YYYY-MM format */\n month: string;\n /** Whether the limit has been reached */\n isLimitReached: boolean;\n}\n\n/**\n * Internal function that fetches limits data from the API.\n */\nasync function fetchLimitsData(): Promise<LimitsData> {\n const backendSrv = getBackendSrv();\n // No appSubUrl prefix: BackendSrv strips the leading `/` so Grafana's\n // `<base href>` adds the subpath (see grafana-assistant-app/issues/6109).\n const apiUrl = `/api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v1/usage/limits/prompt`;\n\n const response = await lastValueFrom(\n backendSrv.fetch({\n url: apiUrl,\n method: 'GET',\n showErrorAlert: false,\n })\n );\n\n // The API returns { status: \"success\", data: { total, limit, month } }\n const responseBody = response.data as { data: { total: number; limit: number; month: string } };\n const limitsData = responseBody.data;\n\n const count = limitsData.total ?? 0;\n const limit = limitsData.limit ?? 0;\n const month = limitsData.month ?? '';\n\n return {\n count,\n limit,\n month,\n isLimitReached: limit > 0 && count >= limit,\n };\n}\n\n/**\n * Checks whether the user has reached their monthly prompt limit.\n *\n * @returns A promise that resolves to `true` if limits are reached, `false` otherwise\n * @throws Error if the API call fails\n *\n * @example\n * ```typescript\n * import { checkLimits } from '@grafana/assistant';\n *\n * const data = await checkLimits();\n * if (data.isLimitReached) {\n * console.log('Monthly limit reached');\n * }\n * ```\n */\nexport async function checkLimits(): Promise<LimitsData> {\n try {\n return await fetchLimitsData();\n } catch (error) {\n throw new Error(`Failed to check limits: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\n * React hook to check user prompt limits.\n * Automatically fetches limits data on mount and listens to real-time updates\n * via the LIMITS_UPDATED_EVENT custom event.\n *\n * @returns An object containing limit data, loading state, error state, and refetch function\n *\n * @example\n * ```typescript\n * import { useLimits } from '@grafana/assistant';\n *\n * function MyComponent() {\n * const { count, limit, isLimitReached, loading, error, refetch } = useLimits();\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * if (isLimitReached) return <div>Monthly limit reached ({count}/{limit})</div>;\n * return <div>Prompts used: {count}/{limit || 'unlimited'}</div>;\n * }\n * ```\n */\nexport function useLimits() {\n const [count, setCount] = useState<number>(0);\n const [limit, setLimit] = useState<number>(0);\n const [month, setMonth] = useState<string>('');\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchLimits = useCallback(async () => {\n try {\n setLoading(true);\n setError(null);\n const result = await fetchLimitsData();\n setCount(result.count);\n setLimit(result.limit);\n setMonth(result.month);\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'Failed to fetch limits';\n setError(errorMessage);\n setCount(0);\n setLimit(0);\n setMonth('');\n } finally {\n setLoading(false);\n }\n }, []);\n\n // Fetch on mount\n useEffect(() => {\n fetchLimits();\n }, [fetchLimits]);\n\n // Listen for real-time updates via custom event\n useEffect(() => {\n const handleLimitsUpdate = (event: Event) => {\n const customEvent = event as CustomEvent<LimitsUpdatedEventDetail>;\n if (customEvent.detail) {\n setCount(customEvent.detail.count);\n setLimit(customEvent.detail.limit);\n // Clear any previous error since we received valid data via SSE\n setError(null);\n }\n };\n\n window.addEventListener(LIMITS_UPDATED_EVENT, handleLimitsUpdate);\n\n return () => {\n window.removeEventListener(LIMITS_UPDATED_EVENT, handleLimitsUpdate);\n };\n }, []);\n\n // Calculate isLimitReached based on current state\n const isLimitReached = limit > 0 && count >= limit;\n\n return {\n count,\n limit,\n month,\n isLimitReached,\n loading,\n error,\n refetch: fetchLimits,\n };\n}\n","import { BusEventWithPayload } from '@grafana/data';\nimport { getAppEvents } from '@grafana/runtime';\n\nexport interface K6SetScriptContentPayload {\n scriptContent: string;\n}\n\n/**\n * Event published by grafana-assistant-app to inject a script into the currently open k6 editor.\n * The k6 app subscribes to this event and updates the editor content in place,\n * avoiding a full page navigation.\n *\n * @example\n * ```typescript\n * import { onK6SetScriptContent } from '@grafana/assistant';\n *\n * const unsubscribe = onK6SetScriptContent(({ scriptContent }) => {\n * editorRef.current?.setValue(scriptContent);\n * });\n *\n * // On unmount\n * unsubscribe();\n * ```\n */\nexport class K6SetScriptContentEvent extends BusEventWithPayload<K6SetScriptContentPayload> {\n static type = 'grafana-assistant:k6-set-script-content';\n}\n\n/**\n * Subscribe to k6 set-script-content events emitted by grafana-assistant-app.\n * Returns an unsubscribe function.\n */\nexport function onK6SetScriptContent(callback: (payload: K6SetScriptContentPayload) => void): () => void {\n const subscription = getAppEvents().subscribe(K6SetScriptContentEvent, (event) => {\n callback(event.payload);\n });\n return () => subscription.unsubscribe();\n}\n"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","hash","input","i","length","charCodeAt","toString","NodeData","constructor","params","text","this","id","type","bypassLimits","formatForLLM","codeElementIds","data","name","equals","other","StructuredNodeData","super","JSON","stringify","require","GLOBAL_REGISTRY_KEY","REGISTRY_CHANGE_EVENT","LEGACY_REGISTRY_UPDATE_EVENT","LEGACY_REGISTRY_REMOVE_EVENT","LEGACY_REGISTRY_SYNC_EVENT","getPageContextRegistry","window","setPageContextRegistry","newRegistry","skipLegacyEvents","dispatchEvent","CustomEvent","detail","registry","legacyBridgeInitialized","providePageContext","urlPattern","initialContext","pattern","RegExp","source","trim","console","warn","registration","generateRegistrationId","context","setContext","newContext","currentRegistry","index","findIndex","reg","unregister","filter","_","addEventListener","event","existingIndex","r","incomingRegistry","Array","isArray","currentIds","Set","map","newRegistrations","has","empty","useProvidePageContext","setContextRef","useRef","undefined","pendingUpdate","isModified","useEffect","current","contextToUse","useCallback","getActivePageContext","currentUrl","activeContext","matchesUrlPattern","push","usePageContext","options","allowQuestions","allowComponents","location","useLocationService","initialPathname","getLocation","pathname","pageContext","setPageContext","useState","currentPathnameRef","updateContext","handleRegistryChange","locationSub","getLocationObservable","subscribe","loc","unsubscribe","removeEventListener","filteredContext","item","node","prefix","Date","now","Math","random","slice","url","test","regexPattern","replace","ComponentNodeData","namespace","keys","components","join","prompt","usePageComponents","useMemo","allComponents","componentData","componentName","component","entries","provideComponents","flags","createAssistantContextItem","setter","newComponents","newPrompt","globalComponents","promptContext","DashboardNodeData","dashboardUid","dashboardTitle","folderUid","folderTitle","FolderNodeData","DatasourceNodeData","datasourceUid","datasourceType","datasourceName","img","uid","EntityNodeData","scope","env","site","Boolean","title","hidden","icon","entityType","properties","LabelNameNodeData","labelName","LabelValueNodeData","labelValue","operator","getDatasourceMeta","datasourceInstance","getDataSourceSrv","getInstanceSettings","meta","info","logos","small","defaultIcons","datasource","label_name","label_value","dashboard","dashboard_folder","unknown","structured","entity","skill","nodeData","error","createContextByType","defaultTitle","getTitleFromContextNode","getImgFromContextNode","navigable","selectable","occurrences","SkillNodeData","skillId","skillName","provideQuestions","initialQuestions","registrationId","convertQuestionsToContext","questions","question","setQuestions","newQuestions","useProvideQuestions","useQuestions","convertContextToQuestions","contextItems","CALLBACK_EXTENSION_POINT","newFunctionNamespace","functions","getExposeAssistantFunctionsConfig","namespaces","targets","fn","ASSISTANT_PLUGIN_ID","ASSISTANT_PLUGIN_TITLE","MAX_RETRY_ATTEMPTS","INITIAL_RETRY_DELAY","MAX_RETRY_DELAY","isAssistantAvailable","getObservablePluginLinks","defer","extensionPointId","pipe","links","some","link","pluginId","throwError","retry","count","delay","retryCount","errorMessage","message","toLowerCase","includes","delayMs","min","timer","catchError","of","OpenExtensionSidebarEvent","BusEventWithPayload","CloseExtensionSidebarEvent","BusEventBase","ToggleExtensionSidebarEvent","openAssistant","props","reportInteraction","from","origin","componentTitle","getAppEvents","publish","openExtensionSidebar","initialPrompt","initialAutoSend","autoSend","initialMode","mode","chatId","appendContext","closeAssistant","closeExtensionSidebar","toggleAssistant","toggleExtensionSidebar","useAssistant","available","setAvailable","sub","isAvailable","isLoading","OpenAssistantButton","OpenAssistantButtonView","size","iconOnlyButton","onClick","styles","useStyles2","getStyles","IconButton","variant","className","tooltip","Button","fill","button","theme","baseBackground","colors","secondary","main","elevatedBackground","emphasize","underlyingColor","background","canvas","outerRadius","shape","radius","default","innerRadius","gradientBorderLayer","content","position","inset","borderRadius","cornerShape","zIndex","pointerEvents","solidBackgroundLayer","transition","css","label","width","maxWidth","isolation","border","padding","spacing","defaultDropdownButtonWidths","sm","md","lg","OpenAssistantSplitButton","OpenAssistantSplitButtonView","menuItems","dropdownButtonWidth","hasMenuItems","resolvedDropdownButtonWidth","wrapperContent","wrapper","ButtonGroup","buttonGroup","cx","segmentButton","mainButtonSplit","mainButtonSolo","Dropdown","overlay","dropdownButton","style","minWidth","Tooltip","dividerColor","weak","display","gap","overflow","boxShadow","borderTopLeftRadius","borderBottomLeftRadius","borderTopRightRadius","borderBottomRightRadius","alignItems","justifyContent","margin","getBackgroundGradientColors","defaultGradientColors","matches","gradients","brandHorizontal","match","createBorderAnimation","backgroundColor","color1","color2","animationSteps","animationFrames","gradientColor1","gradientColor2","finalColor1","finalColor2","step","backgroundImage","GLOBAL_FACTORY_KEY","GLOBAL_INITIALIZER_KEY","GLOBAL_INITIALIZATION_PROMISE_KEY","setInlineAssistantFactory","existing","setInlineAssistantInitializer","async","ensureInlineAssistantInitialized","initializer","Error","existingPromise","initPromise","err","getInlineAssistantFactory","factory","nestedErrorKeys","getStringValue","trimmedValue","extractNestedErrorMessage","visited","directString","nestedErrorMessage","cause","fromEntries","add","errorRecord","nestedDataMessage","nestedMessage","status","statusText","nestedMessages","extractErrorMessage","extractedMessage","String","useInlineAssistant","isGenerating","setIsGenerating","setContent","setError","assistantRef","reset","cancel","generate","sendPrompt","agentName","agentId","systemPrompt","tools","onStart","onDelta","delta","prev","onComplete","onError","dispose","useAIGeneration","onChange","disabled","autoGenerate","streaming","getUserPrompt","hasAutoGenerated","valueBeforeGeneration","getUserPromptRef","displayValue","isSendDisabled","doGenerate","maybeAutoGenerateRef","handleGenerate","GENERATING_PHRASES","useGeneratingPlaceholder","defaultPlaceholder","phrase","setPhrase","wasGenerating","next","floor","AITextInput","placeholder","dataTestId","activePlaceholder","addonAfter","animatedWrapper","Input","onKeyDown","e","metaKey","ctrlKey","preventDefault","currentTarget","suffix","invalid","primary","borderAnimation","keyframes","backgroundOrigin","backgroundClip","animation","AITextArea","rows","effectiveRows","max","textareaWrapper","TextArea","textarea","sendButton","paddingRight","minHeight","scrollbarWidth","right","top","queryIsEmpty","query","dataQueryProps","QueryWithAssistantButton","currentQuery","queries","dataSourceInstanceSettings","app","datasourceApi","CoreApp","Unknown","hasCurrentQuery","otherQueries","q","refId","queryDisplayText","getQueryDisplayText","isUpdating","actionText","codeBlockLines","actionableSentence","DEFAULT_EXAMPLE_PROMPTS","AssistantPromptCard","AssistantPromptCardView","examplePrompts","animated","onClose","onSubmit","setPrompt","inputRef","staticPlaceholder","animatedPlaceholder","prompts","hasUserInput","setDisplay","indexRef","charRef","phaseRef","timeoutId","schedule","setTimeout","currentPrompt","tick","clearTimeout","useAnimatedPlaceholder","rafId","requestAnimationFrame","focus","cancelAnimationFrame","submit","trimmed","card","cardStatic","role","inputRow","ref","shiftKey","getGlowShadow","isDark","cardBase","flexDirection","transitions","handleMotion","elevated","LENS_ERROR_CODES","InvestigationLensRequestError","code","toInvestigationLensError","GLOBAL_IMPLEMENTATION_KEY","setInvestigationLensImplementation","setInvestigationLensInitializer","ensureInvestigationLensInitialized","getInvestigationLensImplementation","implementation","useInvestigationThroughLens","schema","investigationId","enabled","refreshOnEnable","state","setState","schemaJson","generation","setGeneration","bypassCache","consumedGenerationRef","wasEnabledRef","refresh","g","wasEnabled","cancelled","bypassFromRefresh","parse","parseVersion","version","parts","split","versionPart","prerelease","numbers","Number","isNaN","major","minor","patch","TERMS_AND_CONDITIONS_REFRESH_EVENT","fetchTermsData","backendSrv","getBackendSrv","apiUrl","termsData","lastValueFrom","fetch","method","showErrorAlert","termsAccepted","acceptedTermsAndConditions","acceptedVersion","currentVersion","termsType","accepted","needsAcceptance","v1","v2","parsed1","parsed2","compareVersions","checkTerms","useTerms","setAccepted","setTermsType","loading","setLoading","fetchTerms","result","handleTermsRefresh","document","createTool","func","explainer","metadata","toolObj","description","inputSchema","responseFormat","verboseParsingErrors","invoke","invokeOptions","signal","aborted","parsedInput","validate","promises","Promise","reject","once","timeout","race","LIMITS_UPDATED_EVENT","fetchLimitsData","limitsData","total","limit","month","isLimitReached","checkLimits","useLimits","setCount","setLimit","setMonth","fetchLimits","handleLimitsUpdate","customEvent","refetch","K6SetScriptContentEvent","onK6SetScriptContent","callback","subscription","payload"],"sourceRoot":""}
1
+ {"version":3,"file":"index.js","mappings":"mBACA,IAAIA,EAAsB,CCA1BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3EH,EAAwB,CAACS,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFV,EAAyBC,IACH,oBAAXa,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeL,EAASa,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeL,EAAS,aAAc,CAAEe,OAAO,M,KCDhD,SAASC,EAAKC,GACnB,IAAID,EAAO,KAEX,IAAK,IAAIE,EAAI,EAAGA,EAAID,EAAME,OAAQD,IAChCF,GAAQA,GAAQ,GAAKA,EAAOC,EAAMG,WAAWF,GAI/C,OAAQF,IAAS,GAAGK,SAAS,GAC/B,C,6mDCuBO,MAAMC,EAKX,WAAAC,CAAmBC,GAAA,KAAAA,OAAAA,EAHZ,KAAAC,KAAO,GAIZC,KAAKC,GAAKX,EAAKQ,EAAOG,IACtBD,KAAKE,KAAOJ,EAAOI,IACrB,CAGA,gBAAIC,G,MACF,OAA+B,QAAxB,EAAAH,KAAKF,OAAOK,oBAAY,QACjC,CAEA,YAAAC,CAAa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QtC,SAASka,GAAqBC,GACnC,MAAMC,GAAe,IAAA1Z,gBAAezJ,UAAUgjB,GAA0B5lB,IACtE8lB,EAAS9lB,EAAMgmB,WAEjB,MAAO,IAAMD,EAAajjB,aAC5B,CAZS,GAAAhG,KAAO,0CCZT,MAAMmpB,GAA4B,qCAyTlC,SAASC,GACdC,GAEA,MAAO,CACLhgB,MAAO,sBACPyd,YAAa,kGACbha,QAAS,CAACqc,IACVpc,GAAI,IAAMsc,EAEd,C","sources":["webpack://@grafana/assistant/webpack/bootstrap","webpack://@grafana/assistant/webpack/runtime/define property getters","webpack://@grafana/assistant/webpack/runtime/hasOwnProperty shorthand","webpack://@grafana/assistant/webpack/runtime/make namespace object","webpack://@grafana/assistant/./src/utils/hash.ts","webpack://@grafana/assistant/./src/context/base.ts","webpack://@grafana/assistant/external commonjs2 \"@grafana/runtime\"","webpack://@grafana/assistant/external commonjs2 \"react\"","webpack://@grafana/assistant/./src/context/page.ts","webpack://@grafana/assistant/./src/context/component.ts","webpack://@grafana/assistant/./src/context/dashboard.ts","webpack://@grafana/assistant/./src/context/datasource.ts","webpack://@grafana/assistant/./src/context/entity.ts","webpack://@grafana/assistant/./src/context/label.ts","webpack://@grafana/assistant/./src/context/factory.ts","webpack://@grafana/assistant/./src/context/chat.ts","webpack://@grafana/assistant/./src/context/skill.ts","webpack://@grafana/assistant/./src/context/questions.ts","webpack://@grafana/assistant/./src/functions.ts","webpack://@grafana/assistant/external commonjs2 \"rxjs\"","webpack://@grafana/assistant/./src/plugin.ts","webpack://@grafana/assistant/external commonjs2 \"@grafana/data\"","webpack://@grafana/assistant/./src/sidebar.ts","webpack://@grafana/assistant/./src/hook.ts","webpack://@grafana/assistant/external commonjs2 \"react/jsx-runtime\"","webpack://@grafana/assistant/external commonjs2 \"@grafana/ui\"","webpack://@grafana/assistant/external commonjs2 \"@emotion/css\"","webpack://@grafana/assistant/./src/components/button/OpenAssistantButton.tsx","webpack://@grafana/assistant/./src/components/button/OpenAssistantSplitButton.tsx","webpack://@grafana/assistant/./src/utils/theme.ts","webpack://@grafana/assistant/./src/inline/inlineAssistant.ts","webpack://@grafana/assistant/./src/utils/errorHandling.ts","webpack://@grafana/assistant/./src/inline/useInlineAssistant.ts","webpack://@grafana/assistant/./src/components/input/useAIGeneration.ts","webpack://@grafana/assistant/./src/components/input/useGeneratingPlaceholder.ts","webpack://@grafana/assistant/./src/components/input/AITextInput.tsx","webpack://@grafana/assistant/./src/components/input/AITextArea.tsx","webpack://@grafana/assistant/./src/components/button/QueryWithAssistantButton.tsx","webpack://@grafana/assistant/./src/components/prompt-card/useAnimatedPlaceholder.ts","webpack://@grafana/assistant/./src/components/prompt-card/AssistantPromptCard.tsx","webpack://@grafana/assistant/./src/lens/investigationLens.ts","webpack://@grafana/assistant/./src/lens/useInvestigationThroughLens.ts","webpack://@grafana/assistant/./src/terms/versionCompare.ts","webpack://@grafana/assistant/./src/terms/index.ts","webpack://@grafana/assistant/./src/tools/toolFactory.ts","webpack://@grafana/assistant/./src/limits/index.ts","webpack://@grafana/assistant/./src/k6.ts","webpack://@grafana/assistant/./src/extension/extension.ts"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Simple hash function that generates a deterministic hash for a given input string.\n * Uses the djb2 algorithm for simplicity and good distribution.\n */\nexport function hash(input: string): string {\n let hash = 5381;\n\n for (let i = 0; i < input.length; i++) {\n hash = (hash << 5) + hash + input.charCodeAt(i);\n }\n\n // Convert to positive hex string\n return (hash >>> 0).toString(16);\n}\n","import type { IconName } from '@grafana/ui';\nimport type { ItemDataType, ContextItemData, UnknownItemData } from './types';\nimport { hash } from '../utils/hash';\n\nexport interface BaseParams {\n title?: string;\n // If true, the context item will not be shown in the context pills\n hidden?: boolean;\n // Image to display, if not selected, we fallback to icon\n img?: string;\n // Icon to display, if img is provided, icon is ignored\n icon?: IconName;\n /**\n * When true, bypasses size limits for fixed-size content that doesn't need truncation.\n *\n * Set `bypassLimits: true` for fixed-size content like:\n * - Static instructions or prompts\n * - Configuration that doesn't change\n * - Small, bounded metadata\n *\n * Keep `bypassLimits: false` (default) for variable-size content like:\n * - Query results, data tables, graphs\n * - User-generated content, logs\n * - Any content that could grow unexpectedly large\n *\n * @default false\n */\n bypassLimits?: boolean;\n}\n\nexport interface NodeDataParams extends BaseParams {\n id: string;\n type: ItemDataType;\n text?: string;\n}\n\nexport class NodeData {\n public id: string;\n public text = '';\n public type: ItemDataType;\n\n constructor(public params: NodeDataParams) {\n this.id = hash(params.id);\n this.type = params.type;\n }\n\n /** Whether size limits should be bypassed for this context item. Defaults to false. */\n get bypassLimits(): boolean {\n return this.params.bypassLimits ?? false;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.params.text ?? '',\n text: this.params.text ?? '',\n } satisfies UnknownItemData,\n };\n }\n\n equals(other: unknown): boolean {\n if (!(other instanceof NodeData)) {\n return false;\n }\n return this.id === other.id && this.type === other.type;\n }\n}\n\nexport interface StructuredNodeDataParams extends BaseParams {\n data: Record<string, any>;\n}\n\nexport class StructuredNodeData extends NodeData {\n public data: Record<string, any>;\n constructor(params: StructuredNodeDataParams) {\n super({ ...params, id: hash(JSON.stringify(params.data)), type: 'structured' });\n this.data = params.data;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: this.data,\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/runtime\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"react\");","import { useLocationService } from '@grafana/runtime';\nimport type { ChatContextItem } from './types';\nimport { useEffect, useState, useRef, useCallback } from 'react';\n\n// Extend window interface for global registry\ndeclare global {\n interface Window {\n [key: string]: any;\n }\n}\n\nexport interface PageContextRegistration {\n id: string;\n urlPattern: string | RegExp;\n context: ChatContextItem[];\n}\n\n// Global registry key\nconst GLOBAL_REGISTRY_KEY = '__grafanaAssistantPageContextRegistry__';\n\n// Custom event for registry changes\nconst REGISTRY_CHANGE_EVENT = 'grafana-assistant:page-context-registry-changed';\n\n/**\n * Legacy event names for backward compatibility with the previous implementation.\n * These events are emitted alongside the new REGISTRY_CHANGE_EVENT to ensure\n * any existing code listening to the old events continues to work.\n *\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_UPDATE_EVENT = 'grafana-assistant:page-context-update';\n/**\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_REMOVE_EVENT = 'grafana-assistant:page-context-remove';\n/**\n * @deprecated These event name is maintained for backward compatibility only.\n * TODO: Remove after old event-based approach is fully deprecated\n */\nconst LEGACY_REGISTRY_SYNC_EVENT = 'grafana-assistant:page-context-sync';\n\n// Ensure global registry exists on window\nif (!window[GLOBAL_REGISTRY_KEY]) {\n window[GLOBAL_REGISTRY_KEY] = [];\n}\n\n// Get reference to the global registry\nfunction getPageContextRegistry(): PageContextRegistration[] {\n return window[GLOBAL_REGISTRY_KEY];\n}\n\n// TODO: Remove skipLegacyEvents parameter after old event-based approach is fully deprecated\nfunction setPageContextRegistry(newRegistry: PageContextRegistration[], skipLegacyEvents = false): void {\n window[GLOBAL_REGISTRY_KEY] = newRegistry;\n // Notify all listeners that the registry has changed\n window.dispatchEvent(new CustomEvent(REGISTRY_CHANGE_EVENT));\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy sync event for backward compatibility (unless we're processing a legacy event)\n if (!skipLegacyEvents) {\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_SYNC_EVENT, {\n detail: { registry: newRegistry },\n })\n );\n }\n}\n\n/**\n * Bridge to handle legacy events from external apps using old versions of @grafana/assistant.\n * This ensures that registrations from external apps get synced into our window registry.\n *\n * TODO: Remove this entire bridge after old event-based approach is fully deprecated\n */\nlet legacyBridgeInitialized = false;\n\nfunction initializeLegacyEventBridge(): void {\n if (legacyBridgeInitialized) {\n return;\n }\n legacyBridgeInitialized = true;\n\n // Handle legacy update events (registration added or updated)\n window.addEventListener(LEGACY_REGISTRY_UPDATE_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const registration = customEvent.detail as PageContextRegistration;\n\n if (!registration?.id) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const existingIndex = currentRegistry.findIndex((r) => r.id === registration.id);\n\n if (existingIndex !== -1) {\n // Update existing registration\n const newRegistry = [...currentRegistry];\n newRegistry[existingIndex] = registration;\n setPageContextRegistry(newRegistry, true); // Skip legacy events to avoid loops\n } else {\n // Add new registration\n setPageContextRegistry([...currentRegistry, registration], true); // Skip legacy events to avoid loops\n }\n });\n\n // Handle legacy remove events (registration removed)\n window.addEventListener(LEGACY_REGISTRY_REMOVE_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const id = customEvent.detail?.id;\n\n if (!id) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((r) => r.id === id);\n\n if (index !== -1) {\n const newRegistry = currentRegistry.filter((_, i) => i !== index);\n setPageContextRegistry(newRegistry, true); // Skip legacy events to avoid loops\n }\n });\n\n // Handle legacy sync events (entire registry sync from external app)\n window.addEventListener(LEGACY_REGISTRY_SYNC_EVENT, (event: Event) => {\n const customEvent = event as CustomEvent;\n const incomingRegistry = customEvent.detail?.registry as PageContextRegistration[];\n\n if (!Array.isArray(incomingRegistry)) {\n return;\n }\n\n const currentRegistry = getPageContextRegistry();\n const currentIds = new Set(currentRegistry.map((r) => r.id));\n\n // Merge: add any registrations from external app that we don't have\n const newRegistrations = incomingRegistry.filter((r) => !currentIds.has(r.id));\n\n if (newRegistrations.length > 0) {\n setPageContextRegistry([...currentRegistry, ...newRegistrations], true); // Skip legacy events to avoid loops\n }\n });\n}\n\n// TODO: Remove this initialization after old event-based approach is fully deprecated\n// Initialize the bridge on module load\ninitializeLegacyEventBridge();\n\n/**\n * Registers context items for specific pages based on URL patterns.\n * Returns a setter function to update the context dynamically, similar to useState.\n *\n * Multiple registrations with the same URL pattern are allowed and will all be merged\n * when the pattern matches. Each call creates a new independent registration.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialContext - *Initial* array of ContextItems to provide when the pattern matches. IMPORTANT: will be overwritten when setContext is used to update the context.\n * @returns A setter function to update the context, with an unregister method attached\n */\nexport function providePageContext(\n urlPattern: string | RegExp,\n initialContext: ChatContextItem[]\n): ((context: ChatContextItem[]) => void) & { unregister: () => void } {\n // Validate URL pattern at registration time (only warn once, not on every match)\n validateUrlPattern(urlPattern);\n\n // Always create a new registration to allow multiple providers with the same URL pattern\n const registration: PageContextRegistration = {\n id: generateRegistrationId(),\n urlPattern,\n context: [...initialContext],\n };\n\n const registry = getPageContextRegistry();\n setPageContextRegistry([...registry, registration]);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy update event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_UPDATE_EVENT, {\n detail: registration,\n })\n );\n\n // Create setter function that can update the context\n const setContext = (newContext: ChatContextItem[]) => {\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((reg) => reg.id === registration.id);\n if (index !== -1) {\n const newRegistry = [...currentRegistry];\n newRegistry[index] = { ...newRegistry[index], context: [...newContext] };\n setPageContextRegistry(newRegistry);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy update event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_UPDATE_EVENT, {\n detail: newRegistry[index],\n })\n );\n }\n };\n\n // Add unregister method to the setter\n setContext.unregister = () => {\n const currentRegistry = getPageContextRegistry();\n const index = currentRegistry.findIndex((reg) => reg.id === registration.id);\n if (index !== -1) {\n const newRegistry = currentRegistry.filter((_, i) => i !== index);\n setPageContextRegistry(newRegistry);\n\n // TODO: Remove this legacy event emission after old event-based approach is fully deprecated\n // Emit legacy remove event for backward compatibility\n window.dispatchEvent(\n new CustomEvent(LEGACY_REGISTRY_REMOVE_EVENT, {\n detail: { id: registration.id },\n })\n );\n }\n };\n\n return setContext;\n}\n\nconst empty: ChatContextItem[] = [];\n\n/**\n * React hook for providing page context that automatically cleans up on unmount.\n * This is the recommended way to use page context in React components.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialContext - Initial array of ContextItems to provide when the pattern matches. IMPORTANT: will be overwritten when setContext is used to update the context.\n * @returns A setter function to update the context\n */\nexport function useProvidePageContext(\n urlPattern: string | RegExp,\n initialContext: ChatContextItem[] = empty\n): (context: ChatContextItem[]) => void {\n const setContextRef = useRef<ReturnType<typeof providePageContext> | undefined>(undefined);\n const pendingUpdate = useRef<ChatContextItem[] | undefined>(undefined);\n const isModified = useRef(false);\n\n // Create or update the registration when dependencies change\n // biome-ignore lint/correctness/useExhaustiveDependencies: initialContext is intentionally excluded to prevent re-registering on every render; updates are handled by the second effect\n useEffect(() => {\n // Reset isModified flag when urlPattern changes so that initialContext updates\n // are applied to the new registration until manually modified again\n isModified.current = false;\n\n // If we have pending updates, prefer those over initialContext as they represent\n // newer state from child components\n const contextToUse = pendingUpdate.current !== undefined ? pendingUpdate.current : initialContext;\n setContextRef.current = providePageContext(urlPattern, contextToUse);\n\n // Clear pending update as it's now applied\n if (pendingUpdate.current !== undefined) {\n pendingUpdate.current = undefined;\n }\n\n // Cleanup on unmount or dependency change\n return () => {\n setContextRef.current?.unregister();\n setContextRef.current = undefined;\n };\n // We intentionally exclude initialContext from deps to prevent re-registering on every render\n // Updates to initialContext are handled by the second effect\n }, [urlPattern]);\n\n // Update context when initialContext changes, BUT only if we haven't manually modified it.\n // This prevents unstable initialContext props (e.g. passing [] inline) from overwriting\n // updates made via setContext by child components.\n useEffect(() => {\n if (!isModified.current && setContextRef.current) {\n setContextRef.current(initialContext);\n }\n }, [initialContext]);\n\n // Return a stable setter function\n const setContext = useCallback((newContext: ChatContextItem[]) => {\n isModified.current = true;\n if (setContextRef.current) {\n setContextRef.current(newContext);\n } else {\n pendingUpdate.current = newContext;\n }\n }, []);\n\n return setContext;\n}\n\n/**\n * Gets all context items that match the current URL.\n *\n * @param currentUrl - The current page URL to match against\n * @param registrations - Array of registrations to match against\n * @returns Array of ChatContextItem from all matching registrations\n */\nfunction getActivePageContext(currentUrl: string): ChatContextItem[] {\n if (!currentUrl) {\n return [];\n }\n\n const activeContext: ChatContextItem[] = [];\n const registry = getPageContextRegistry();\n\n for (const registration of registry) {\n if (matchesUrlPattern(currentUrl, registration.urlPattern)) {\n activeContext.push(...registration.context);\n }\n }\n\n return activeContext;\n}\n\nexport function usePageContext(\n options: { allowQuestions: boolean; allowComponents: boolean } = { allowQuestions: false, allowComponents: false }\n): ChatContextItem[] {\n const location = useLocationService();\n const initialPathname = location.getLocation().pathname;\n const [pageContext, setPageContext] = useState<ChatContextItem[]>(() => getActivePageContext(initialPathname));\n const currentPathnameRef = useRef(initialPathname);\n\n useEffect(() => {\n // Function to update context based on current location and registry\n const updateContext = () => {\n const pathname = location.getLocation().pathname;\n const context = getActivePageContext(pathname);\n setPageContext(context);\n };\n\n // Handle registry changes\n const handleRegistryChange = () => {\n updateContext();\n };\n\n // Subscribe to location changes\n const locationSub = location.getLocationObservable().subscribe((loc: { pathname: string }) => {\n const pathname = loc.pathname;\n if (pathname !== currentPathnameRef.current) {\n currentPathnameRef.current = pathname;\n updateContext();\n }\n });\n\n // Listen for registry changes\n window.addEventListener(REGISTRY_CHANGE_EVENT, handleRegistryChange);\n\n // TODO: Remove these legacy event listeners after old event-based approach is fully deprecated\n // Listen for legacy events for backward compatibility\n window.addEventListener(LEGACY_REGISTRY_UPDATE_EVENT, handleRegistryChange);\n window.addEventListener(LEGACY_REGISTRY_REMOVE_EVENT, handleRegistryChange);\n window.addEventListener(LEGACY_REGISTRY_SYNC_EVENT, handleRegistryChange);\n\n // Initial update\n updateContext();\n\n return () => {\n locationSub.unsubscribe();\n window.removeEventListener(REGISTRY_CHANGE_EVENT, handleRegistryChange);\n // TODO: Remove these legacy event listener removals after old event-based approach is fully deprecated\n window.removeEventListener(LEGACY_REGISTRY_UPDATE_EVENT, handleRegistryChange);\n window.removeEventListener(LEGACY_REGISTRY_REMOVE_EVENT, handleRegistryChange);\n window.removeEventListener(LEGACY_REGISTRY_SYNC_EVENT, handleRegistryChange);\n };\n }, [location]);\n\n let filteredContext = pageContext;\n\n if (!options.allowQuestions) {\n filteredContext = filteredContext.filter((item) => item.node.data?.type !== 'question');\n }\n\n if (!options.allowComponents) {\n filteredContext = filteredContext.filter((item) => item.node.data?.type !== 'component');\n }\n\n return filteredContext;\n}\n\nexport function generateRegistrationId(prefix = 'page-context'): string {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Validates the URL pattern at registration time and logs warnings for problematic patterns.\n * This is called once during registration, not on every URL match.\n */\nfunction validateUrlPattern(pattern: string | RegExp): void {\n if (pattern instanceof RegExp) {\n // Check if RegExp pattern matches everything (e.g., /.*/, /^.*$/)\n // This is intentional for global contexts (e.g., components), so we use a scoped warning\n const source = pattern.source;\n if (source === '.*' || source === '^.*$' || source === '^.*' || source === '.*$') {\n // Note: This is expected for global contexts like provideComponents.\n // The warning is intentionally omitted here since it's a valid use case.\n // If you want to warn for specific cases, filter them here.\n }\n return;\n }\n\n if (typeof pattern === 'string') {\n // Validate urlPattern - log error if empty string is passed\n if (!pattern || pattern.trim() === '') {\n console.warn(\n 'useProvidePageContext: Empty string passed as urlPattern. This will cause the context to not match any pages.'\n );\n return;\n }\n\n // Check if the pattern matches everything (e.g., ** becomes ^.*$)\n if (pattern === '**') {\n // Note: This is expected for global contexts.\n // The warning is intentionally omitted here since it's a valid use case.\n }\n }\n}\n\nfunction matchesUrlPattern(url: string, pattern: string | RegExp): boolean {\n if (pattern instanceof RegExp) {\n return pattern.test(url);\n }\n\n // For string patterns, support simple wildcards\n if (typeof pattern === 'string') {\n // Empty pattern never matches\n if (!pattern || pattern.trim() === '') {\n return false;\n }\n\n // Convert simple wildcard pattern to regex\n // * matches any characters except /, ** matches any path segments\n // Handle ** first with a placeholder to avoid conflicts\n const regexPattern = pattern\n .replace(/\\*\\*/g, '\\u0000DOUBLE_STAR\\u0000') // Temporary placeholder for **\n .replace(/\\*/g, '[^/]*') // * becomes [^/]*\n // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional \\u0000 null byte used as placeholder to avoid glob pattern conflicts\n .replace(/\\u0000DOUBLE_STAR\\u0000/g, '.*') // Replace placeholder with .*\n .replace(/\\?/g, '.'); // ? becomes .\n\n const finalRegex = `^${regexPattern}$`;\n const regex = new RegExp(finalRegex);\n return regex.test(url);\n }\n\n return false;\n}\n\n/**\n * Test utility function to clear all registrations from the registry.\n * This should only be used in tests to ensure a clean slate between test runs.\n *\n * @internal This is for testing purposes only\n */\nexport function __clearPageContextRegistryForTesting(): void {\n setPageContextRegistry([]);\n}\n","import { type ComponentType, useMemo } from 'react';\nimport { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, ComponentItemData } from './types';\nimport { providePageContext, usePageContext } from './page';\nimport { createAssistantContextItem } from './chat';\n\nexport type ComponentImplementation = ComponentType<any>;\nexport type NamedComponents = Record<string, ComponentImplementation>;\n\n/**\n * Type used to create a component context item.\n */\nexport interface CreateComponentContextParams extends BaseParams {\n components: Record<string, ComponentType<any>>;\n prompt: string;\n namespace?: string;\n}\n\nexport class ComponentNodeData extends NodeData {\n public components: Record<string, ComponentType<any>>;\n public prompt: string;\n public namespace: string;\n\n constructor(params: CreateComponentContextParams) {\n const namespace = params.namespace || 'components';\n super({ ...params, id: `${namespace}-${Object.keys(params.components).join('-')}`, type: 'component' });\n this.components = params.components;\n this.prompt = params.prompt;\n this.namespace = namespace;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n data: {\n name: `Custom UI components (${this.namespace})`,\n prompt: this.prompt\n ? this.prompt +\n '\\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.'\n : '',\n } satisfies Omit<ComponentItemData, 'components' | 'text' | 'namespace'>,\n };\n }\n}\n\n/**\n * React hook that provides all components available globally.\n * Components are available everywhere, regardless of URL patterns.\n *\n * @returns Object containing all components available globally, keyed by namespace.componentName\n */\nexport function usePageComponents(): Record<string, ComponentImplementation> {\n const pageContext = usePageContext({ allowComponents: true, allowQuestions: false });\n\n // Use useMemo to avoid recreating the components object on every render\n const components = useMemo(() => {\n const allComponents: Record<string, ComponentImplementation> = {};\n\n // Filter for component context items and extract their components\n for (const item of pageContext.filter((item) => item.node.data?.components)) {\n const componentData = item.node.data;\n if (componentData?.components && Object.keys(componentData.components).length > 0) {\n const namespace = componentData.namespace || componentData.name || 'components';\n\n // Add each component with namespace_componentName format\n for (const [componentName, component] of Object.entries(componentData.components)) {\n allComponents[`${namespace}_${componentName}`] = component as ComponentImplementation;\n }\n }\n }\n\n return allComponents;\n }, [pageContext]);\n\n return components;\n}\n\n/**\n * Provide components to the assistant.\n *\n * Components are always available globally, but the prompt is only applied when the URL pattern matches.\n *\n * For catch-all URL patterns, returns a setter that takes a context array.\n * For specific URL patterns, returns a setter that takes components and prompt separately.\n *\n * @param prompt - The prompt to use for the components (only applied when URL matches).\n * @param namespace - The namespace to use for the components.\n * @param components - The components to provide (always available).\n * @param urlPattern - The URL pattern to match for the prompt (components are always available).\n * @returns A setter function to update the context, with an unregister method attached\n */\nexport function provideComponents(\n prompt: string,\n namespace: string,\n components: Record<string, ComponentImplementation>,\n urlPattern: string | RegExp = /.*/\n): ((newComponents: Record<string, ComponentImplementation>, newPrompt: string) => void) & { unregister: () => void } {\n // Check if the URL pattern is catch-all (.*) - if so, register everything together\n const isCatchAll = (pattern: string | RegExp) => {\n if (pattern instanceof RegExp) {\n return pattern.source === '.*' && pattern.flags === '';\n }\n return pattern === '.*' || pattern === '/.*/';\n };\n\n if (isCatchAll(urlPattern)) {\n // If pattern is catch-all, register components and prompt together globally\n const setContext = providePageContext(/.*/, [\n createAssistantContextItem('component', {\n components,\n prompt,\n namespace,\n }),\n ]);\n\n // Create a wrapper setter that matches the expected signature\n const setter = (newComponents: Record<string, ComponentImplementation>, newPrompt: string) => {\n setContext([\n createAssistantContextItem('component', {\n components: newComponents,\n prompt: newPrompt,\n namespace,\n }),\n ]);\n };\n\n // Attach unregister method\n setter.unregister = setContext.unregister;\n\n return setter;\n }\n\n // For specific URL patterns, separate components (global) from prompt (URL-specific)\n const globalComponents = providePageContext(/.*/, [\n createAssistantContextItem('component', {\n components,\n prompt: '', // No prompt for global components\n namespace,\n }),\n ]);\n\n // Only register prompt for specific URL pattern\n const promptContext = providePageContext(urlPattern, [\n createAssistantContextItem('component', {\n components: {}, // No components, just prompt\n prompt,\n namespace,\n }),\n ]);\n\n // Return a setter that properly separates components and prompt\n // When updating, we extract components and prompt from the new data and update each registration appropriately\n const setter = (newComponents: Record<string, ComponentImplementation>, newPrompt: string) => {\n // Update global components registration with new components (but empty prompt)\n globalComponents([\n createAssistantContextItem('component', {\n components: newComponents,\n prompt: '', // No prompt for global components\n namespace,\n }),\n ]);\n\n // Update URL-specific registration with new prompt (but empty components)\n promptContext([\n createAssistantContextItem('component', {\n components: {}, // No components, just prompt\n prompt: newPrompt,\n namespace,\n }),\n ]);\n };\n\n // Attach unregister method that cleans up both registrations\n setter.unregister = () => {\n globalComponents.unregister();\n promptContext.unregister();\n };\n\n return setter;\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, DashboardItemData, FolderItemData } from './types';\n\nexport interface CreateDashboardContextParams extends BaseParams {\n dashboardUid: string;\n dashboardTitle: string;\n folderUid?: string;\n folderTitle?: string;\n}\n\nexport interface CreateFolderContextParams extends BaseParams {\n folderUid: string;\n folderTitle: string;\n}\n\nexport class DashboardNodeData extends NodeData {\n public dashboardUid: string;\n public dashboardTitle: string;\n public folderUid?: string;\n public folderTitle?: string;\n\n constructor(params: CreateDashboardContextParams) {\n super({ ...params, id: params.dashboardUid, type: 'dashboard' });\n this.dashboardUid = params.dashboardUid;\n this.dashboardTitle = params.dashboardTitle;\n this.folderUid = params.folderUid;\n this.folderTitle = params.folderTitle;\n this.text = params.dashboardTitle;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.dashboardTitle,\n dashboardUid: this.dashboardUid,\n dashboardTitle: this.dashboardTitle,\n folderUid: this.folderUid,\n folderTitle: this.folderTitle,\n text: this.text,\n } satisfies DashboardItemData,\n };\n }\n}\n\nexport class FolderNodeData extends NodeData {\n public folderUid: string;\n public folderTitle: string;\n public text = '';\n\n constructor(params: CreateFolderContextParams) {\n super({ ...params, id: params.folderUid, type: 'dashboard_folder' });\n this.folderUid = params.folderUid;\n this.folderTitle = params.folderTitle;\n this.text = params.folderTitle;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.folderTitle,\n folderUid: this.folderUid,\n folderTitle: this.folderTitle,\n text: this.text,\n } satisfies FolderItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { DatasourceMeta } from './factory';\nimport type { ContextItemData, DatasourceItemData } from './types';\n\n/**\n * Type used to create a datasource context item.\n *\n * All required attributes will be inferred from the datasources uid.\n */\nexport interface CreateDatasourceContextParams extends BaseParams {\n datasourceUid: string;\n}\n\nexport class DatasourceNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public img?: string;\n\n constructor(params: CreateDatasourceContextParams & DatasourceMeta) {\n super({ ...params, id: params.datasourceUid, type: 'datasource' });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.img = params.img;\n this.text = params.datasourceName;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.datasourceName,\n uid: this.datasourceUid,\n type: this.datasourceType,\n text: this.text,\n } satisfies DatasourceItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, EntityItemData } from './types';\n\n/**\n * Type used to create an entity context item.\n */\nexport interface CreateEntityContextParams extends BaseParams {\n type: string;\n name: string;\n scope?: {\n env?: string;\n site?: string;\n namespace?: string;\n };\n properties?: Record<string, any>;\n}\n\nexport class EntityNodeData extends NodeData {\n public entityType: string;\n public name: string;\n public scope?: {\n env?: string;\n site?: string;\n namespace?: string;\n };\n public properties?: Record<string, any>;\n\n constructor(params: CreateEntityContextParams) {\n super({\n id: `${params.type}-${params.name}-${[params.scope?.env, params.scope?.site, params.scope?.namespace].filter(Boolean).join('-')}`,\n type: 'entity',\n title: params.title,\n hidden: params.hidden,\n img: params.img,\n icon: params.icon,\n text: params.name,\n });\n this.entityType = params.type;\n this.name = params.name;\n this.scope = params.scope;\n this.properties = params.properties;\n this.text = params.name;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: 'entity',\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.name,\n text: this.text,\n type: this.entityType,\n scope: this.scope,\n properties: this.properties,\n } satisfies EntityItemData,\n };\n }\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { DatasourceMeta } from './factory';\nimport type { ContextItemData, LabelNameItemData, LabelValueItemData } from './types';\n\nexport interface CreateLabelNameContextParams extends BaseParams {\n datasourceUid: string;\n labelName: string;\n}\n\nexport interface CreateLabelValueContextParams extends CreateLabelNameContextParams {\n labelValue: string;\n /** Filter operator (e.g., '=', '!=', '=~', '!~'). Defaults to '=' if not specified */\n operator?: string;\n}\n\nexport class LabelNameNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public labelName: string;\n public img?: string;\n\n constructor(params: CreateLabelNameContextParams & DatasourceMeta) {\n super({ ...params, id: `${params.datasourceUid}-${params.labelName}`, type: 'label_name' });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.labelName = params.labelName;\n this.text = params.labelName;\n this.img = params.img;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.labelName,\n datasourceUid: this.datasourceUid,\n datasourceType: this.datasourceType,\n datasourceName: this.datasourceName,\n labelName: this.labelName,\n text: this.text,\n } satisfies LabelNameItemData,\n };\n }\n}\n\nexport class LabelValueNodeData extends NodeData {\n public datasourceUid: string;\n public datasourceType: string;\n public datasourceName: string;\n public labelName: string;\n public labelValue: string;\n public img?: string;\n public operator: string;\n\n constructor(params: CreateLabelValueContextParams & DatasourceMeta) {\n super({\n ...params,\n id: `${params.datasourceUid}-${params.labelName}-${params.labelValue}-${params.operator || '='}`,\n type: 'label_value',\n });\n this.datasourceUid = params.datasourceUid;\n this.datasourceType = params.datasourceType;\n this.datasourceName = params.datasourceName;\n this.labelName = params.labelName;\n this.labelValue = params.labelValue;\n this.text = params.labelValue;\n this.img = params.img;\n this.operator = params.operator || '=';\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.labelValue,\n datasourceUid: this.datasourceUid,\n datasourceType: this.datasourceType,\n datasourceName: this.datasourceName,\n labelName: this.labelName,\n labelValue: this.labelValue,\n text: this.text,\n operator: this.operator,\n } satisfies LabelValueItemData,\n };\n }\n}\n","import { getDataSourceSrv } from '@grafana/runtime';\nimport { NodeData, type NodeDataParams, StructuredNodeData, type StructuredNodeDataParams } from './base';\nimport { ComponentNodeData, type CreateComponentContextParams } from './component';\nimport {\n DashboardNodeData,\n FolderNodeData,\n type CreateDashboardContextParams,\n type CreateFolderContextParams,\n} from './dashboard';\nimport { DatasourceNodeData, type CreateDatasourceContextParams } from './datasource';\nimport { EntityNodeData, type CreateEntityContextParams } from './entity';\nimport {\n LabelNameNodeData,\n LabelValueNodeData,\n type CreateLabelNameContextParams,\n type CreateLabelValueContextParams,\n} from './label';\n\n/**\n * registry to handle the type mappings between ItemData type, params and node data\n */\nexport type ContextTypeRegistry = {\n datasource: { params: CreateDatasourceContextParams; node: DatasourceNodeData };\n label_name: { params: CreateLabelNameContextParams; node: LabelNameNodeData };\n label_value: { params: CreateLabelValueContextParams; node: LabelValueNodeData };\n dashboard: { params: CreateDashboardContextParams; node: DashboardNodeData };\n dashboard_folder: { params: CreateFolderContextParams; node: FolderNodeData };\n structured: { params: StructuredNodeDataParams; node: StructuredNodeData };\n component: { params: CreateComponentContextParams; node: ComponentNodeData };\n entity: { params: CreateEntityContextParams; node: EntityNodeData };\n unknown: { params: NodeDataParams; node: NodeData };\n};\n\nexport type DatasourceMeta = {\n datasourceType: string;\n datasourceName: string;\n img?: string;\n};\n\n/**\n * Helper function to get datasource type from datasource UID\n */\nfunction getDatasourceMeta(datasourceUid: string): DatasourceMeta {\n const datasourceInstance = getDataSourceSrv().getInstanceSettings(datasourceUid);\n return {\n datasourceType: datasourceInstance?.type ?? 'unknown',\n datasourceName: datasourceInstance?.name ?? datasourceUid,\n img: datasourceInstance?.meta?.info?.logos?.small,\n };\n}\n\n/**\n * Creates context nodes based on type with full type safety using generics\n */\nexport function createContextByType<T extends keyof ContextTypeRegistry>(\n type: T,\n params: ContextTypeRegistry[T]['params']\n): ContextTypeRegistry[T]['node'] {\n switch (type) {\n case 'datasource':\n return new DatasourceNodeData({\n ...(params as CreateDatasourceContextParams),\n ...getDatasourceMeta((params as CreateDatasourceContextParams).datasourceUid),\n });\n case 'label_name':\n return new LabelNameNodeData({\n ...(params as CreateLabelNameContextParams),\n ...getDatasourceMeta((params as CreateLabelNameContextParams).datasourceUid),\n });\n case 'label_value':\n return new LabelValueNodeData({\n ...(params as CreateLabelValueContextParams),\n ...getDatasourceMeta((params as CreateLabelValueContextParams).datasourceUid),\n });\n case 'dashboard':\n return new DashboardNodeData(params as CreateDashboardContextParams);\n case 'dashboard_folder':\n return new FolderNodeData(params as CreateFolderContextParams);\n case 'structured':\n return new StructuredNodeData(params as StructuredNodeDataParams);\n case 'component':\n return new ComponentNodeData({\n ...(params as CreateComponentContextParams),\n hidden: true,\n });\n case 'entity':\n return new EntityNodeData(params as CreateEntityContextParams);\n case 'unknown':\n return new NodeData(params as NodeDataParams);\n default:\n console.error(`Unknown context type: ${type}`);\n return new NodeData(params as NodeDataParams);\n }\n}\n","import type { IconName } from '@grafana/ui';\nimport { type NodeData, StructuredNodeData } from './base';\nimport { createContextByType, type ContextTypeRegistry } from './factory';\nimport type { ChatContextItem, ItemDataType } from './types';\n\nconst defaultIcons: Record<ItemDataType, IconName> = {\n datasource: 'database',\n label_name: 'database',\n label_value: 'database',\n dashboard: 'dashboard',\n dashboard_folder: 'folder',\n unknown: 'circle-mono',\n structured: 'gf-grid',\n component: 'gf-grid',\n entity: 'asserts',\n skill: 'play',\n};\n\nfunction getTitleFromContextNode(nodeData: NodeData | StructuredNodeData): string {\n return nodeData instanceof StructuredNodeData\n ? nodeData.formatForLLM().data.name\n : (nodeData.text ?? 'Given Context');\n}\n\nfunction getImgFromContextNode(nodeData: NodeData | StructuredNodeData): string | undefined {\n if ('img' in nodeData) {\n return (nodeData as { img?: string }).img;\n }\n return undefined;\n}\n\n/**\n * Creates a new chat context item that can be added to conversations.\n *\n * This function creates structured context items that provide additional information\n * to the AI assistant during conversations. Context items can include:\n * - Datasources (metrics, logs, traces)\n * - Labels and their values\n * - Dashboards and folders\n * - Structured data objects\n *\n * The created context item includes display metadata (title, icon, image) and\n * the underlying data that will be formatted and sent to the LLM when the\n * context is included in a conversation.\n *\n * @param type - The type of context to create (Datasource, Label, Dashboard etc.)\n * @param params - Type-specific parameters for creating the context item\n * @returns A ChatContextItem that can be added to conversation context\n *\n * @example\n * ```typescript\n * // Create a context that will be passed into the function triggering an assistant open\n * openAssistant({\n * ...\n * origin: 'my-feature',\n * context: [\n * createAssistantContextItem('datasource', {\n * datasourceUid: datasource.uid,\n * img: datasource.meta?.info?.logos?.small,\n * }),\n * ],\n * });\n * ```\n */\nexport function createAssistantContextItem<T extends keyof ContextTypeRegistry>(\n type: T,\n params: ContextTypeRegistry[T]['params']\n): ChatContextItem {\n const nodeData = createContextByType(type, params);\n const defaultTitle = params.title ?? getTitleFromContextNode(nodeData);\n const img = params.img ?? getImgFromContextNode(nodeData);\n return {\n node: {\n id: nodeData.id,\n name: defaultTitle,\n img,\n icon: params.icon ?? defaultIcons[type],\n navigable: false,\n selectable: true,\n data: nodeData,\n },\n occurrences: [],\n };\n}\n","import { type BaseParams, NodeData } from './base';\nimport type { ContextItemData, SkillItemData } from './types';\n\nexport interface CreateSkillContextParams extends BaseParams {\n skillId: string;\n skillName: string;\n}\n\nexport class SkillNodeData extends NodeData {\n public skillId: string;\n public skillName: string;\n\n constructor(params: CreateSkillContextParams) {\n super({\n ...params,\n id: params.skillId,\n type: 'skill',\n text: params.skillName,\n });\n this.skillId = params.skillId;\n this.skillName = params.skillName;\n this.text = params.skillName;\n }\n\n formatForLLM(codeElementIds?: string[]): ContextItemData {\n return {\n type: this.type,\n codeElementIds,\n bypassLimits: this.bypassLimits,\n data: {\n name: this.skillName,\n skillId: this.skillId,\n skillName: this.skillName,\n text: this.text,\n } satisfies SkillItemData,\n };\n }\n}\n","import { useMemo } from 'react';\nimport type { ChatContextItem } from './types';\nimport { providePageContext, useProvidePageContext, usePageContext, generateRegistrationId } from './page';\n\nexport interface Question {\n prompt: string;\n title?: string;\n context?: ChatContextItem[];\n}\n\nexport interface QuestionRegistration {\n id: string;\n urlPattern: string | RegExp;\n questions: Question[];\n}\n\n/**\n * Registers questions for specific pages based on URL patterns.\n * Returns a setter function to update the questions dynamically, similar to useState.\n *\n * Multiple registrations with the same URL pattern are allowed and will all be merged\n * when the pattern matches. Each call creates a new independent registration.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialQuestions - Initial array of questions to provide when the pattern matches\n * @returns A setter function to update the questions, with an unregister method attached\n */\nexport function provideQuestions(\n urlPattern: string | RegExp,\n initialQuestions: Question[]\n): ((questions: Question[]) => void) & { unregister: () => void } {\n // Generate a unique registration ID to prevent collisions when multiple registrations exist\n const registrationId = generateRegistrationId('question');\n\n // Convert questions to ChatContextItem format for the underlying system\n const convertQuestionsToContext = (questions: Question[]): ChatContextItem[] => {\n return questions.map((question, index) => ({\n node: {\n id: `question-${registrationId}-${index}`,\n name: question.title || question.prompt,\n navigable: false,\n selectable: true,\n icon: 'question-circle',\n data: {\n type: 'question',\n prompt: question.prompt,\n title: question.title,\n context: question.context || [],\n },\n },\n occurrences: [],\n }));\n };\n\n // Use the existing providePageContext system\n const setContext = providePageContext(urlPattern, convertQuestionsToContext(initialQuestions));\n\n // Create a wrapper that converts between questions and context\n const setQuestions = (newQuestions: Question[]) => {\n setContext(convertQuestionsToContext(newQuestions));\n };\n\n // Add unregister method\n setQuestions.unregister = setContext.unregister;\n\n return setQuestions;\n}\n\n/**\n * React hook for providing questions that automatically cleans up on unmount.\n * This is the recommended way to use questions in React components.\n *\n * @param urlPattern - URL pattern (string or RegExp) to match against page URLs\n * @param initialQuestions - Initial array of questions to provide when the pattern matches\n * @returns A setter function to update the questions\n */\nexport function useProvideQuestions(\n urlPattern: string | RegExp,\n initialQuestions: Question[] = []\n): (questions: Question[]) => void {\n // Generate a stable unique registration ID per component instance to prevent collisions\n const registrationId = useMemo(\n () => generateRegistrationId('question'),\n [] // Empty deps = generated once per component instance\n );\n\n // Convert questions to ChatContextItem format for the underlying system\n const convertQuestionsToContext = (questions: Question[]): ChatContextItem[] => {\n return questions.map((question, index) => ({\n node: {\n id: `question-${registrationId}-${index}`,\n name: question.title ?? question.prompt,\n navigable: false,\n selectable: true,\n icon: 'question-circle',\n data: {\n type: 'question',\n prompt: question.prompt,\n title: question.title,\n context: question.context || [],\n },\n },\n occurrences: [],\n }));\n };\n\n // Use the existing useProvidePageContext system\n const setContext = useProvidePageContext(urlPattern, convertQuestionsToContext(initialQuestions));\n\n // Create a wrapper that converts between questions and context\n const setQuestions = (newQuestions: Question[]) => {\n setContext(convertQuestionsToContext(newQuestions));\n };\n\n return setQuestions;\n}\n\n/**\n * React hook to get all questions that match the current URL.\n * This filters the page context to only return question-type items.\n *\n * @returns Array of questions from all matching registrations\n */\nexport function useQuestions(): Question[] {\n const pageContext = usePageContext({ allowQuestions: true, allowComponents: false });\n\n // Filter and convert context items to questions\n return convertContextToQuestions(pageContext);\n}\n\nconst convertContextToQuestions = (contextItems: ChatContextItem[]): Question[] => {\n return contextItems\n .filter((item) => item.node.data?.type === 'question')\n .map((item) => ({\n prompt: item.node.data?.prompt || item.node.name,\n title: item.node.data?.title,\n context: item.node.data?.context || [],\n }));\n};\n","import type { PluginExtensionAddedFunctionConfig } from '@grafana/data';\n\nexport type CallbackFunction = () => FunctionNamespace[];\nexport type FunctionImplementation = (...args: any[]) => any;\nexport const CALLBACK_EXTENSION_POINT = 'grafana-assistant-app/callback/v0-alpha';\n\nexport type NamedFunctions = Record<string, FunctionImplementation>;\nexport type FunctionNamespace = {\n namespace: string;\n functions: NamedFunctions;\n};\n\nexport function newFunctionNamespace(namespace: string, functions: NamedFunctions): FunctionNamespace {\n return {\n namespace,\n functions,\n };\n}\n\nexport function getExposeAssistantFunctionsConfig(\n namespaces: FunctionNamespace[]\n): PluginExtensionAddedFunctionConfig<() => FunctionNamespace[]> {\n return {\n title: 'callback',\n targets: [CALLBACK_EXTENSION_POINT],\n fn: () => {\n return namespaces.map((namespace) => {\n return {\n namespace: namespace.namespace,\n functions: namespace.functions,\n };\n });\n },\n };\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs\");","import { getObservablePluginLinks } from '@grafana/runtime';\n// biome-ignore lint/suspicious/noDeprecatedImports: throwError and timer have deprecated overloads but we use the non-deprecated factory/single-arg forms\nimport { catchError, defer, map, type Observable, of, retry, throwError, timer } from 'rxjs';\n\nexport const ASSISTANT_PLUGIN_ID = 'grafana-assistant-app';\nexport const ASSISTANT_PLUGIN_TITLE = 'Grafana Assistant';\n\nconst MAX_RETRY_ATTEMPTS = 10;\nconst INITIAL_RETRY_DELAY = 100; // 100ms\nconst MAX_RETRY_DELAY = 5000; // 5 seconds\n\n/**\n * Check if the assistant is available.\n * @returns An observable that emits true if the assistant is available, false otherwise.\n */\nexport function isAssistantAvailable(): Observable<boolean> {\n // this is to avoid crashing in older Grafana versions\n if (!getObservablePluginLinks) {\n return of(false);\n }\n\n // Use defer to make the call lazy and handle both sync and async errors\n return defer(() => {\n try {\n const links = getObservablePluginLinks({\n extensionPointId: 'grafana/extension-sidebar/v0-alpha',\n });\n return links.pipe(\n map((links: Array<{ pluginId: string; title: string }>) =>\n links.some((link) => link.pluginId === ASSISTANT_PLUGIN_ID && link.title === ASSISTANT_PLUGIN_TITLE)\n )\n );\n } catch (error) {\n // If getObservablePluginLinks throws synchronously, convert to observable error\n return throwError(() => error);\n }\n }).pipe(\n retry({\n count: MAX_RETRY_ATTEMPTS,\n delay: (error, retryCount) => {\n // Check if error indicates Grafana hasn't started yet\n const errorMessage = error?.message?.toLowerCase() || '';\n const isGrafanaNotReady =\n errorMessage.includes('can only be used after') ||\n errorMessage.includes('grafana instance has started') ||\n errorMessage.includes('not started');\n\n // Don't retry for non-race-condition errors\n if (!isGrafanaNotReady) {\n throw error;\n }\n\n // Exponential backoff: delay = INITIAL_RETRY_DELAY * 2^retryCount, capped at MAX_RETRY_DELAY\n const delayMs = Math.min(INITIAL_RETRY_DELAY * 2 ** (retryCount - 1), MAX_RETRY_DELAY);\n return timer(delayMs);\n },\n }),\n catchError(() => {\n // After all retries exhausted, return false\n return of(false);\n })\n );\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/data\");","import { BusEventBase, BusEventWithPayload } from '@grafana/data';\nimport { getAppEvents, reportInteraction } from '@grafana/runtime';\nimport type { ChatContextItem } from './context/types';\nimport { ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE } from './plugin';\n\ninterface OpenExtensionSidebarPayload {\n props?: Record<string, unknown>;\n pluginId: string;\n componentTitle: string;\n}\n\nclass OpenExtensionSidebarEvent extends BusEventWithPayload<OpenExtensionSidebarPayload> {\n static type = 'open-extension-sidebar';\n}\n\nclass CloseExtensionSidebarEvent extends BusEventBase {\n static type = 'close-extension-sidebar';\n}\n\nclass ToggleExtensionSidebarEvent extends BusEventWithPayload<OpenExtensionSidebarPayload> {\n static type = 'toggle-extension-sidebar';\n}\n\nfunction openExtensionSidebar(pluginId: string, componentTitle: string, props?: Record<string, unknown>) {\n const event = new OpenExtensionSidebarEvent({\n pluginId,\n componentTitle,\n props,\n });\n getAppEvents().publish(event);\n}\n\nfunction closeExtensionSidebar() {\n const event = new CloseExtensionSidebarEvent();\n getAppEvents().publish(event);\n}\n\nfunction toggleExtensionSidebar(pluginId: string, componentTitle: string, props?: Record<string, unknown>) {\n const event = new ToggleExtensionSidebarEvent({\n pluginId,\n componentTitle,\n props,\n });\n getAppEvents().publish(event);\n}\n\nexport type OpenAssistantProps = {\n origin: string;\n\n prompt?: string;\n context?: ChatContextItem[];\n autoSend?: boolean;\n /** Mode to open the assistant in. Built-in modes: 'assistant', 'investigation', 'dashboarding'. Can also be a backend agent ID. */\n mode?: string;\n /** When set, sends the prompt as a follow-up into this existing conversation instead of creating a new one. */\n chatId?: string;\n /** When true, append context to the chat instead of replacing it. */\n appendContext?: boolean;\n};\n\n/**\n * Open the Grafana Assistant sidebar with a given initial prompt.\n *\n * @param props - The props to pass to the assistant.\n * @param props.origin - The origin of the request that opened the assistant. This is used to track the source of the request. Should be a structured string using forward slashes, with the first part as a namespace. Examples: 'grafana-datasources/prometheus/query-builder', 'grafana-slo-app/slo-editor-overview', 'grafana/trace-view-analyzer`.\n * @param props.prompt - The initial prompt to display in the assistant.\n * @param props.context - The initial context to display in the assistant. Created with `createContext`.\n * @param props.autoSend - Whether to automatically send the initial prompt. When true, opens a chat and sends the initial prompt right away. When false, opens chat and updates user message without sending it. Defaults to true.\n * @param props.mode - The mode to open the assistant in. Built-in modes: 'assistant', 'investigation', 'dashboarding'. Can also be a backend agent ID. Defaults to 'assistant'.\n * @param props.chatId - When set, sends the prompt as a follow-up into this existing conversation instead of creating a new one.\n */\nexport function openAssistant(props: OpenAssistantProps) {\n reportInteraction('grafana_assistant_app_opened_sidebar', {\n from: props.origin,\n });\n\n openExtensionSidebar(ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE, {\n initialPrompt: props.prompt,\n initialContext: props.context,\n initialAutoSend: props.autoSend ?? true,\n origin: props.origin,\n initialMode: props.mode,\n chatId: props.chatId,\n appendContext: props.appendContext,\n });\n}\n\n/**\n * Close the Grafana Assistant sidebar.\n */\nexport function closeAssistant() {\n closeExtensionSidebar();\n}\n\nexport function toggleAssistant(props: OpenAssistantProps) {\n reportInteraction('grafana_assistant_app_toggled_sidebar', {\n from: props.origin,\n prompt: props.prompt ?? '',\n });\n\n toggleExtensionSidebar(ASSISTANT_PLUGIN_ID, ASSISTANT_PLUGIN_TITLE, {\n initialPrompt: props.prompt,\n initialContext: props.context,\n initialAutoSend: props.autoSend ?? true,\n origin: props.origin,\n initialMode: props.mode,\n chatId: props.chatId,\n appendContext: props.appendContext,\n });\n}\n","import { useEffect, useState } from 'react';\nimport { isAssistantAvailable } from './plugin';\nimport { closeAssistant, openAssistant, toggleAssistant, type OpenAssistantProps } from './sidebar';\n\nexport type AssistantHook = {\n /** Whether the availability check is still in progress. */\n isLoading: boolean;\n isAvailable: boolean;\n openAssistant: ((props: OpenAssistantProps) => void) | undefined;\n closeAssistant: (() => void) | undefined;\n toggleAssistant: ((props: OpenAssistantProps) => void) | undefined;\n};\n/**\n * Hook to check if the assistant is available and return the open, close, and toggle functions.\n * @returns {AssistantHook}\n */\nexport function useAssistant(): AssistantHook {\n const [available, setAvailable] = useState<boolean | undefined>(undefined);\n\n useEffect(() => {\n const sub = isAssistantAvailable().subscribe(setAvailable);\n return () => sub.unsubscribe();\n }, []);\n\n const isAvailable = available ?? false;\n\n return {\n isLoading: available === undefined,\n isAvailable,\n openAssistant: isAvailable ? openAssistant : undefined,\n closeAssistant: isAvailable ? closeAssistant : undefined,\n toggleAssistant: isAvailable ? toggleAssistant : undefined,\n };\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"react/jsx-runtime\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@grafana/ui\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@emotion/css\");","import { useEffect } from 'react';\nimport { Button, IconButton, useStyles2 } from '@grafana/ui';\nimport { css } from '@emotion/css';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { reportInteraction } from '@grafana/runtime';\n\nexport interface OpenAssistantButtonProps {\n /** Prompt to pass to the openAssistant function. */\n prompt: string;\n /** Origin of the request that opened the assistant. This is used to track the source of the request. Should be a structured string using forward slashes, with the first part as a namespace. Examples: 'grafana-datasources/prometheus/query-builder', 'grafana-slo-app/slo-editor-overview', 'grafana/trace-view-analyzer`. */\n origin: string;\n /** Context to pass to the openAssistant function. Optional, defaults to undefined. Created with `createAssistantContextItem`. */\n context?: ChatContextItem[];\n /** Whether to automatically send the prompt. Optional, defaults to true. */\n autoSend?: boolean;\n /** Text to display on the button. Optional, defaults to 'Analyze with Assistant' */\n title?: string;\n /** Button size, defaults to sm */\n size?: 'xs' | 'sm' | 'md' | 'lg';\n /** If true, the button will be Assistant icon only with name as title. Defaults to false. */\n iconOnlyButton?: boolean;\n /** Function to call when the button is clicked. Optional, defaults to undefined. */\n onClick?: () => void;\n}\n\n/**\n * A button component that opens the Grafana Assistant with configurable prompt and context.\n */\nexport function OpenAssistantButton(props: OpenAssistantButtonProps) {\n // If the assistant is not available, return empty\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <OpenAssistantButtonView {...props} openAssistant={openAssistant} />;\n}\n\n/**\n * Presentational component separated from OpenAssistantButton to avoid hook dependencies in Storybook.\n * It is not exported for users of the package.\n */\nexport function OpenAssistantButtonView({\n prompt,\n origin,\n context,\n autoSend = true,\n title = 'Analyze with Assistant',\n size = 'sm',\n iconOnlyButton = false,\n openAssistant,\n onClick,\n}: OpenAssistantButtonProps & {\n openAssistant: (props: OpenAssistantProps) => void;\n}) {\n const styles = useStyles2(getStyles);\n\n useEffect(() => {\n reportInteraction('grafana_assistant_app_open_sidebar_button_displayed', {\n from: origin,\n });\n }, [origin]);\n\n return (\n <>\n {iconOnlyButton ? (\n <IconButton\n name=\"ai-sparkle\"\n onClick={() => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n }}\n variant=\"secondary\"\n size={size}\n aria-label={title}\n className={styles.icon}\n tooltip={title}\n data-testid=\"assistant-icon-button\"\n />\n ) : (\n <Button\n icon=\"ai-sparkle\"\n onClick={() => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n }}\n variant=\"secondary\"\n fill=\"solid\"\n size={size}\n title={title}\n aria-label={title}\n className={styles.button}\n data-testid=\"assistant-button\"\n >\n {title}\n </Button>\n )}\n </>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const baseBackground = theme.colors.secondary.main;\n const elevatedBackground = theme.colors.emphasize(baseBackground, 0.05);\n\n // Canvas is what's typically underneath buttons\n const underlyingColor = theme.colors.background.canvas;\n\n const borderWidth = 1;\n const outerRadius = theme.shape.radius.default;\n // inner radius = outer radius - border width, but take at least 1px\n const innerRadius = `max(calc(${outerRadius} - ${borderWidth}px), 1px)`;\n\n // Gradient border layer (::before)\n const gradientBorderLayer = {\n content: '\"\"',\n position: 'absolute' as const,\n inset: 0,\n borderRadius: outerRadius,\n cornerShape: 'squircle',\n background: 'linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))',\n zIndex: -2,\n pointerEvents: 'none' as const,\n };\n\n // Solid background layer factory (::after)\n // Layer transparent color over canvas to make it opaque and mask the gradient properly\n const solidBackgroundLayer = (background: string) => ({\n content: '\"\"',\n position: 'absolute' as const,\n inset: `${borderWidth}px`,\n borderRadius: innerRadius,\n cornerShape: 'squircle',\n background: `linear-gradient(${background}, ${background}), ${underlyingColor}`,\n zIndex: -1,\n transition: 'none',\n pointerEvents: 'none' as const,\n });\n\n return {\n button: css({\n label: 'assistant-button',\n width: 'fit-content',\n maxWidth: '100%',\n position: 'relative',\n isolation: 'isolate',\n border: 'none',\n transition: 'none !important',\n '&::before': gradientBorderLayer,\n '&::after': {\n ...solidBackgroundLayer(baseBackground),\n transition: 'none',\n },\n '&:hover': {\n transition: 'none !important',\n },\n '&:hover::after': {\n background: `linear-gradient(${elevatedBackground}, ${elevatedBackground}), ${underlyingColor}`,\n },\n }),\n icon: css({\n label: 'assistant-icon',\n position: 'relative',\n isolation: 'isolate',\n border: 'none',\n background: 'none',\n padding: theme.spacing(0.5),\n '&::before': { ...gradientBorderLayer, transition: 'background 0.1s ease' },\n '&:hover::after': {\n ...solidBackgroundLayer(baseBackground),\n background: `linear-gradient(${elevatedBackground}, ${elevatedBackground}), ${underlyingColor}`,\n },\n }),\n };\n};\n","import { type ReactElement, useEffect } from 'react';\nimport { Button, ButtonGroup, Dropdown, Tooltip, useStyles2 } from '@grafana/ui';\nimport { css, cx } from '@emotion/css';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { reportInteraction } from '@grafana/runtime';\n\nexport interface OpenAssistantSplitButtonProps {\n /** Prompt to pass to the openAssistant function. */\n prompt: string;\n /** Origin of the request that opened the assistant. */\n origin: string;\n /** Context to pass to the openAssistant function. Optional, defaults to undefined. */\n context?: ChatContextItem[];\n /** Whether to automatically send the prompt. Optional, defaults to true. */\n autoSend?: boolean;\n /** Text to display on the button. Optional, defaults to 'Chat with Assistant' */\n title?: string;\n /** Button size, defaults to sm */\n size?: 'sm' | 'md' | 'lg';\n /** Function to call when the main button is clicked. Optional. */\n onClick?: () => void;\n /** Additional menu items to show in the dropdown. Optional. */\n menuItems?: ReactElement;\n /** Tooltip text to display on hover. Optional. */\n tooltip?: string;\n /** Width for the dropdown/chevron segment. Accepts pixels as number or any CSS width value. */\n dropdownButtonWidth?: number | string;\n}\n\ntype AssistantButtonSize = NonNullable<OpenAssistantSplitButtonProps['size']>;\n\nconst defaultDropdownButtonWidths: Record<AssistantButtonSize, number> = {\n sm: 32,\n md: 36,\n lg: 40,\n};\n\n/**\n * A split button component that opens the Grafana Assistant with a dropdown for additional actions.\n * The gradient border wraps around both buttons as a unified control.\n */\nexport function OpenAssistantSplitButton(props: OpenAssistantSplitButtonProps) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <OpenAssistantSplitButtonView {...props} openAssistant={openAssistant} />;\n}\n\nexport function OpenAssistantSplitButtonView({\n prompt,\n origin,\n context,\n autoSend = true,\n title = 'Chat with Assistant',\n size = 'sm',\n onClick,\n menuItems,\n tooltip,\n dropdownButtonWidth,\n openAssistant,\n}: OpenAssistantSplitButtonProps & {\n openAssistant: (props: OpenAssistantProps) => void;\n}) {\n const styles = useStyles2(getStyles);\n const hasMenuItems = Boolean(menuItems);\n const resolvedDropdownButtonWidth = toCssWidth(dropdownButtonWidth ?? defaultDropdownButtonWidths[size]);\n\n useEffect(() => {\n reportInteraction('grafana_assistant_app_open_sidebar_split_button_displayed', {\n from: origin,\n });\n }, [origin]);\n\n const handleMainClick = () => {\n onClick?.();\n openAssistant({ prompt, context, autoSend, origin });\n };\n\n const wrapperContent = (\n <div className={styles.wrapper}>\n <ButtonGroup className={styles.buttonGroup}>\n <Button\n icon=\"ai-sparkle\"\n onClick={handleMainClick}\n variant=\"secondary\"\n fill=\"solid\"\n size={size}\n aria-label={title}\n className={cx(styles.segmentButton, hasMenuItems ? styles.mainButtonSplit : styles.mainButtonSolo)}\n data-testid=\"assistant-split-button-main\"\n >\n {title}\n </Button>\n {menuItems && (\n <Dropdown overlay={menuItems}>\n <Button\n variant=\"secondary\"\n icon=\"angle-down\"\n size={size}\n aria-label=\"More AI actions\"\n className={cx(styles.segmentButton, styles.dropdownButton)}\n style={{ width: resolvedDropdownButtonWidth, minWidth: resolvedDropdownButtonWidth }}\n data-testid=\"assistant-split-button-dropdown\"\n />\n </Dropdown>\n )}\n </ButtonGroup>\n </div>\n );\n\n return tooltip ? <Tooltip content={tooltip}>{wrapperContent}</Tooltip> : wrapperContent;\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const baseBackground = theme.colors.secondary.main;\n const elevatedBackground = theme.colors.emphasize(baseBackground, 0.05);\n const underlyingColor = theme.colors.background.canvas;\n const dividerColor = theme.colors.border.weak;\n const borderWidth = 1;\n const outerRadius = theme.shape.radius.default;\n const innerRadius = `max(calc(${outerRadius} - ${borderWidth}px), 1px)`;\n\n return {\n wrapper: css({\n label: 'assistant-split-button-wrapper',\n position: 'relative',\n isolation: 'isolate',\n display: 'inline-block',\n // Gradient border around the entire button group\n '&::before': {\n content: '\"\"',\n position: 'absolute',\n inset: 0,\n borderRadius: outerRadius,\n cornerShape: 'squircle',\n background: 'linear-gradient(90deg, rgb(168, 85, 247), rgb(249, 115, 22))',\n zIndex: -1,\n pointerEvents: 'none',\n },\n // Solid background layer\n '&::after': {\n content: '\"\"',\n position: 'absolute',\n inset: `${borderWidth}px`,\n borderRadius: innerRadius,\n cornerShape: 'squircle',\n background: `linear-gradient(${baseBackground}, ${baseBackground}), ${underlyingColor}`,\n zIndex: -1,\n pointerEvents: 'none',\n },\n }),\n buttonGroup: css({\n label: 'assistant-split-button-group',\n gap: 0,\n position: 'relative',\n zIndex: 1,\n borderRadius: innerRadius,\n overflow: 'hidden',\n // Make buttons transparent to show the wrapper's gradient\n '& button': {\n border: 'none',\n boxShadow: 'none',\n background: 'transparent !important',\n },\n }),\n segmentButton: css({\n label: 'assistant-split-button-segment',\n position: 'relative',\n '&:hover': {\n background: `${elevatedBackground} !important`,\n },\n '&:focus-visible': {\n background: `${elevatedBackground} !important`,\n },\n '&[aria-expanded=\"true\"]': {\n background: `${elevatedBackground} !important`,\n },\n }),\n mainButtonSolo: css({\n label: 'assistant-split-button-main-solo',\n borderRadius: innerRadius,\n }),\n mainButtonSplit: css({\n label: 'assistant-split-button-main-split',\n borderTopLeftRadius: innerRadius,\n borderBottomLeftRadius: innerRadius,\n borderTopRightRadius: 0,\n borderBottomRightRadius: 0,\n }),\n dropdownButton: css({\n label: 'assistant-split-button-dropdown',\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n gap: 0,\n borderTopLeftRadius: 0,\n borderBottomLeftRadius: 0,\n borderTopRightRadius: innerRadius,\n borderBottomRightRadius: innerRadius,\n padding: '0 !important',\n boxShadow: `inset 1px 0 0 ${dividerColor}`,\n '& svg': {\n margin: 0,\n },\n }),\n };\n};\n\nfunction toCssWidth(width: number | string): string {\n return typeof width === 'number' ? `${width}px` : width;\n}\n","import type { GrafanaTheme2 } from '@grafana/data';\n\n/**\n * Default gradient colors for the assistant\n */\nconst GRADIENT_COLORS = {\n PURPLE: 'rgb(168, 85, 247)',\n ORANGE: 'rgb(249, 115, 22)',\n} as const;\n\n// FIXME: use SDK as single source of truth for these color schemes?\n\n/**\n * Returns the colors of the background gradient based on the theme.\n *\n * @param theme - The Grafana theme object.\n * @returns The colors of the background gradient as tuple.\n */\nexport const getBackgroundGradientColors = (theme: GrafanaTheme2): [string, string] => {\n const defaultGradientColors: [string, string] = [GRADIENT_COLORS.PURPLE, GRADIENT_COLORS.ORANGE];\n\n // Check if the theme does not use gradients by default\n if (theme.name.toLowerCase() === 'dark' || theme.name.toLowerCase() === 'light') {\n return defaultGradientColors;\n }\n\n // If the theme uses gradients, extract the colors from the gradient string\n const gradientString = theme.colors.gradients.brandHorizontal;\n const hexColorRegex = /#[0-9A-Fa-f]{6}/g;\n const matches = gradientString.match(hexColorRegex);\n if (!matches || matches.length < 2) {\n // Fallback to default colors if extraction fails\n return defaultGradientColors;\n }\n\n return [matches[0], matches[1]];\n};\n\n/**\n * Creates animation keyframes for a rotating gradient border effect.\n * This is used for loading states in inputs and other components.\n *\n * @param theme - The Grafana theme object\n * @param backgroundColor - The background color to use in the animation\n * @param color1 - First gradient color (optional, defaults to theme purple)\n * @param color2 - Second gradient color (optional, defaults to theme orange)\n * @returns Animation keyframes object for use with @emotion/css keyframes\n *\n * @example\n * ```ts\n * const borderAnimation = keyframes({\n * label: 'border-animation',\n * ...createBorderAnimation(theme, theme.colors.background.primary),\n * });\n * ```\n */\nexport const createBorderAnimation = (\n theme: GrafanaTheme2,\n backgroundColor: string,\n color1?: string,\n color2?: string\n): Record<string, { backgroundImage: string }> => {\n const animationSteps = Array.from({ length: 101 }, (_, i) => i);\n const animationFrames: Record<string, { backgroundImage: string }> = {};\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n const finalColor1 = color1 ?? gradientColor1;\n const finalColor2 = color2 ?? gradientColor2;\n\n for (const step of animationSteps) {\n animationFrames[`${step}%`] = {\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from ${step * 3.6}deg, transparent 60%, ${finalColor1} 80%, ${finalColor2} 100%, transparent 15%)\n `,\n };\n }\n\n return animationFrames;\n};\n","import type { InlineToolRunnable } from '../tools/types';\n\nexport interface InlineAssistantPromptOptions {\n prompt: string;\n agentName?: string;\n agentId?: string;\n systemPrompt?: string;\n tools?: InlineToolRunnable[];\n onStart?: () => void;\n onDelta?: (delta: string) => void;\n onComplete?: (text: string) => void;\n onError?: (error: Error) => void;\n}\n\nexport interface InlineAssistant {\n sendPrompt(options: InlineAssistantPromptOptions): Promise<void>;\n cancel(): void;\n dispose(): void;\n}\n\n// Extend window interface for global registry\ndeclare global {\n interface Window {\n [key: string]: any;\n }\n}\n\nexport type InlineAssistantFactory = (origin: string) => Promise<InlineAssistant>;\nexport type InlineAssistantInitializer = () => Promise<void>;\n\n// Global registry keys for cross-plugin sharing\nconst GLOBAL_FACTORY_KEY = '__grafanaAssistantInlineFactory__';\nconst GLOBAL_INITIALIZER_KEY = '__grafanaAssistantInlineInitializer__';\nconst GLOBAL_INITIALIZATION_PROMISE_KEY = '__grafanaAssistantInlineInitPromise__';\n\nexport function setInlineAssistantFactory(fn: InlineAssistantFactory): void {\n const existing = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (existing && existing !== fn) {\n console.warn('InlineAssistant factory already set; ignoring subsequent setInlineAssistantFactory call');\n return;\n }\n if (!existing) {\n window[GLOBAL_FACTORY_KEY] = fn;\n }\n}\n\n/**\n * Register a lazy initializer that will be called on first use.\n * The plugin code should register this to enable lazy loading of the inline assistant.\n *\n * This uses global storage (window) so that all plugins share the same initializer,\n * regardless of which plugin instance or package version loads first.\n */\nexport function setInlineAssistantInitializer(fn: InlineAssistantInitializer): void {\n const existing = window[GLOBAL_INITIALIZER_KEY] as InlineAssistantInitializer | undefined;\n if (existing && existing !== fn) {\n console.warn('InlineAssistant initializer already set; ignoring subsequent setInlineAssistantInitializer call');\n return;\n }\n if (!existing) {\n window[GLOBAL_INITIALIZER_KEY] = fn;\n }\n}\n\n/**\n * Ensure the inline assistant is initialized. If an initializer is registered,\n * it will be called on first use. Otherwise, checks if factory is already registered.\n *\n * Uses global storage (window) so that initialization is shared across all plugins.\n */\nexport async function ensureInlineAssistantInitialized(): Promise<void> {\n // If factory is already set, we're good\n const factory = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (factory) {\n return;\n }\n\n // If no initializer is registered, throw error\n const initializer = window[GLOBAL_INITIALIZER_KEY] as InlineAssistantInitializer | undefined;\n if (!initializer) {\n throw new Error(\n 'InlineAssistant not initialized. Make sure the Grafana Assistant plugin is loaded and initialized.'\n );\n }\n\n // If initialization is in progress, wait for it\n const existingPromise = window[GLOBAL_INITIALIZATION_PROMISE_KEY] as Promise<void> | null | undefined;\n if (existingPromise) {\n return existingPromise;\n }\n\n // Start initialization\n const initPromise = (async () => {\n try {\n await initializer();\n } catch (err) {\n // Reset on error so retry is possible\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = null;\n throw err;\n }\n })();\n\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = initPromise;\n return initPromise;\n}\n\nexport function getInlineAssistantFactory(): InlineAssistantFactory {\n const factory = window[GLOBAL_FACTORY_KEY] as InlineAssistantFactory | undefined;\n if (!factory) {\n throw new Error('InlineAssistant factory not initialized. Make sure the Grafana Assistant plugin is loaded.');\n }\n return factory;\n}\n","const nestedErrorKeys = ['message', 'error', 'err', 'detail', 'details'] as const;\n\nfunction getStringValue(value: unknown): string | null {\n if (typeof value !== 'string') {\n return null;\n }\n\n const trimmedValue = value.trim();\n return trimmedValue === '' ? null : trimmedValue;\n}\n\nfunction isUnhelpfulErrorMessage(message: string | null): boolean {\n if (!message) {\n return true;\n }\n\n return message === '[object Object]' || message === 'Error' || message === 'Unknown error';\n}\n\nfunction extractNestedErrorMessage(error: unknown, visited = new Set<object>()): string | null {\n const directString = getStringValue(error);\n if (directString) {\n return directString;\n }\n\n if (error instanceof Error) {\n const errorMessage = getStringValue(error.message);\n if (!isUnhelpfulErrorMessage(errorMessage)) {\n return errorMessage;\n }\n\n const nestedErrorMessage = extractNestedErrorMessage(error.cause, visited);\n if (nestedErrorMessage) {\n return nestedErrorMessage;\n }\n\n const ownPropertiesMessage = extractNestedErrorMessage(\n Object.fromEntries(\n Object.entries(error as Error & Record<string, unknown>).filter(([key]) => key !== 'message' && key !== 'name')\n ),\n visited\n );\n if (ownPropertiesMessage) {\n return ownPropertiesMessage;\n }\n\n return errorMessage ?? getStringValue(error.name) ?? null;\n }\n\n if (!error || typeof error !== 'object') {\n return null;\n }\n\n if (visited.has(error)) {\n return null;\n }\n visited.add(error);\n\n const errorRecord = error as Record<string, unknown>;\n\n if ('data' in errorRecord) {\n const nestedDataMessage = extractNestedErrorMessage(errorRecord.data, visited);\n if (nestedDataMessage) {\n return nestedDataMessage;\n }\n }\n\n for (const key of nestedErrorKeys) {\n if (key in errorRecord) {\n const nestedMessage = extractNestedErrorMessage(errorRecord[key], visited);\n if (nestedMessage) {\n return nestedMessage;\n }\n }\n }\n\n const status = errorRecord.status;\n const statusText = getStringValue(errorRecord.statusText);\n if ((typeof status === 'number' || typeof status === 'string') && statusText) {\n return `HTTP ${status}: ${statusText}`;\n }\n\n if (Array.isArray(error)) {\n const nestedMessages = error\n .map((item) => extractNestedErrorMessage(item, visited))\n .filter((message): message is string => Boolean(message));\n\n if (nestedMessages.length > 0) {\n return nestedMessages.join('; ');\n }\n }\n\n return null;\n}\n\n/**\n * Extract error message from backend errors (handles various error formats).\n *\n * @internal SDK-private helper for useInlineAssistant. Not part of the public\n * `@grafana/assistant` surface — do not re-export from `index.ts`.\n */\nexport function extractErrorMessage(error: unknown): string {\n const extractedMessage = extractNestedErrorMessage(error);\n if (extractedMessage) {\n return extractedMessage;\n }\n\n // Objects that expose no message are not serialized: fetch-like errors carry\n // the request URL, headers and body on `config`, which would end up in the\n // messages this helper feeds back to callers.\n if (error && typeof error === 'object') {\n return 'Unknown error';\n }\n\n if (error == null) {\n return 'Unknown error';\n }\n\n return String(error);\n}\n","import { useState, useCallback, useRef, useEffect } from 'react';\nimport type { InlineAssistantOptions, InlineAssistantResult } from './types';\nimport { getInlineAssistantFactory, type InlineAssistant, ensureInlineAssistantInitialized } from './inlineAssistant';\nimport { extractErrorMessage } from '../utils/errorHandling';\n\n/**\n * React hook for inline assistant generation with streaming support.\n *\n * This hook enables generating content (like panel titles or descriptions) inline\n * without opening the assistant sidebar. Each hook instance creates its own chat\n * conversation, so all generations from the same instance are grouped together.\n * Generated content is ephemeral - it won't appear in the user's chat history\n * but will be tracked in the admin UI for analytics.\n *\n * Uses the full BaseMultiStepAgent infrastructure for tool execution and multi-step workflows.\n *\n * The implementation is lazy-loaded on first use to reduce initial bundle size.\n *\n * @example\n * ```typescript\n * function PanelEditor() {\n * const { generate, isGenerating, content, error, reset } = useInlineAssistant();\n * const [title, setTitle] = useState('');\n *\n * const handleGenerate = () => {\n * generate({\n * prompt: 'Generate a panel title for CPU metrics',\n * origin: 'grafana/panel-editor/title',\n * systemPrompt: 'Generate only the title text, no explanation',\n * onComplete: (text) => setTitle(text.trim()),\n * onError: (err) => console.error(err)\n * });\n * };\n *\n * return (\n * <div>\n * <input value={title} onChange={(e) => setTitle(e.target.value)} />\n * <button onClick={handleGenerate} disabled={isGenerating}>\n * {isGenerating ? 'Generating...' : 'Generate with Assistant'}\n * </button>\n * {isGenerating && <div>{content}</div>}\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Using tools with inline assistant\n * import { lokiQueryHandlerTool } from 'agent/tools';\n *\n * function ComponentWithTools() {\n * const { generate } = useInlineAssistant();\n *\n * const handleGenerate = async () => {\n * await generate({\n * prompt: 'Query Loki for error logs from the last hour',\n * origin: 'my-app/component',\n * tools: [lokiQueryHandlerTool],\n * onComplete: (text) => console.log('Generated:', text),\n * });\n * };\n *\n * return <button onClick={handleGenerate}>Generate</button>;\n * }\n * ```\n */\nexport function useInlineAssistant(): InlineAssistantResult {\n const [isGenerating, setIsGenerating] = useState(false);\n const [content, setContent] = useState('');\n const [error, setError] = useState<Error | null>(null);\n const assistantRef = useRef<InlineAssistant | null>(null);\n\n /**\n * Reset error and content state\n */\n const reset = useCallback(() => {\n setError(null);\n setContent('');\n }, []);\n\n /**\n * Cancel the current generation\n */\n const cancel = useCallback(() => {\n if (assistantRef.current) {\n assistantRef.current.cancel();\n }\n setIsGenerating(false);\n }, []);\n\n /**\n * Generate content with the given options\n */\n const generate = useCallback(async (options: InlineAssistantOptions): Promise<void> => {\n // Reset state\n setError(null);\n setContent('');\n setIsGenerating(true);\n\n try {\n // Ensure the inline assistant is initialized (lazy-loads on first use)\n await ensureInlineAssistantInitialized();\n\n const factory = getInlineAssistantFactory();\n\n // Create or reuse assistant for this origin\n if (!assistantRef.current) {\n assistantRef.current = await factory(options.origin);\n }\n\n await assistantRef.current.sendPrompt({\n prompt: options.prompt,\n agentName: options.agentName,\n agentId: options.agentId,\n systemPrompt: options.systemPrompt,\n tools: options.tools,\n onStart: () => {\n setIsGenerating(true);\n },\n onDelta: (delta) => {\n setContent((prev) => prev + delta);\n options.onDelta?.(delta);\n },\n onComplete: (text) => {\n setContent(text);\n setIsGenerating(false);\n options.onComplete?.(text);\n },\n onError: (err) => {\n setError(err);\n setIsGenerating(false);\n options.onError?.(err);\n },\n });\n } catch (err) {\n const error = new Error(extractErrorMessage(err), { cause: err });\n setError(error);\n setIsGenerating(false);\n options.onError?.(error);\n }\n }, []);\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n if (assistantRef.current) {\n assistantRef.current.cancel();\n assistantRef.current.dispose();\n assistantRef.current = null;\n }\n };\n }, []);\n\n return {\n generate,\n isGenerating,\n content,\n error,\n cancel,\n reset,\n };\n}\n","import { useCallback, useEffect, useRef } from 'react';\nimport { useInlineAssistant } from '../../inline/useInlineAssistant';\n\nexport interface UseAIGenerationOptions {\n value: string;\n onChange: (value: string) => void;\n origin: string;\n systemPrompt?: string;\n onComplete?: (text: string) => void;\n onError?: (error: Error) => void;\n onDelta?: (delta: string) => void;\n disabled?: boolean;\n autoGenerate?: boolean;\n streaming?: boolean;\n getUserPrompt?: (textInput: string) => string;\n}\n\nexport function useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n}: UseAIGenerationOptions) {\n const { generate, isGenerating, content, error, reset } = useInlineAssistant();\n const hasAutoGenerated = useRef(false);\n const valueBeforeGeneration = useRef(value);\n const getUserPromptRef = useRef(getUserPrompt);\n getUserPromptRef.current = getUserPrompt;\n\n const displayValue = isGenerating ? (streaming ? content : '') : value;\n const resolvedPrompt = getUserPrompt ? getUserPrompt(value.trim()) : value.trim();\n const isSendDisabled = !resolvedPrompt || disabled || isGenerating;\n\n const doGenerate = useCallback(\n (prompt: string) => {\n valueBeforeGeneration.current = value;\n onChange('');\n reset();\n\n generate({\n prompt,\n origin,\n systemPrompt,\n onDelta,\n onComplete: (text) => {\n onChange(text);\n onComplete?.(text);\n },\n onError: (err) => {\n onChange(valueBeforeGeneration.current);\n onError?.(err);\n },\n });\n },\n [value, onChange, origin, systemPrompt, onDelta, onComplete, onError, generate, reset]\n );\n\n // Auto-generate at most once, on mount, evaluating the props as they are at mount.\n const maybeAutoGenerateRef = useRef<() => void>(() => {});\n maybeAutoGenerateRef.current = () => {\n if (autoGenerate && systemPrompt && !value && !hasAutoGenerated.current && !disabled) {\n hasAutoGenerated.current = true;\n doGenerate(systemPrompt);\n }\n };\n useEffect(() => {\n maybeAutoGenerateRef.current();\n }, []);\n\n const handleGenerate = useCallback(() => {\n const fn = getUserPromptRef.current;\n const prompt = fn ? fn(value.trim()) : value.trim();\n if (!prompt || disabled || isGenerating) {\n return;\n }\n doGenerate(prompt);\n }, [value, disabled, isGenerating, doGenerate]);\n\n return {\n displayValue,\n isSendDisabled,\n handleGenerate,\n isGenerating,\n error,\n };\n}\n","import { useRef, useState } from 'react';\n\nconst GENERATING_PHRASES = [\n 'Generating...',\n 'Brewing...',\n 'Cooking...',\n 'Crunching...',\n 'Phrasing...',\n 'Wording...',\n 'Crafting...',\n 'Composing...',\n 'Drafting...',\n 'Shaping...',\n 'Forming...',\n 'Molding...',\n 'Sketching...',\n 'Whipping up...',\n 'Conjuring...',\n 'Stirring...',\n];\n\n/**\n * Returns a random placeholder phrase while generating, or the provided\n * default placeholder when idle. A new phrase is picked each time generation starts.\n */\nexport function useGeneratingPlaceholder(isGenerating: boolean, defaultPlaceholder: string): string {\n const [phrase, setPhrase] = useState('');\n const wasGenerating = useRef(false);\n\n if (isGenerating && !wasGenerating.current) {\n const next = GENERATING_PHRASES[Math.floor(Math.random() * GENERATING_PHRASES.length)];\n setPhrase(next);\n wasGenerating.current = true;\n return next;\n }\n\n if (!isGenerating) {\n wasGenerating.current = false;\n }\n\n return isGenerating ? phrase : defaultPlaceholder;\n}\n","import type { KeyboardEvent } from 'react';\nimport { Input, IconButton, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport type { AIInputProps } from './types';\nimport { useAIGeneration } from './useAIGeneration';\nimport { useGeneratingPlaceholder } from './useGeneratingPlaceholder';\n\nexport interface AITextInputProps extends AIInputProps {}\n\n/**\n * An AI-powered controlled text input component that uses the Grafana Assistant engine to generate content.\n * Features an integrated send button as well as a gradient border animation while generating.\n */\nexport function AITextInput({\n value,\n onChange,\n placeholder,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n className,\n 'data-testid': dataTestId,\n}: AITextInputProps) {\n const { displayValue, isSendDisabled, handleGenerate, isGenerating, error } = useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled,\n autoGenerate,\n streaming,\n getUserPrompt,\n });\n const styles = useStyles2(getStyles);\n const activePlaceholder = useGeneratingPlaceholder(isGenerating, placeholder ?? 'Ask AI to generate...');\n\n const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n // Cmd/Ctrl + Enter to send\n if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {\n e.preventDefault();\n handleGenerate();\n }\n };\n\n const addonAfter = (\n <IconButton\n name=\"ai-sparkle\"\n onClick={handleGenerate}\n disabled={isSendDisabled}\n tooltip={isSendDisabled ? 'Enter text to generate' : 'Generate with AI'}\n data-testid={dataTestId ? `${dataTestId}-send` : undefined}\n />\n );\n\n return (\n <div className={cx(styles.wrapper, { [styles.animatedWrapper]: isGenerating }, className)} data-testid={dataTestId}>\n <Input\n value={displayValue}\n onKeyDown={handleKeyDown}\n onChange={(e) => onChange(e.currentTarget.value)}\n placeholder={activePlaceholder}\n disabled={disabled || isGenerating}\n suffix={addonAfter}\n invalid={!!error}\n data-testid={dataTestId ? `${dataTestId}-input` : undefined}\n />\n </div>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const borderAnimation = keyframes({\n label: 'ai-input-border-animation',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n return {\n wrapper: css({\n label: 'ai-text-input-wrapper',\n position: 'relative',\n border: '1px solid transparent',\n borderRadius: theme.shape.radius.default,\n cornerShape: 'squircle',\n }),\n animatedWrapper: css({\n label: 'ai-text-input-animated',\n border: '1px solid transparent',\n // Set initial backgroundImage with both gradients so Chrome can animate properly\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n animation: `${borderAnimation} 2s linear infinite`,\n '& input': {\n // Remove the default border from the input when animated wrapper is active\n border: 'none !important',\n },\n }),\n };\n};\n","import type { KeyboardEvent } from 'react';\nimport { TextArea, IconButton, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport type { AIInputProps } from './types';\nimport { useAIGeneration } from './useAIGeneration';\nimport { useGeneratingPlaceholder } from './useGeneratingPlaceholder';\n\nexport interface AITextAreaProps extends AIInputProps {\n /** Number of rows for the textarea */\n rows?: number;\n}\n\n/**\n * An AI-powered controlled textarea component that uses the Grafana Assistant engine to generate content.\n * Features an integrated send button as well as a gradient border animation while generating.\n */\nexport function AITextArea({\n value,\n onChange,\n placeholder,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled = false,\n autoGenerate = false,\n streaming = false,\n getUserPrompt,\n rows = 4,\n className,\n 'data-testid': dataTestId,\n}: AITextAreaProps) {\n const { displayValue, isSendDisabled, handleGenerate, isGenerating, error } = useAIGeneration({\n value,\n onChange,\n origin,\n systemPrompt,\n onComplete,\n onError,\n onDelta,\n disabled,\n autoGenerate,\n streaming,\n getUserPrompt,\n });\n const styles = useStyles2(getStyles);\n const activePlaceholder = useGeneratingPlaceholder(\n isGenerating,\n placeholder ?? 'Ask AI to generate... (Cmd/Ctrl+Enter to send)'\n );\n const effectiveRows = Math.max(rows, 2);\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n // Cmd/Ctrl + Enter to send\n if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {\n e.preventDefault();\n handleGenerate();\n }\n };\n\n return (\n <div\n className={cx(styles.textareaWrapper, { [styles.animatedWrapper]: isGenerating }, className)}\n data-testid={dataTestId}\n >\n <TextArea\n value={displayValue}\n onKeyDown={handleKeyDown}\n onChange={(e) => onChange(e.currentTarget.value)}\n placeholder={activePlaceholder}\n disabled={disabled || isGenerating}\n rows={effectiveRows}\n className={styles.textarea}\n invalid={!!error}\n data-testid={dataTestId ? `${dataTestId}-textarea` : undefined}\n />\n <IconButton\n name=\"ai-sparkle\"\n onClick={handleGenerate}\n disabled={isSendDisabled}\n className={styles.sendButton}\n aria-label=\"Generate with AI\"\n tooltip={isSendDisabled ? 'Enter text to generate' : 'Generate with AI (Cmd/Ctrl+Enter)'}\n data-testid={dataTestId ? `${dataTestId}-send` : undefined}\n />\n </div>\n );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const borderAnimation = keyframes({\n label: 'ai-textarea-border-animation',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n return {\n textareaWrapper: css({\n label: 'ai-textarea-wrapper',\n position: 'relative',\n border: '1px solid transparent',\n borderRadius: theme.shape.radius.default,\n cornerShape: 'squircle',\n }),\n animatedWrapper: css({\n label: 'ai-textarea-animated',\n border: '1px solid transparent',\n // Set initial backgroundImage with both gradients so Chrome can animate properly\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n animation: `${borderAnimation} 2s linear infinite`,\n '& textarea': {\n // Remove the default border from the textarea when animated wrapper is active\n border: 'none !important',\n },\n }),\n textarea: css({\n label: 'ai-textarea',\n // ensures the text does not \"underflow\" the send button\n paddingRight: theme.spacing(4),\n // Keep at least a 2-row visual height even if outer styles try to shrink the control\n minHeight: theme.spacing(6),\n '& textarea': {\n minHeight: theme.spacing(6),\n },\n // Hide scrollbar\n scrollbarWidth: 'none', // Firefox\n '&::-webkit-scrollbar': {\n display: 'none', // Chrome, Safari, Edge\n },\n }),\n sendButton: css({\n label: 'ai-textarea-send',\n position: 'absolute',\n right: theme.spacing(1),\n top: theme.spacing(1),\n }),\n };\n};\n","import { CoreApp, type DataSourceApi, type DataSourceInstanceSettings } from '@grafana/data';\nimport type { DataQuery, DataSourceJsonData } from '@grafana/schema';\nimport type { ComponentSize } from '@grafana/ui';\nimport { createAssistantContextItem } from '../../context';\nimport { useAssistant } from '../../hook';\nimport { OpenAssistantButtonView } from './OpenAssistantButton';\n\nfunction queryIsEmpty(query: DataQuery): boolean {\n const dataQueryProps = ['refId', 'hide', 'key', 'queryType', 'datasource'];\n\n for (const key in query) {\n if (key === 'label') {\n continue;\n }\n if (!dataQueryProps.includes(key)) {\n return false;\n }\n }\n\n return true;\n}\n\nexport interface QueryWithAssistantButtonProps<TQuery extends DataQuery = DataQuery> {\n size?: ComponentSize;\n currentQuery: TQuery;\n queries: TQuery[];\n dataSourceInstanceSettings: DataSourceInstanceSettings;\n app?: CoreApp;\n datasourceApi: DataSourceApi<TQuery, DataSourceJsonData, {}> | null;\n title?: string;\n}\n\nexport function QueryWithAssistantButton<TQuery extends DataQuery = DataQuery>({\n size,\n currentQuery,\n queries,\n dataSourceInstanceSettings,\n app,\n datasourceApi,\n title = 'Query with Assistant',\n}: QueryWithAssistantButtonProps<TQuery>) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n\n const origin = `grafana/query-editor/${dataSourceInstanceSettings.type}/${app ?? CoreApp.Unknown ?? 'unknown'}`;\n\n const hasCurrentQuery = !queryIsEmpty(currentQuery);\n const otherQueries = queries.filter((q) => q.refId !== currentQuery.refId && !queryIsEmpty(q));\n\n const context = [\n createAssistantContextItem('datasource', {\n datasourceUid: dataSourceInstanceSettings.uid,\n }),\n ];\n\n if (hasCurrentQuery) {\n context.push(\n createAssistantContextItem('structured', {\n title: 'Current query',\n data: currentQuery,\n })\n );\n }\n\n if (otherQueries.length > 0) {\n context.push(\n createAssistantContextItem('structured', {\n title: 'Other queries',\n data: {\n queries: otherQueries,\n },\n })\n );\n }\n\n const queryDisplayText =\n hasCurrentQuery && datasourceApi?.getQueryDisplayText ? datasourceApi.getQueryDisplayText(currentQuery) : null;\n\n const isUpdating = !!queryDisplayText;\n const actionText = isUpdating\n ? 'Help me update the current query to answer my questions and provide the insights I need.'\n : 'Help me create a new query to answer my questions and provide the insights I need.';\n\n const codeBlockLines: string[] = [];\n\n if (queryDisplayText) {\n codeBlockLines.push(`Current query: ${queryDisplayText}`);\n }\n\n codeBlockLines.push(`Selected data source: ${dataSourceInstanceSettings.name}`);\n\n const actionableSentence = isUpdating\n ? 'Please describe what you want to change or improve in this query.'\n : \"Please describe what you want to query and what insights you're looking for.\";\n\n const prompt = [actionText, '```', ...codeBlockLines, '```', actionableSentence].join('\\n');\n\n return (\n <OpenAssistantButtonView\n prompt={prompt}\n origin={origin}\n context={context}\n autoSend={false}\n title={title}\n size={size}\n openAssistant={openAssistant}\n />\n );\n}\n","import { useState, useRef, useEffect } from 'react';\n\nconst DEFAULT_EXAMPLE_PROMPTS = [\n 'What does this panel show?',\n 'Explain the trend in this data',\n 'Why is there a spike?',\n 'Add a threshold at 80%',\n 'Change the legend to table mode',\n];\n\nexport { DEFAULT_EXAMPLE_PROMPTS };\n\nexport function useAnimatedPlaceholder(staticPlaceholder: string, prompts: string[], hasUserInput: boolean): string {\n const [display, setDisplay] = useState('');\n const indexRef = useRef(0);\n const charRef = useRef(0);\n const phaseRef = useRef<'typing' | 'pause' | 'erasing'>('typing');\n\n useEffect(() => {\n indexRef.current = 0;\n charRef.current = 0;\n phaseRef.current = 'typing';\n setDisplay('');\n\n if (hasUserInput || prompts.length === 0) {\n return;\n }\n\n const tick = () => {\n const currentPrompt = prompts[indexRef.current];\n\n if (phaseRef.current === 'typing') {\n charRef.current++;\n setDisplay(currentPrompt.slice(0, charRef.current));\n if (charRef.current >= currentPrompt.length) {\n phaseRef.current = 'pause';\n }\n } else if (phaseRef.current === 'pause') {\n phaseRef.current = 'erasing';\n } else if (phaseRef.current === 'erasing') {\n charRef.current--;\n setDisplay(currentPrompt.slice(0, charRef.current));\n if (charRef.current <= 0) {\n phaseRef.current = 'typing';\n indexRef.current = (indexRef.current + 1) % prompts.length;\n }\n }\n };\n\n const getDelay = () => {\n if (phaseRef.current === 'pause') {\n return 800;\n }\n if (phaseRef.current === 'erasing') {\n return 15;\n }\n return 30 + Math.random() * 20;\n };\n\n let timeoutId: ReturnType<typeof setTimeout>;\n const schedule = () => {\n timeoutId = setTimeout(() => {\n tick();\n schedule();\n }, getDelay());\n };\n schedule();\n\n return () => clearTimeout(timeoutId);\n }, [hasUserInput, prompts]);\n\n if (hasUserInput || prompts.length === 0) {\n return staticPlaceholder;\n }\n\n return display;\n}\n","import { type KeyboardEvent, useRef, useState, useEffect, useCallback } from 'react';\nimport { IconButton, Input, useStyles2 } from '@grafana/ui';\nimport { css, cx, keyframes } from '@emotion/css';\nimport type { GrafanaTheme2 } from '@grafana/data';\nimport { reportInteraction } from '@grafana/runtime';\nimport type { ChatContextItem } from '../../context/types';\nimport { useAssistant } from '../../hook';\nimport type { OpenAssistantProps } from '../../sidebar';\nimport { createBorderAnimation, getBackgroundGradientColors } from '../../utils/theme';\nimport { useAnimatedPlaceholder, DEFAULT_EXAMPLE_PROMPTS } from './useAnimatedPlaceholder';\n\nexport interface AssistantPromptCardProps {\n /** Origin of the request for analytics tracking. Should be a structured string using forward slashes. */\n origin: string;\n /** Context items passed to the assistant on submit. Created with `createAssistantContextItem`. */\n context?: ChatContextItem[];\n /** Assistant mode (e.g. 'dashboarding'). Defaults to 'assistant'. */\n mode?: string;\n /** Placeholder text for the input. */\n placeholder?: string;\n /** Example prompts to cycle through as animated placeholder text. Pass an empty array to disable. */\n examplePrompts?: string[];\n /** Called when the card should close (Escape key, close button). */\n onClose?: () => void;\n /** Called after a prompt is submitted, receives the prompt string. */\n onSubmit?: (prompt: string) => void;\n /** Called when the user clicks the card body. */\n onClick?: () => void;\n /** Whether the card border is animated. Defaults to true. */\n animated?: boolean;\n /** Extra CSS class for the root element. */\n className?: string;\n}\n\n/**\n * A prompt card component that opens the Grafana Assistant with a user-typed prompt and context.\n * Renders nothing if the assistant is not available. Positioning is the consumer's responsibility.\n */\nexport function AssistantPromptCard(props: AssistantPromptCardProps) {\n const { isAvailable, openAssistant } = useAssistant();\n if (!isAvailable || !openAssistant) {\n return null;\n }\n return <AssistantPromptCardView {...props} openAssistant={openAssistant} />;\n}\n\nexport interface AssistantPromptCardViewProps extends AssistantPromptCardProps {\n openAssistant: (props: OpenAssistantProps) => void;\n}\n\nexport function AssistantPromptCardView({\n origin,\n context,\n mode,\n placeholder,\n examplePrompts,\n animated = true,\n onClose,\n onSubmit,\n onClick,\n className,\n openAssistant,\n}: AssistantPromptCardViewProps) {\n const [prompt, setPrompt] = useState('');\n const inputRef = useRef<HTMLInputElement>(null);\n const styles = useStyles2(getStyles);\n const resolvedPrompts = examplePrompts ?? (placeholder !== undefined ? [] : DEFAULT_EXAMPLE_PROMPTS);\n const staticPlaceholder = placeholder ?? 'Ask Assistant...';\n const animatedPlaceholder = useAnimatedPlaceholder(staticPlaceholder, resolvedPrompts, prompt.length > 0);\n\n useEffect(() => {\n reportInteraction('grafana_assistant_app_prompt_card_displayed', { from: origin });\n }, [origin]);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: context is an intentional re-trigger to re-focus the input when the context changes\n useEffect(() => {\n const rafId = requestAnimationFrame(() => inputRef.current?.focus());\n return () => cancelAnimationFrame(rafId);\n }, [context]);\n\n const submit = useCallback(\n (text: string) => {\n const trimmed = text.trim();\n if (!trimmed) {\n return;\n }\n\n openAssistant({ prompt: trimmed, context, autoSend: true, origin, mode });\n onSubmit?.(trimmed);\n setPrompt('');\n },\n [openAssistant, context, origin, mode, onSubmit]\n );\n\n const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n submit(prompt);\n }\n\n if (e.key === 'Escape') {\n e.preventDefault();\n onClose?.();\n }\n };\n\n return (\n <div\n className={cx(animated ? styles.card : styles.cardStatic, className)}\n onClick={onClick}\n role=\"search\"\n aria-label={staticPlaceholder}\n data-testid=\"assistant-prompt-card\"\n >\n <div className={styles.inputRow}>\n <Input\n ref={inputRef}\n value={prompt}\n onChange={(e) => setPrompt(e.currentTarget.value)}\n onKeyDown={handleKeyDown}\n placeholder={animatedPlaceholder}\n suffix={\n <IconButton\n name=\"ai-sparkle\"\n onClick={() => submit(prompt)}\n disabled={!prompt.trim()}\n tooltip=\"Send to assistant\"\n aria-label=\"Send to assistant\"\n data-testid=\"assistant-prompt-card-send\"\n />\n }\n data-testid=\"assistant-prompt-card-input\"\n />\n </div>\n </div>\n );\n}\n\nfunction getGlowShadow(theme: GrafanaTheme2) {\n const baseShadow = theme.isDark ? 'rgb(17 18 23)' : 'rgb(245 245 245)';\n return [\n 'rgba(168, 85, 247, 0.25) 3px -1px 20px',\n 'rgba(249, 115, 22, 0.18) -5px 3px 40px',\n 'rgba(168, 85, 247, 0.12) 7px 4px 60px',\n `${baseShadow} 0 6px 30px`,\n ].join(', ');\n}\n\nconst getStyles = (theme: GrafanaTheme2) => {\n const backgroundColor = theme.colors.background.primary;\n const [gradientColor1, gradientColor2] = getBackgroundGradientColors(theme);\n\n const borderAnimation = keyframes({\n label: 'prompt-card-border',\n ...createBorderAnimation(theme, backgroundColor),\n });\n\n const cardBase = {\n label: 'assistant-prompt-card',\n position: 'relative' as const,\n display: 'flex',\n flexDirection: 'column' as const,\n gap: theme.spacing(1),\n padding: theme.spacing(1),\n borderRadius: theme.shape.radius.lg,\n boxShadow: getGlowShadow(theme),\n };\n\n return {\n card: css({\n ...cardBase,\n cornerShape: 'squircle',\n background: backgroundColor,\n border: '1px solid transparent',\n backgroundImage: `\n linear-gradient(${backgroundColor}, ${backgroundColor}),\n conic-gradient(from 0deg, transparent 60%, ${gradientColor1} 80%, ${gradientColor2} 100%, transparent 15%)\n `,\n backgroundOrigin: 'border-box',\n backgroundClip: 'padding-box, border-box',\n [theme.transitions.handleMotion('no-preference')]: {\n animation: `${borderAnimation} 2s linear infinite`,\n },\n }),\n cardStatic: css({\n ...cardBase,\n label: 'assistant-prompt-card-static',\n background: theme.colors.background.elevated,\n border: `1px solid ${theme.colors.border.weak}`,\n }),\n inputRow: css({\n label: 'prompt-card-input-row',\n display: 'flex',\n alignItems: 'center',\n gap: theme.spacing(0.5),\n '& input': {\n border: 'none !important',\n },\n }),\n };\n};\n","import { extractErrorMessage } from '../utils/errorHandling';\nimport type { InvestigationLensError, InvestigationLensErrorCode } from './types';\n\n/**\n * Request passed to the lens implementation registered by the Grafana\n * Assistant plugin.\n */\nexport interface InvestigationLensRequest {\n investigationId: string;\n /** JSON Schema describing the shape of the desired structured view. */\n schema: unknown;\n /** Attribution for the generation, e.g. `'grafana-irm/incident-detail'`. */\n origin: string;\n /** When true, bypass the cached result and regenerate. */\n refresh?: boolean;\n}\n\n/**\n * The lens implementation provided by the Grafana Assistant plugin. Resolves\n * with data conforming to the request's schema, or rejects with an error\n * carrying an {@link InvestigationLensErrorCode} `code` property.\n */\nexport type InvestigationLensImplementation = (request: InvestigationLensRequest) => Promise<unknown>;\nexport type InvestigationLensInitializer = () => Promise<void>;\n\nconst LENS_ERROR_CODES: readonly InvestigationLensErrorCode[] = [\n 'unavailable',\n 'no_report',\n 'permission_denied',\n 'validation_failed',\n 'llm_error',\n];\n\nfunction isLensErrorCode(value: unknown): value is InvestigationLensErrorCode {\n return typeof value === 'string' && (LENS_ERROR_CODES as readonly string[]).includes(value);\n}\n\n/**\n * Typed error the lens implementation throws to signal a specific failure\n * mode. Consumers should not need this class — the hook converts failures to\n * plain {@link InvestigationLensError} values. Conversion is structural (it\n * reads the `code` property), so it works even when the host plugin and the\n * assistant plugin bundle different copies of this package.\n */\nexport class InvestigationLensRequestError extends Error {\n constructor(\n public readonly code: InvestigationLensErrorCode,\n message: string\n ) {\n super(message);\n this.name = 'InvestigationLensRequestError';\n }\n}\n\n/** Converts any thrown value into a plain, typed lens error. */\nexport function toInvestigationLensError(err: unknown): InvestigationLensError {\n if (err && typeof err === 'object' && 'code' in err && isLensErrorCode(err.code)) {\n return { code: err.code, message: extractErrorMessage(err) };\n }\n return { code: 'llm_error', message: extractErrorMessage(err) };\n}\n\n// Extend window interface for global registry\ndeclare global {\n interface Window {\n [key: string]: any;\n }\n}\n\n// Global registry keys for cross-plugin sharing: all plugins (and all copies\n// of this package) must observe the same implementation, regardless of which\n// bundle loads first.\nconst GLOBAL_IMPLEMENTATION_KEY = '__grafanaAssistantLensImplementation__';\nconst GLOBAL_INITIALIZER_KEY = '__grafanaAssistantLensInitializer__';\nconst GLOBAL_INITIALIZATION_PROMISE_KEY = '__grafanaAssistantLensInitPromise__';\n\nexport function setInvestigationLensImplementation(fn: InvestigationLensImplementation): void {\n const existing = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (existing && existing !== fn) {\n console.warn('InvestigationLens implementation already set; ignoring subsequent call');\n return;\n }\n if (!existing) {\n window[GLOBAL_IMPLEMENTATION_KEY] = fn;\n }\n}\n\n/**\n * Register a lazy initializer that is called on first use. The Grafana\n * Assistant plugin registers this at bootstrap so the heavy implementation\n * loads only when a consumer actually requests a lens view.\n */\nexport function setInvestigationLensInitializer(fn: InvestigationLensInitializer): void {\n const existing = window[GLOBAL_INITIALIZER_KEY] as InvestigationLensInitializer | undefined;\n if (existing && existing !== fn) {\n console.warn('InvestigationLens initializer already set; ignoring subsequent call');\n return;\n }\n if (!existing) {\n window[GLOBAL_INITIALIZER_KEY] = fn;\n }\n}\n\n/**\n * Ensure the lens implementation is initialized, invoking the registered\n * initializer on first use. Throws an `unavailable` lens error when no\n * initializer is registered (assistant plugin missing or too old).\n */\nexport async function ensureInvestigationLensInitialized(): Promise<void> {\n const implementation = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (implementation) {\n return;\n }\n\n const initializer = window[GLOBAL_INITIALIZER_KEY] as InvestigationLensInitializer | undefined;\n if (!initializer) {\n throw new InvestigationLensRequestError(\n 'unavailable',\n 'Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.'\n );\n }\n\n // If initialization is in progress, wait for it\n const existingPromise = window[GLOBAL_INITIALIZATION_PROMISE_KEY] as Promise<void> | null | undefined;\n if (existingPromise) {\n return existingPromise;\n }\n\n const initPromise = (async () => {\n try {\n await initializer();\n } catch (err) {\n // Reset on error so retry is possible\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = null;\n throw err;\n }\n })();\n\n window[GLOBAL_INITIALIZATION_PROMISE_KEY] = initPromise;\n return initPromise;\n}\n\nexport function getInvestigationLensImplementation(): InvestigationLensImplementation {\n const implementation = window[GLOBAL_IMPLEMENTATION_KEY] as InvestigationLensImplementation | undefined;\n if (!implementation) {\n throw new InvestigationLensRequestError(\n 'unavailable',\n 'Investigation lens is not available. Make sure the Grafana Assistant plugin is installed and up to date.'\n );\n }\n return implementation;\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { FromSchema, JSONSchema } from 'json-schema-to-ts';\n\nimport {\n ensureInvestigationLensInitialized,\n getInvestigationLensImplementation,\n toInvestigationLensError,\n} from './investigationLens';\nimport type {\n InvestigationLensState,\n UseInvestigationThroughLensOptions,\n UseInvestigationThroughLensResult,\n} from './types';\n\n/**\n * Derives a structured, LLM-generated view of an investigation's report,\n * shaped by a caller-provided JSON Schema. Declarative: generation runs on\n * mount and whenever the schema or investigation changes; results are cached\n * by the Grafana Assistant plugin per (investigation, schema, report\n * content), so remounts don't regenerate for an unchanged report.\n *\n * Field `description`s are per-field instructions to the model — that is the\n * steering mechanism. Deterministic facts (ids, titles, statuses, timestamps,\n * links) are provided to the model verbatim and copied through rather than\n * generated, so reserve schema fields for genuine synthesis from the report.\n *\n * Declare the schema with `as const` to get a fully typed `data` inferred\n * from the schema (via `json-schema-to-ts`):\n *\n * @example\n * ```typescript\n * const schema = {\n * type: 'object',\n * properties: {\n * headline: {\n * type: 'string',\n * description: 'One sentence describing the incident for an executive audience, max 80 characters.',\n * },\n * followUps: {\n * type: 'array',\n * description: 'Concrete follow-up actions to prevent recurrence.',\n * items: {\n * type: 'object',\n * properties: {\n * action: { type: 'string' },\n * urgency: { type: 'string', enum: ['now', 'this-week', 'backlog'] },\n * },\n * required: ['action', 'urgency'],\n * additionalProperties: false,\n * },\n * },\n * },\n * required: ['headline', 'followUps'],\n * additionalProperties: false,\n * } as const;\n *\n * function IncidentReview({ investigationId }: { investigationId: string }) {\n * const lens = useInvestigationThroughLens(schema, investigationId, {\n * origin: 'grafana-irm/incident-review',\n * });\n *\n * if (lens.status === 'loading') return <Spinner />;\n * if (lens.status === 'error') return <span>{lens.error.message}</span>;\n * // lens.data.followUps[0].urgency is 'now' | 'this-week' | 'backlog'\n * return <h3>{lens.data.headline}</h3>;\n * }\n * ```\n *\n * Requires the Grafana Assistant plugin; when it is missing or outdated the\n * hook resolves to an `error` state with code `unavailable` — it never throws\n * into the host's render.\n *\n * Note on `enabled` gating: re-enabling serves cached results by default. If\n * the report may have changed while the hook was disabled — e.g. `enabled`\n * gates on the report streaming — set `refreshOnEnable: true` so the fetch\n * triggered by the false → true transition bypasses the caches once.\n */\nexport function useInvestigationThroughLens<S extends JSONSchema, T = FromSchema<S>>(\n schema: S,\n investigationId: string,\n options: UseInvestigationThroughLensOptions\n): UseInvestigationThroughLensResult<T> {\n const { origin, enabled = true, refreshOnEnable = false } = options;\n const [state, setState] = useState<InvestigationLensState<T>>({ status: 'loading' });\n\n // Key generation on the schema's content, not its identity: consumers\n // typically declare the schema inline, so the object is recreated every\n // render even though it never changes.\n const schemaJson = useMemo(() => JSON.stringify(schema), [schema]);\n\n // refresh() bumps the generation to re-run generation with a cache bypass.\n // The bypass is one-shot: the ref records which generation already consumed\n // it, so a later run triggered by a schema/investigation change (same\n // generation, different deps) does not inherit `refresh: true`.\n const [generation, setGeneration] = useState({ id: 0, bypassCache: false });\n const consumedGenerationRef = useRef(0);\n\n // For refreshOnEnable: tracks whether the previous effect run was enabled,\n // so the run triggered by a false → true transition bypasses caches exactly\n // once. Initialized to the mount-time value so a first mount with\n // `enabled: true` takes the normal cached path.\n const wasEnabledRef = useRef(enabled);\n\n const refresh = useCallback(() => {\n setGeneration((g) => ({ id: g.id + 1, bypassCache: true }));\n }, []);\n\n useEffect(() => {\n const wasEnabled = wasEnabledRef.current;\n wasEnabledRef.current = enabled;\n\n if (!enabled) {\n setState({ status: 'loading' });\n return;\n }\n\n let cancelled = false;\n const bypassFromRefresh = generation.bypassCache && consumedGenerationRef.current !== generation.id;\n consumedGenerationRef.current = generation.id;\n const bypassCache = bypassFromRefresh || (refreshOnEnable && !wasEnabled);\n setState({ status: 'loading' });\n\n (async () => {\n try {\n await ensureInvestigationLensInitialized();\n const implementation = getInvestigationLensImplementation();\n const data = await implementation({\n investigationId,\n schema: JSON.parse(schemaJson),\n origin,\n refresh: bypassCache,\n });\n if (!cancelled) {\n setState({ status: 'success', data: data as T });\n }\n } catch (err) {\n if (!cancelled) {\n setState({ status: 'error', error: toInvestigationLensError(err) });\n }\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [schemaJson, investigationId, origin, enabled, refreshOnEnable, generation]);\n\n return { ...state, refresh };\n}\n","/**\n * Lightweight semantic version comparison utility.\n * Replaces semver library to reduce bundle size.\n *\n * Supports standard semver format: major.minor.patch[-prerelease][+build]\n * Pre-release versions are considered lower than release versions.\n * Build metadata is ignored for comparison purposes.\n */\n\ninterface ParsedVersion {\n major: number;\n minor: number;\n patch: number;\n prerelease?: string;\n}\n\n/**\n * Parses a semantic version string into its components.\n * @param version - Version string (e.g., \"1.2.3\", \"0.0.2-ga\", \"1.2.3+build\")\n * @returns Parsed version object or null if invalid\n */\nfunction parseVersion(version: string): ParsedVersion | null {\n // Remove build metadata (everything after +)\n const withoutBuild = version.split('+')[0];\n\n // Split into version and prerelease parts\n const parts = withoutBuild.split('-');\n const versionPart = parts[0];\n const prerelease = parts.length > 1 ? parts.slice(1).join('-') : undefined;\n\n // Parse major.minor.patch\n const numbers = versionPart.split('.').map(Number);\n if (numbers.length !== 3 || numbers.some(isNaN)) {\n return null;\n }\n\n return {\n major: numbers[0],\n minor: numbers[1],\n patch: numbers[2],\n prerelease,\n };\n}\n\n/**\n * Compares two semantic versions.\n * @param v1 - First version string\n * @param v2 - Second version string\n * @returns -1 if v1 < v2, 0 if v1 === v2, 1 if v1 > v2, or null if either version is invalid\n */\nfunction compareVersions(v1: string, v2: string): number | null {\n const parsed1 = parseVersion(v1);\n const parsed2 = parseVersion(v2);\n\n if (!parsed1 || !parsed2) {\n return null;\n }\n\n // Compare major version\n if (parsed1.major !== parsed2.major) {\n return parsed1.major > parsed2.major ? 1 : -1;\n }\n\n // Compare minor version\n if (parsed1.minor !== parsed2.minor) {\n return parsed1.minor > parsed2.minor ? 1 : -1;\n }\n\n // Compare patch version\n if (parsed1.patch !== parsed2.patch) {\n return parsed1.patch > parsed2.patch ? 1 : -1;\n }\n\n // If both have prerelease, compare lexicographically\n // If only one has prerelease, it's considered lower\n if (parsed1.prerelease && parsed2.prerelease) {\n if (parsed1.prerelease === parsed2.prerelease) {\n return 0;\n }\n return parsed1.prerelease > parsed2.prerelease ? 1 : -1;\n }\n\n if (parsed1.prerelease && !parsed2.prerelease) {\n return -1; // v1 has prerelease, v2 doesn't, so v1 < v2\n }\n\n if (!parsed1.prerelease && parsed2.prerelease) {\n return 1; // v1 doesn't have prerelease, v2 does, so v1 > v2\n }\n\n return 0; // Both are release versions with same major.minor.patch\n}\n\n/**\n * Checks if version v1 is greater than version v2.\n * @param v1 - First version string\n * @param v2 - Second version string\n * @returns true if v1 > v2, false otherwise (including if either version is invalid)\n */\nexport function isVersionGreaterThan(v1: string, v2: string): boolean {\n const result = compareVersions(v1, v2);\n return result === 1;\n}\n","import { getBackendSrv } from '@grafana/runtime';\nimport { lastValueFrom } from 'rxjs';\nimport { useState, useEffect } from 'react';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\nimport { isVersionGreaterThan } from './versionCompare';\nimport type { components } from './settings.gen';\n\n/**\n * The type of terms that apply to a tenant.\n * - 'msa': Master Service Agreement - only requires acceptance, no version checking\n * - 'termsAndConditions': Full terms and conditions - requires acceptance AND version checking\n */\nexport type TermsType = components['schemas']['TermsAndConditionsResponse']['termsType'];\n\n/**\n * Internal result type for fetching terms data.\n */\ninterface TermsCheckResult {\n accepted: boolean;\n termsType: TermsType;\n}\n\n/**\n * Event name that is dispatched when terms and conditions are accepted.\n * Other components can listen to this event to refresh their UI.\n */\nexport const TERMS_AND_CONDITIONS_REFRESH_EVENT = 'grafana-assistant-terms-and-conditions-refresh';\n\n/**\n * Internal function that fetches and evaluates terms data.\n * Returns both the acceptance status and the terms type.\n */\nasync function fetchTermsData(): Promise<TermsCheckResult> {\n const backendSrv = getBackendSrv();\n // No appSubUrl prefix: BackendSrv strips the leading `/` so Grafana's\n // `<base href>` adds the subpath (see grafana-assistant-app/issues/6109).\n const apiUrl = `/api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v1/settings/terms`;\n\n const response = await lastValueFrom(\n backendSrv.fetch({\n url: apiUrl,\n method: 'GET',\n showErrorAlert: false,\n })\n );\n\n // The API returns { status: \"success\", data: { ... } }, so we need to access response.data.data\n const responseBody = response.data as { data: components['schemas']['TermsAndConditionsResponse'] };\n const termsData = responseBody.data;\n\n const termsAccepted = termsData.acceptedTermsAndConditions ?? false;\n const acceptedVersion = termsData.acceptedVersion;\n const currentVersion = termsData.version;\n const termsType = termsData.termsType;\n\n // For MSA, we only check if terms are accepted\n if (termsType === 'msa') {\n return { accepted: termsAccepted, termsType };\n }\n\n // Check if terms are not accepted, or if no version was recorded or current version is missing\n if (!termsAccepted || !acceptedVersion || !currentVersion) {\n return { accepted: false, termsType };\n }\n\n // Check if the current version is newer than the accepted version\n const needsAcceptance = isVersionGreaterThan(currentVersion, acceptedVersion);\n return { accepted: termsAccepted && !needsAcceptance, termsType };\n}\n\n/**\n * Checks whether terms and conditions are accepted and up-to-date.\n * This function verifies that:\n * 1. Terms have been accepted\n * 2. The accepted version matches or exceeds the current version\n *\n * @returns A promise that resolves to `true` if terms are accepted and up-to-date, `false` otherwise\n * @throws Error if the API call fails\n *\n * @example\n * ```typescript\n * import { checkTerms } from '@grafana/assistant';\n *\n * const accepted = await checkTerms();\n * if (!accepted) {\n * // Show terms acceptance UI\n * console.log('Terms need to be accepted');\n * }\n * ```\n */\nexport async function checkTerms(): Promise<boolean> {\n try {\n const result = await fetchTermsData();\n return result.accepted;\n } catch (error) {\n // If API call fails, throw the error so callers can handle it\n throw new Error(`Failed to check terms requirements: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\n * React hook to check terms and conditions acceptance status.\n * Automatically fetches terms data on mount and re-fetches when terms change\n * (via TERMS_AND_CONDITIONS_REFRESH_EVENT).\n *\n * @returns An object containing whether terms are accepted, the terms type, loading state, and error state\n *\n * @example\n * ```typescript\n * import { useTerms } from '@grafana/assistant';\n *\n * function MyComponent() {\n * const { accepted, termsType, loading, error } = useTerms();\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return <div>Terms accepted</div>;\n * }\n * ```\n */\nexport function useTerms() {\n const [accepted, setAccepted] = useState<boolean>(false);\n const [termsType, setTermsType] = useState<TermsType | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n async function fetchTerms() {\n try {\n setLoading(true);\n setError(null);\n const result = await fetchTermsData();\n setAccepted(result.accepted);\n setTermsType(result.termsType);\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'Failed to check terms';\n setError(errorMessage);\n setAccepted(false);\n setTermsType(null);\n } finally {\n setLoading(false);\n }\n }\n\n fetchTerms();\n\n // Listen for the refresh event to re-fetch when terms change\n const handleTermsRefresh = () => {\n fetchTerms();\n };\n document.addEventListener(TERMS_AND_CONDITIONS_REFRESH_EVENT, handleTermsRefresh);\n return () => {\n document.removeEventListener(TERMS_AND_CONDITIONS_REFRESH_EVENT, handleTermsRefresh);\n };\n }, []);\n\n return {\n accepted,\n termsType,\n loading,\n error,\n };\n}\n","import type { ToolInvokeOptions, ToolOutput, JSONSchema, JsonObject, InlineToolRunnable } from './types';\n\n/**\n * Creates a tool with the given implementation, schema, and metadata.\n * This is a zod-free implementation that accepts JSON Schema directly and a validation function.\n *\n * @param func The function implementation for the tool\n * @param options Tool configuration options\n * @returns A tool object that can be used in the agent\n */\nexport function createTool<T>(\n func: (input: T, options: ToolInvokeOptions) => Promise<ToolOutput>,\n options: {\n name: string;\n description: string;\n inputSchema: JSONSchema; // JSON Schema directly - no zod dependency!\n validate: (input: JsonObject) => T; // Validation function - replaces zod.parse()\n metadata?: {\n explainer?: (input?: T) => string;\n [key: string]: any;\n };\n verboseParsingErrors?: boolean;\n responseFormat?: 'content_and_artifact' | string;\n }\n): InlineToolRunnable {\n const { explainer, ...metadata } = options.metadata ?? {};\n const toolObj: InlineToolRunnable = {\n name: options.name,\n description: options.description,\n inputSchema: options.inputSchema,\n metadata: explainer\n ? {\n ...metadata,\n explainer: (input: JsonObject) => explainer(input as T),\n }\n : metadata,\n responseFormat: options.responseFormat,\n verboseParsingErrors: options.verboseParsingErrors,\n async invoke(input: JsonObject, invokeOptions: ToolInvokeOptions): Promise<ToolOutput> {\n try {\n if (invokeOptions.signal?.aborted) {\n throw new Error(`Tool ${options.name} execution was aborted`);\n }\n\n // Use the provided validation function instead of zod.parse()\n const parsedInput = options.validate(input);\n const functionPromise = func(parsedInput, invokeOptions);\n const promises = [functionPromise];\n\n if (invokeOptions.signal) {\n promises.push(\n new Promise((_, reject) => {\n invokeOptions.signal?.addEventListener(\n 'abort',\n () => {\n reject(new Error(`Tool ${options.name} execution was aborted`));\n },\n { once: true }\n );\n })\n );\n }\n\n // If we have a timeout, add a promise to handle it\n if (invokeOptions.timeout && invokeOptions.timeout > 0) {\n promises.push(\n new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error(`Tool ${options.name} execution timed out after ${invokeOptions.timeout}ms`));\n }, invokeOptions.timeout);\n })\n );\n }\n\n // Race the function promise against the abort and timeout promises\n return Promise.race(promises);\n } catch (error) {\n // Handle parsing errors and wrap them in ToolError\n if (options.verboseParsingErrors) {\n console.error(`Error invoking tool ${options.name}:`, error, input);\n }\n throw error;\n }\n },\n };\n\n return toolObj;\n}\n","import { getBackendSrv } from '@grafana/runtime';\nimport { lastValueFrom } from 'rxjs';\nimport { useState, useEffect, useCallback } from 'react';\nimport { ASSISTANT_PLUGIN_ID } from '../plugin';\n\n/**\n * Event name dispatched when limits are updated via SSE.\n * Other components can listen to this event to get real-time updates.\n */\nexport const LIMITS_UPDATED_EVENT = 'grafana-assistant-limits-updated';\n\n/**\n * Detail payload for the LIMITS_UPDATED_EVENT custom event.\n */\nexport interface LimitsUpdatedEventDetail {\n count: number;\n limit: number;\n}\n\n/**\n * Result type for limits data.\n */\nexport interface LimitsData {\n /** Current prompt count for the month */\n count: number;\n /** Monthly prompt limit (0 = unlimited) */\n limit: number;\n /** Current month in YYYY-MM format */\n month: string;\n /** Whether the limit has been reached */\n isLimitReached: boolean;\n}\n\n/**\n * Internal function that fetches limits data from the API.\n */\nasync function fetchLimitsData(): Promise<LimitsData> {\n const backendSrv = getBackendSrv();\n // No appSubUrl prefix: BackendSrv strips the leading `/` so Grafana's\n // `<base href>` adds the subpath (see grafana-assistant-app/issues/6109).\n const apiUrl = `/api/plugins/${ASSISTANT_PLUGIN_ID}/resources/api/v1/usage/limits/prompt`;\n\n const response = await lastValueFrom(\n backendSrv.fetch({\n url: apiUrl,\n method: 'GET',\n showErrorAlert: false,\n })\n );\n\n // The API returns { status: \"success\", data: { total, limit, month } }\n const responseBody = response.data as { data: { total: number; limit: number; month: string } };\n const limitsData = responseBody.data;\n\n const count = limitsData.total ?? 0;\n const limit = limitsData.limit ?? 0;\n const month = limitsData.month ?? '';\n\n return {\n count,\n limit,\n month,\n isLimitReached: limit > 0 && count >= limit,\n };\n}\n\n/**\n * Checks whether the user has reached their monthly prompt limit.\n *\n * @returns A promise that resolves to `true` if limits are reached, `false` otherwise\n * @throws Error if the API call fails\n *\n * @example\n * ```typescript\n * import { checkLimits } from '@grafana/assistant';\n *\n * const data = await checkLimits();\n * if (data.isLimitReached) {\n * console.log('Monthly limit reached');\n * }\n * ```\n */\nexport async function checkLimits(): Promise<LimitsData> {\n try {\n return await fetchLimitsData();\n } catch (error) {\n throw new Error(`Failed to check limits: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\n * React hook to check user prompt limits.\n * Automatically fetches limits data on mount and listens to real-time updates\n * via the LIMITS_UPDATED_EVENT custom event.\n *\n * @returns An object containing limit data, loading state, error state, and refetch function\n *\n * @example\n * ```typescript\n * import { useLimits } from '@grafana/assistant';\n *\n * function MyComponent() {\n * const { count, limit, isLimitReached, loading, error, refetch } = useLimits();\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * if (isLimitReached) return <div>Monthly limit reached ({count}/{limit})</div>;\n * return <div>Prompts used: {count}/{limit || 'unlimited'}</div>;\n * }\n * ```\n */\nexport function useLimits() {\n const [count, setCount] = useState<number>(0);\n const [limit, setLimit] = useState<number>(0);\n const [month, setMonth] = useState<string>('');\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchLimits = useCallback(async () => {\n try {\n setLoading(true);\n setError(null);\n const result = await fetchLimitsData();\n setCount(result.count);\n setLimit(result.limit);\n setMonth(result.month);\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'Failed to fetch limits';\n setError(errorMessage);\n setCount(0);\n setLimit(0);\n setMonth('');\n } finally {\n setLoading(false);\n }\n }, []);\n\n // Fetch on mount\n useEffect(() => {\n fetchLimits();\n }, [fetchLimits]);\n\n // Listen for real-time updates via custom event\n useEffect(() => {\n const handleLimitsUpdate = (event: Event) => {\n const customEvent = event as CustomEvent<LimitsUpdatedEventDetail>;\n if (customEvent.detail) {\n setCount(customEvent.detail.count);\n setLimit(customEvent.detail.limit);\n // Clear any previous error since we received valid data via SSE\n setError(null);\n }\n };\n\n window.addEventListener(LIMITS_UPDATED_EVENT, handleLimitsUpdate);\n\n return () => {\n window.removeEventListener(LIMITS_UPDATED_EVENT, handleLimitsUpdate);\n };\n }, []);\n\n // Calculate isLimitReached based on current state\n const isLimitReached = limit > 0 && count >= limit;\n\n return {\n count,\n limit,\n month,\n isLimitReached,\n loading,\n error,\n refetch: fetchLimits,\n };\n}\n","import { BusEventWithPayload } from '@grafana/data';\nimport { getAppEvents } from '@grafana/runtime';\n\nexport interface K6SetScriptContentPayload {\n scriptContent: string;\n}\n\n/**\n * Event published by grafana-assistant-app to inject a script into the currently open k6 editor.\n * The k6 app subscribes to this event and updates the editor content in place,\n * avoiding a full page navigation.\n *\n * @example\n * ```typescript\n * import { onK6SetScriptContent } from '@grafana/assistant';\n *\n * const unsubscribe = onK6SetScriptContent(({ scriptContent }) => {\n * editorRef.current?.setValue(scriptContent);\n * });\n *\n * // On unmount\n * unsubscribe();\n * ```\n */\nexport class K6SetScriptContentEvent extends BusEventWithPayload<K6SetScriptContentPayload> {\n static type = 'grafana-assistant:k6-set-script-content';\n}\n\n/**\n * Subscribe to k6 set-script-content events emitted by grafana-assistant-app.\n * Returns an unsubscribe function.\n */\nexport function onK6SetScriptContent(callback: (payload: K6SetScriptContentPayload) => void): () => void {\n const subscription = getAppEvents().subscribe(K6SetScriptContentEvent, (event) => {\n callback(event.payload);\n });\n return () => subscription.unsubscribe();\n}\n","import type { PluginExtensionAddedFunctionConfig } from '@grafana/data';\nimport type { ComponentType, ReactNode } from 'react';\n\n/**\n * Extension point id consumed by the Grafana Assistant.\n *\n * A contributing app plugin registers a manifest function against this target via\n * `AppPlugin.addFunction()` (declared under `extensions.addedFunctions` in its `plugin.json`).\n * The Assistant discovers registrations with `usePluginFunctions()` and invokes each function to\n * obtain the plugin's {@link AssistantExtensionManifest}.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport const ASSISTANT_EXTENSION_POINT = 'grafana-assistant-app/extension/v1';\n\n/**\n * Props passed to a `tool-card` chit component registered via {@link ChitContribution}.\n *\n * These are the normalized props every tool row in the Assistant chat track receives; a\n * registered card renders in place of the generic tool card with the same information.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface ToolChitProps {\n /** The fully namespaced tool name that produced this card. */\n toolName: string;\n /** The tool call input, as sent to the tool. */\n input: unknown;\n /** The tool result, once available. `undefined` while the tool is still running. */\n result: unknown;\n /** Execution state of the tool call. */\n status: 'running' | 'success' | 'error';\n}\n\n/**\n * A contribution to the Assistant chat track (\"chits\"): either a rich card keyed by tool name,\n * or a widget detector that renders inline widgets from message text.\n *\n * - `tool-card`: renders in place of the generic tool card for the listed tool names. A plugin\n * may only register cards for tools it owns (tool names are namespaced by the tool pipeline\n * and checked against the contributing plugin id).\n * - `widget`: extends the Assistant's widget detector chain. Built-in detectors run first,\n * plugin detectors after; the first match wins.\n *\n * Component and function references are the only non-JSON-serializable parts of a manifest —\n * refer to {@link AssistantExtensionManifest} for the serializability contract.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport type ChitContribution =\n | {\n kind: 'tool-card';\n /** Fully namespaced tool names this card renders for. Must be owned by the contributing plugin. */\n toolNames: string[];\n /** The card component, rendered inside a per-chit error boundary. */\n component: ComponentType<ToolChitProps>;\n }\n | {\n kind: 'widget';\n /** Returns true when this widget should render for the given message text. */\n detect: (text: string, meta: unknown) => boolean;\n /** Renders the widget for a matched message. */\n render: (text: string, meta: unknown) => ReactNode;\n };\n\n/**\n * The artifact file node handed to plugin artifact renderers and toolbars.\n *\n * Intentionally minimal and forward-compatible: renderers must treat this as the complete\n * artifact surface and must not fetch artifact content from anywhere else.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantArtifactNode {\n /** File path of the artifact in the conversation's artifact filesystem. */\n path: string;\n /** The artifact kind extension, e.g. `.grafana-k6-app.test`. */\n ext: string;\n /** The artifact content. Shape is owned by the contributing plugin's `validate` contract. */\n data: unknown;\n /**\n * Monotonically increasing per-artifact write counter. Increments on every write to this\n * artifact. Suitable for memoization keys, cache-busting, and change detection. NOT a\n * timestamp — carries no wall-clock meaning.\n */\n revision: number;\n}\n\n/**\n * Read-only handle over the conversation's artifact filesystem, mirroring the host's read\n * surface.\n *\n * The handle spans the whole conversation: it includes other plugins' and built-in artifacts by\n * design — composition is the point. There is no write surface; artifact writes happen only\n * through the Assistant's validated `write_artifact` path. Renderers must treat this handle as\n * the only artifact-content source besides their own node.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantArtifactFs {\n /** All artifacts in the conversation, in stable path order. */\n list(): AssistantArtifactNode[];\n /** Read one artifact by exact normalized path. */\n read(path: string): AssistantArtifactNode | undefined;\n /** Whether an artifact exists at the path. */\n has(path: string): boolean;\n}\n\n/**\n * Props passed to a plugin artifact renderer.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface ArtifactRendererProps {\n /** The artifact node to render. */\n node: AssistantArtifactNode;\n /** Read-only handle over the conversation's artifact filesystem. */\n fs: AssistantArtifactFs;\n}\n\n/**\n * Props passed to an optional plugin artifact toolbar.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface ArtifactToolbarProps {\n /** The artifact node the toolbar acts on. */\n node: AssistantArtifactNode;\n /** Read-only handle over the conversation's artifact filesystem. */\n fs: AssistantArtifactFs;\n}\n\n/**\n * A plugin-contributed artifact kind for the Assistant canvas.\n *\n * The `ext` is double-dot namespaced as `.{pluginId}.{kind}`, where `pluginId` is your full,\n * exact plugin id — for example `.grafana-k6-app.test`, not a shortened slug. This keeps plugin\n * kinds out of the built-in single-dot space and keeps orphaned artifacts attributable to their\n * owning plugin without a live registry, since the plugin id is readable from the artifact path.\n *\n * Everything except `validate`, `renderer`, and `toolbar` is JSON-serializable — refer to\n * {@link AssistantExtensionManifest} for the serializability contract.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface ArtifactKindContribution {\n /** Artifact extension in the form `.{pluginId}.{kind}` (exact plugin id), double-dot namespaced. */\n ext: `.${string}.${string}`;\n /** Human-readable label shown on artifact tabs and cards. */\n label: string;\n /** Icon name shown next to the label. */\n icon: string;\n /**\n * Tab promotion order, ascending: LOWER values are promoted and rendered earlier. Built-in\n * kinds always occupy the lowest values (`.report` = 0, `.dashboard` = 1, `.query` = 2) and\n * cannot be jumped — the host clamps this value to non-negative and offsets it into a range\n * after every built-in, so it only orders your kinds relative to other plugin-contributed\n * kinds. Ties break by most recently updated artifact first; kinds with no live registration\n * sort last.\n */\n tabPriority: number;\n /** Write-time content contract: returns true when `data` is valid for this kind. */\n validate(data: unknown): boolean;\n /** Renders the artifact in the canvas. Receives the artifact node and a read-only conversation filesystem handle. */\n renderer: ComponentType<ArtifactRendererProps>;\n /** Optional toolbar rendered above the artifact. */\n toolbar?: ComponentType<ArtifactToolbarProps>;\n /** Optional one-line hint teaching the model how to write artifacts of this kind. */\n promptHint?: string;\n}\n\n/**\n * Environment conditions evaluated by the Assistant when deciding whether a contributed mode is\n * available. Unknown condition strings fail closed (the mode is hidden).\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport type PromptContributionAvailability = 'not-oss' | 'not-trial';\n\n/**\n * A plugin-contributed Assistant mode (system prompt variant).\n *\n * The contribution is exposed in the mode picker as `${pluginId}:${modeId}` and its prompt text\n * is always rendered inside an attributed `<plugin_contribution>` wrapper, subject to a\n * per-plugin byte budget and an assistant-side allowlist.\n *\n * All fields are JSON-serializable — refer to {@link AssistantExtensionManifest} for the\n * serializability contract.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface PromptContribution {\n /** Plugin-local mode id. Exposed to users as `${pluginId}:${modeId}`. */\n modeId: string;\n /** Human-readable mode label shown in the mode picker. */\n label: string;\n /** Short description of the mode shown in the mode picker. */\n description: string;\n /** One line describing when the Assistant should suggest this mode. */\n whenToUse: string;\n /**\n * How `prompt` composes with the base system prompt.\n *\n * - `prepend` / `append`: `prompt` is added before / after the base guidance, which is\n * otherwise kept intact.\n * - `replace`: the rest of the base guidance is dropped, but the Assistant's identity section\n * is ALWAYS retained — the composed prompt is the identity block, then the current-mode\n * block, then the attributed plugin body. A plugin never controls or replaces the\n * Assistant's identity.\n *\n * Prefer `prepend` or `append` unless the mode is a genuinely self-contained specialist that\n * needs none of the base guidance.\n */\n compose: 'prepend' | 'append' | 'replace';\n /**\n * The prompt snippet (`prepend`/`append`) or specialist body (`replace`). With `replace`, this\n * body is composed after the Assistant's always-retained identity section — refer to\n * {@link PromptContribution.compose}.\n */\n prompt: string;\n /** Optional hidden first message sent when the mode is selected on a fresh chat. */\n initialMessage?: string;\n /**\n * Whether the mode can be switched to mid-conversation. Defaults to true. When false the mode\n * is entry-point only: listed on fresh chats and reachable via deep links, but hidden from the\n * picker mid-conversation and excluded from mode suggestions.\n */\n switchable?: boolean;\n /** Environment conditions evaluated by the Assistant; all must hold for the mode to show. */\n availability?: PromptContributionAvailability[];\n /** Names of the plugin's own tools scoped exclusively to this mode. */\n modeToolNames?: string[];\n /** Optional icon name shown in the mode picker. */\n icon?: string;\n /** Optional feature state badge shown next to the mode label. */\n featureState?: 'preview' | 'experimental';\n}\n\n/**\n * A proposed first message shown on fresh chats (empty conversations) on the Assistant chat\n * surfaces, visibly attributed to the contributing plugin.\n *\n * Selecting a starter sends `message` as an ordinary, user-visible user message. Starters are\n * never auto-sent, never hidden, and never modify the system prompt — which is why they are part\n * of the v1 chat-content surface (master flag + per-plugin kill switch only; no allowlist, no\n * prompt-contributions flag). Contrast with {@link PromptContribution.initialMessage}, which is\n * hidden, auto-sent on mode selection, and ships behind the v2 prompt-contributions flag.\n *\n * Enforced bounds (entries beyond a cap are dropped whole by the Assistant): max 3 starters per\n * plugin, `message` at most 500 characters, `label` at most 80 characters.\n *\n * Starters are pure data (fully JSON-serializable), making them ideal for the future static\n * `plugin.json` transport — refer to {@link AssistantExtensionManifest} for the serializability\n * contract.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantStarter {\n /** Optional short label shown on the starter; defaults to the message itself. Max 80 characters. */\n label?: string;\n /** The user message sent, visibly and as-is, when the starter is selected. Max 500 characters. */\n message: string;\n}\n\n/**\n * The manifest a Grafana app plugin returns from its assistant extension function to contribute\n * chits, starters, artifact kinds, and prompt/mode variants to the Grafana Assistant.\n *\n * Serializability contract: every field of the manifest is JSON-serializable **except**\n * component and function references (`ChitContribution.component` / `detect` / `render`,\n * `ArtifactKindContribution.validate` / `renderer` / `toolbar`). This constraint is deliberate:\n * it enables a future transport where the static halves of a manifest are declared in signed\n * `plugin.json` metadata and only component references are resolved at runtime.\n *\n * Unknown fields and unknown contribution kinds are ignored by the Assistant, so manifests\n * produced by newer SDK versions degrade gracefully on older Assistant versions.\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport interface AssistantExtensionManifest {\n /** Manifest schema version. Always 1 for this SDK version. */\n schemaVersion: 1;\n /** Chat-track contributions: tool cards and widget detectors. */\n chits?: ChitContribution[];\n /**\n * Proposed first messages offered on fresh chats, attributed to the plugin. Max 3.\n *\n * When to use which: use `provideQuestions` to suggest questions on pages YOUR plugin already\n * runs on (URL-scoped, page-context registry, requires your module to be loaded on that page,\n * unattributed); use manifest `starters` for proposed first messages in the Assistant's fresh\n * chats ANYWHERE (extension-point transport, loads your module on demand, plugin-attributed,\n * governed by the Assistant's per-plugin kill switch and caps, statically declarable in the\n * future). They intentionally share the same rendering surface and send path.\n */\n starters?: AssistantStarter[];\n /** Canvas artifact kinds. */\n artifactKinds?: ArtifactKindContribution[];\n /** Assistant mode / system prompt contributions. */\n promptContributions?: PromptContribution[];\n}\n\n/**\n * Builds the `AppPlugin.addFunction()` configuration that registers an assistant extension\n * manifest with the Grafana Assistant.\n *\n * Purity contract: the registered function MUST be pure and stable — invoked any number of\n * times, it must return the same (deep-equal) manifest for the same environment. The Assistant\n * dedups deep-equal results; an unstable manifest churns downstream consumers and invalidates\n * prompt caching. Gate on your own feature flags *before* registering rather than returning a\n * varying manifest.\n *\n * @example\n * ```typescript\n * import { AppPlugin } from '@grafana/data';\n * import { getAssistantExtensionConfig } from '@grafana/assistant';\n *\n * export const plugin = new AppPlugin().addFunction(\n * getAssistantExtensionConfig({\n * schemaVersion: 1,\n * chits: [{ kind: 'tool-card', toolNames: ['myplugin_run_check'], component: MyToolCard }],\n * })\n * );\n * ```\n *\n * @experimental This API is under active development and may change in future releases.\n */\nexport function getAssistantExtensionConfig(\n manifest: AssistantExtensionManifest\n): PluginExtensionAddedFunctionConfig<() => AssistantExtensionManifest> {\n return {\n title: 'assistant-extension',\n description: 'Contributes chits, starters, artifact kinds, and prompt contributions to the Grafana Assistant.',\n targets: [ASSISTANT_EXTENSION_POINT],\n fn: () => manifest,\n };\n}\n"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","hash","input","i","length","charCodeAt","toString","NodeData","constructor","params","text","this","id","type","bypassLimits","formatForLLM","codeElementIds","data","name","equals","other","StructuredNodeData","super","JSON","stringify","require","GLOBAL_REGISTRY_KEY","REGISTRY_CHANGE_EVENT","LEGACY_REGISTRY_UPDATE_EVENT","LEGACY_REGISTRY_REMOVE_EVENT","LEGACY_REGISTRY_SYNC_EVENT","getPageContextRegistry","window","setPageContextRegistry","newRegistry","skipLegacyEvents","dispatchEvent","CustomEvent","detail","registry","legacyBridgeInitialized","providePageContext","urlPattern","initialContext","pattern","RegExp","source","trim","console","warn","registration","generateRegistrationId","context","setContext","newContext","currentRegistry","index","findIndex","reg","unregister","filter","_","addEventListener","event","existingIndex","r","incomingRegistry","Array","isArray","currentIds","Set","map","newRegistrations","has","empty","useProvidePageContext","setContextRef","useRef","undefined","pendingUpdate","isModified","useEffect","current","contextToUse","useCallback","getActivePageContext","currentUrl","activeContext","matchesUrlPattern","push","usePageContext","options","allowQuestions","allowComponents","location","useLocationService","initialPathname","getLocation","pathname","pageContext","setPageContext","useState","currentPathnameRef","updateContext","handleRegistryChange","locationSub","getLocationObservable","subscribe","loc","unsubscribe","removeEventListener","filteredContext","item","node","prefix","Date","now","Math","random","slice","url","test","regexPattern","replace","ComponentNodeData","namespace","keys","components","join","prompt","usePageComponents","useMemo","allComponents","componentData","componentName","component","entries","provideComponents","flags","createAssistantContextItem","setter","newComponents","newPrompt","globalComponents","promptContext","DashboardNodeData","dashboardUid","dashboardTitle","folderUid","folderTitle","FolderNodeData","DatasourceNodeData","datasourceUid","datasourceType","datasourceName","img","uid","EntityNodeData","scope","env","site","Boolean","title","hidden","icon","entityType","properties","LabelNameNodeData","labelName","LabelValueNodeData","labelValue","operator","getDatasourceMeta","datasourceInstance","getDataSourceSrv","getInstanceSettings","meta","info","logos","small","defaultIcons","datasource","label_name","label_value","dashboard","dashboard_folder","unknown","structured","entity","skill","nodeData","error","createContextByType","defaultTitle","getTitleFromContextNode","getImgFromContextNode","navigable","selectable","occurrences","SkillNodeData","skillId","skillName","provideQuestions","initialQuestions","registrationId","convertQuestionsToContext","questions","question","setQuestions","newQuestions","useProvideQuestions","useQuestions","convertContextToQuestions","contextItems","CALLBACK_EXTENSION_POINT","newFunctionNamespace","functions","getExposeAssistantFunctionsConfig","namespaces","targets","fn","ASSISTANT_PLUGIN_ID","ASSISTANT_PLUGIN_TITLE","MAX_RETRY_ATTEMPTS","INITIAL_RETRY_DELAY","MAX_RETRY_DELAY","isAssistantAvailable","getObservablePluginLinks","defer","extensionPointId","pipe","links","some","link","pluginId","throwError","retry","count","delay","retryCount","errorMessage","message","toLowerCase","includes","delayMs","min","timer","catchError","of","OpenExtensionSidebarEvent","BusEventWithPayload","CloseExtensionSidebarEvent","BusEventBase","ToggleExtensionSidebarEvent","openAssistant","props","reportInteraction","from","origin","componentTitle","getAppEvents","publish","openExtensionSidebar","initialPrompt","initialAutoSend","autoSend","initialMode","mode","chatId","appendContext","closeAssistant","closeExtensionSidebar","toggleAssistant","toggleExtensionSidebar","useAssistant","available","setAvailable","sub","isAvailable","isLoading","OpenAssistantButton","OpenAssistantButtonView","size","iconOnlyButton","onClick","styles","useStyles2","getStyles","IconButton","variant","className","tooltip","Button","fill","button","theme","baseBackground","colors","secondary","main","elevatedBackground","emphasize","underlyingColor","background","canvas","outerRadius","shape","radius","default","innerRadius","gradientBorderLayer","content","position","inset","borderRadius","cornerShape","zIndex","pointerEvents","solidBackgroundLayer","transition","css","label","width","maxWidth","isolation","border","padding","spacing","defaultDropdownButtonWidths","sm","md","lg","OpenAssistantSplitButton","OpenAssistantSplitButtonView","menuItems","dropdownButtonWidth","hasMenuItems","resolvedDropdownButtonWidth","wrapperContent","wrapper","ButtonGroup","buttonGroup","cx","segmentButton","mainButtonSplit","mainButtonSolo","Dropdown","overlay","dropdownButton","style","minWidth","Tooltip","dividerColor","weak","display","gap","overflow","boxShadow","borderTopLeftRadius","borderBottomLeftRadius","borderTopRightRadius","borderBottomRightRadius","alignItems","justifyContent","margin","getBackgroundGradientColors","defaultGradientColors","matches","gradients","brandHorizontal","match","createBorderAnimation","backgroundColor","color1","color2","animationSteps","animationFrames","gradientColor1","gradientColor2","finalColor1","finalColor2","step","backgroundImage","GLOBAL_FACTORY_KEY","GLOBAL_INITIALIZER_KEY","GLOBAL_INITIALIZATION_PROMISE_KEY","setInlineAssistantFactory","existing","setInlineAssistantInitializer","async","ensureInlineAssistantInitialized","initializer","Error","existingPromise","initPromise","err","getInlineAssistantFactory","factory","nestedErrorKeys","getStringValue","trimmedValue","extractNestedErrorMessage","visited","directString","nestedErrorMessage","cause","fromEntries","add","errorRecord","nestedDataMessage","nestedMessage","status","statusText","nestedMessages","extractErrorMessage","String","useInlineAssistant","isGenerating","setIsGenerating","setContent","setError","assistantRef","reset","cancel","generate","sendPrompt","agentName","agentId","systemPrompt","tools","onStart","onDelta","delta","prev","onComplete","onError","dispose","useAIGeneration","onChange","disabled","autoGenerate","streaming","getUserPrompt","hasAutoGenerated","valueBeforeGeneration","getUserPromptRef","displayValue","isSendDisabled","doGenerate","maybeAutoGenerateRef","handleGenerate","GENERATING_PHRASES","useGeneratingPlaceholder","defaultPlaceholder","phrase","setPhrase","wasGenerating","next","floor","AITextInput","placeholder","dataTestId","activePlaceholder","addonAfter","animatedWrapper","Input","onKeyDown","e","metaKey","ctrlKey","preventDefault","currentTarget","suffix","invalid","primary","borderAnimation","keyframes","backgroundOrigin","backgroundClip","animation","AITextArea","rows","effectiveRows","max","textareaWrapper","TextArea","textarea","sendButton","paddingRight","minHeight","scrollbarWidth","right","top","queryIsEmpty","query","dataQueryProps","QueryWithAssistantButton","currentQuery","queries","dataSourceInstanceSettings","app","datasourceApi","CoreApp","Unknown","hasCurrentQuery","otherQueries","q","refId","queryDisplayText","getQueryDisplayText","isUpdating","actionText","codeBlockLines","actionableSentence","DEFAULT_EXAMPLE_PROMPTS","AssistantPromptCard","AssistantPromptCardView","examplePrompts","animated","onClose","onSubmit","setPrompt","inputRef","staticPlaceholder","animatedPlaceholder","prompts","hasUserInput","setDisplay","indexRef","charRef","phaseRef","timeoutId","schedule","setTimeout","currentPrompt","tick","clearTimeout","useAnimatedPlaceholder","rafId","requestAnimationFrame","focus","cancelAnimationFrame","submit","trimmed","card","cardStatic","role","inputRow","ref","shiftKey","getGlowShadow","isDark","cardBase","flexDirection","transitions","handleMotion","elevated","LENS_ERROR_CODES","InvestigationLensRequestError","code","toInvestigationLensError","GLOBAL_IMPLEMENTATION_KEY","setInvestigationLensImplementation","setInvestigationLensInitializer","ensureInvestigationLensInitialized","getInvestigationLensImplementation","implementation","useInvestigationThroughLens","schema","investigationId","enabled","refreshOnEnable","state","setState","schemaJson","generation","setGeneration","bypassCache","consumedGenerationRef","wasEnabledRef","refresh","g","wasEnabled","cancelled","bypassFromRefresh","parse","parseVersion","version","parts","split","versionPart","prerelease","numbers","Number","isNaN","major","minor","patch","TERMS_AND_CONDITIONS_REFRESH_EVENT","fetchTermsData","backendSrv","getBackendSrv","apiUrl","termsData","lastValueFrom","fetch","method","showErrorAlert","termsAccepted","acceptedTermsAndConditions","acceptedVersion","currentVersion","termsType","accepted","needsAcceptance","v1","v2","parsed1","parsed2","compareVersions","checkTerms","useTerms","setAccepted","setTermsType","loading","setLoading","fetchTerms","result","handleTermsRefresh","document","createTool","func","explainer","metadata","toolObj","description","inputSchema","responseFormat","verboseParsingErrors","invoke","invokeOptions","signal","aborted","parsedInput","validate","promises","Promise","reject","once","timeout","race","LIMITS_UPDATED_EVENT","fetchLimitsData","limitsData","total","limit","month","isLimitReached","checkLimits","useLimits","setCount","setLimit","setMonth","fetchLimits","handleLimitsUpdate","customEvent","refetch","K6SetScriptContentEvent","onK6SetScriptContent","callback","subscription","payload","ASSISTANT_EXTENSION_POINT","getAssistantExtensionConfig","manifest"],"sourceRoot":""}