"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    ApToolCall: ()=>ApToolCall
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const react_namespaceObject = require("@lingui/react");
const CheckCircle_namespaceObject = require("@mui/icons-material/CheckCircle");
var CheckCircle_default = /*#__PURE__*/ __webpack_require__.n(CheckCircle_namespaceObject);
const Error_namespaceObject = require("@mui/icons-material/Error");
var Error_default = /*#__PURE__*/ __webpack_require__.n(Error_namespaceObject);
const KeyboardArrowDown_namespaceObject = require("@mui/icons-material/KeyboardArrowDown");
var KeyboardArrowDown_default = /*#__PURE__*/ __webpack_require__.n(KeyboardArrowDown_namespaceObject);
const KeyboardArrowRight_namespaceObject = require("@mui/icons-material/KeyboardArrowRight");
var KeyboardArrowRight_default = /*#__PURE__*/ __webpack_require__.n(KeyboardArrowRight_namespaceObject);
const material_namespaceObject = require("@mui/material");
const apollo_core_namespaceObject = require("@uipath/apollo-core");
var apollo_core_default = /*#__PURE__*/ __webpack_require__.n(apollo_core_namespaceObject);
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const external_ApToolCall_types_cjs_namespaceObject = require("./ApToolCall.types.cjs");
const ToolCallSection_cjs_namespaceObject = require("./components/ToolCallSection.cjs");
const traceIconUtils_cjs_namespaceObject = require("./utils/traceIconUtils.cjs");
const Container = (0, material_namespaceObject.styled)('div')({
    fontSize: apollo_core_default().FontFamily.FontMSize,
    padding: apollo_core_default().Spacing.SpacingS,
    color: 'var(--color-foreground-de-emp)',
    maxWidth: '100%',
    boxSizing: 'border-box'
});
const Header = (0, material_namespaceObject.styled)('div')({
    display: 'flex',
    alignItems: 'center',
    padding: apollo_core_default().Spacing.SpacingMicro,
    borderRadius: apollo_core_default().Spacing.SpacingMicro,
    marginBottom: apollo_core_default().Spacing.SpacingXs,
    cursor: 'pointer',
    '&:hover': {
        backgroundColor: 'var(--color-background-hover)'
    },
    '&:focus-visible': {
        outline: `${apollo_core_default().Border.BorderThickS} solid var(--color-focus-indicator)`,
        outlineOffset: '-1px'
    }
});
const LoadingSpinner = (0, material_namespaceObject.styled)(material_namespaceObject.CircularProgress)({
    width: `${apollo_core_default().Spacing.SpacingM} !important`,
    height: `${apollo_core_default().Spacing.SpacingM} !important`,
    marginRight: apollo_core_default().Spacing.SpacingXs
});
const ErrorIconStyled = (0, material_namespaceObject.styled)(Error_default())({
    width: apollo_core_default().Spacing.SpacingM,
    marginRight: apollo_core_default().Spacing.SpacingXs,
    color: 'var(--color-error-icon)',
    fill: 'var(--color-error-icon)'
});
const SuccessIconStyled = (0, material_namespaceObject.styled)(CheckCircle_default())({
    width: apollo_core_default().Spacing.SpacingM,
    marginRight: apollo_core_default().Spacing.SpacingXs,
    color: 'var(--color-success-icon)',
    fill: 'var(--color-success-icon)'
});
const ArrowIcon = (0, material_namespaceObject.styled)(KeyboardArrowDown_default(), {
    shouldForwardProp: (prop)=>'expanded' !== prop
})(({ expanded })=>({
        marginLeft: apollo_core_default().Spacing.SpacingXs,
        transform: expanded ? 'rotate(180deg)' : 'none'
    }));
const TraceArrowIcon = (0, material_namespaceObject.styled)(KeyboardArrowRight_default(), {
    shouldForwardProp: (prop)=>'expanded' !== prop
})(({ expanded })=>({
        transition: 'transform 0.2s ease',
        transform: expanded ? 'rotate(90deg)' : 'none',
        flexShrink: 0
    }));
const SectionsContainer = (0, material_namespaceObject.styled)('div', {
    shouldForwardProp: (prop)=>'expanded' !== prop
})(({ expanded })=>({
        marginLeft: apollo_core_default().Spacing.SpacingS,
        paddingLeft: apollo_core_default().Spacing.SpacingS,
        borderLeft: `${apollo_core_default().Border.BorderThickS} solid var(--color-border)`,
        maxHeight: expanded ? 'fit-content' : '0',
        overflow: 'hidden',
        transition: 'max-height 0.2s ease',
        maxWidth: `calc(100% - ${apollo_core_default().Spacing.SpacingBase})`,
        boxSizing: 'border-box',
        '&:focus-visible': {
            outline: `${apollo_core_default().Border.BorderThickS} solid var(--color-focus-indicator)`,
            outlineOffset: '-1px'
        }
    }));
const TraceItemsContainer = (0, material_namespaceObject.styled)('div')({
    marginTop: apollo_core_default().Spacing.SpacingMicro,
    paddingLeft: apollo_core_default().Spacing.SpacingMicro
});
const TraceItemContainer = (0, material_namespaceObject.styled)('div', {
    shouldForwardProp: (prop)=>'clickable' !== prop
})(({ clickable })=>({
        display: 'flex',
        alignItems: 'center',
        gap: apollo_core_default().Spacing.SpacingXs,
        marginBottom: apollo_core_default().Spacing.SpacingS,
        ...clickable && {
            cursor: 'pointer',
            borderRadius: apollo_core_default().Spacing.SpacingMicro,
            '&:hover': {
                backgroundColor: 'var(--color-background-hover)'
            }
        }
    }));
const TraceName = (0, material_namespaceObject.styled)('span')({
    display: 'inline-block',
    flex: 1
});
const ArrowPlaceholder = (0, material_namespaceObject.styled)('span')({
    width: '20px',
    flexShrink: 0,
    display: 'inline-block'
});
const TraceIcon = (0, material_namespaceObject.styled)('span')({
    display: 'inline-flex',
    alignItems: 'center',
    flexShrink: 0,
    width: '16px',
    height: '16px',
    '& svg': {
        width: '100%',
        height: '100%'
    }
});
function getVisibleChildren(node) {
    const result = [];
    for (const child of node.children ?? [])if ('llmCall' !== child.data.type && 'agentOutput' !== child.data.type) result.push(child);
    return result;
}
const TraceItem = ({ child, depth = 0 })=>{
    const visibleChildren = (0, external_react_namespaceObject.useMemo)(()=>getVisibleChildren(child), [
        child
    ]);
    const hasChildren = visibleChildren.length > 0;
    const [itemExpanded, setItemExpanded] = (0, external_react_namespaceObject.useState)(false);
    const iconSvg = (0, external_react_namespaceObject.useMemo)(()=>(0, traceIconUtils_cjs_namespaceObject.getSpanIconSvg)(child.data), [
        child.data
    ]);
    const handleKeyDown = (event)=>{
        if ('Enter' === event.key || ' ' === event.key) {
            event.preventDefault();
            setItemExpanded((prev)=>!prev);
        }
    };
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(jsx_runtime_namespaceObject.Fragment, {
        children: [
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(TraceItemContainer, {
                clickable: hasChildren,
                style: {
                    paddingLeft: depth > 0 ? `calc(${depth} * ${apollo_core_default().Spacing.SpacingM})` : void 0
                },
                onClick: hasChildren ? ()=>setItemExpanded((prev)=>!prev) : void 0,
                role: hasChildren ? 'button' : void 0,
                tabIndex: hasChildren ? 0 : void 0,
                onKeyDown: hasChildren ? handleKeyDown : void 0,
                "aria-expanded": hasChildren ? itemExpanded : void 0,
                children: [
                    hasChildren ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(TraceArrowIcon, {
                        fontSize: "small",
                        expanded: itemExpanded
                    }) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ArrowPlaceholder, {}),
                    iconSvg && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(TraceIcon, {
                        dangerouslySetInnerHTML: {
                            __html: iconSvg
                        }
                    }),
                    /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(TraceName, {
                        children: child.name.replace('_', ' ')
                    })
                ]
            }),
            hasChildren && itemExpanded && visibleChildren.map((c)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(TraceItemContent, {
                    child: c,
                    depth: depth + 1
                }, c.key))
        ]
    });
};
const TraceItemContent = /*#__PURE__*/ external_react_default().memo(TraceItem);
const ApToolCall = /*#__PURE__*/ external_react_default().forwardRef((props, ref)=>{
    const { span, toolName, input, output, isError, startTime, endTime, displayMode } = props;
    const { _ } = (0, react_namespaceObject.useLingui)();
    const [toolCallExpanded, setToolCallExpanded] = (0, external_react_namespaceObject.useState)(false);
    const [expandedSections, setExpandedSections] = (0, external_react_namespaceObject.useState)({
        input: false,
        traces: false,
        escalation: true,
        output: false,
        errors: false
    });
    const getAttributes = (0, external_react_namespaceObject.useCallback)((data)=>{
        let attrs = data.attributes;
        if ('string' == typeof attrs) try {
            attrs = JSON.parse(attrs);
        } catch  {
            return {};
        }
        return attrs || {};
    }, []);
    const taskUrls = (0, external_react_namespaceObject.useMemo)(()=>{
        if (!span) return [];
        const urls = [];
        let attributes = span.data.attributes;
        if ('string' == typeof attributes) try {
            attributes = JSON.parse(attributes);
        } catch  {
            attributes = {};
        }
        if ('object' == typeof attributes && attributes?.taskUrl) urls.push({
            taskUrl: attributes.taskUrl,
            status: span.data.status || null
        });
        const visitedSpans = new Set();
        const childStack = [
            ...span.children || []
        ];
        while(childStack.length > 0){
            const child = childStack.pop();
            if (!child?.data?.id) continue;
            if (visitedSpans.has(child.data.id)) continue;
            visitedSpans.add(child.data.id);
            let childAttributes = child.data.attributes;
            if ('string' == typeof childAttributes) try {
                childAttributes = JSON.parse(childAttributes);
            } catch  {
                childAttributes = {};
            }
            if ('object' == typeof childAttributes && childAttributes?.taskUrl) urls.push({
                taskUrl: childAttributes.taskUrl,
                status: child.data.status || null
            });
            if (child.children?.length) childStack.push(...child.children);
        }
        return urls;
    }, [
        span
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (taskUrls.length > 0) setToolCallExpanded(true);
    }, [
        taskUrls
    ]);
    const hasChildSpanWithError = (0, external_react_namespaceObject.useMemo)(()=>{
        if (!span) return false;
        const visitedSpans = new Set();
        const childStack = [
            ...span.children || []
        ];
        while(childStack.length > 0){
            const child = childStack.pop();
            if (!child?.data?.id) continue;
            if (visitedSpans.has(child.data.id)) continue;
            visitedSpans.add(child.data.id);
            if ('error' === child.data.status) return true;
            if (child.children?.length) childStack.push(...child.children);
        }
        return false;
    }, [
        span
    ]);
    const getStatus = (0, external_react_namespaceObject.useMemo)(()=>{
        if (input && !output && void 0 === isError) return 'loading';
        if (input && (output || void 0 !== isError)) return isError ? 'error' : 'success';
        if (span) {
            if ('unset' === span.data.status) return 'loading';
            if ('error' === span.data.status || hasChildSpanWithError) return 'error';
            if ('ok' === span.data.status) return 'success';
        }
        return null;
    }, [
        input,
        output,
        isError,
        span,
        hasChildSpanWithError
    ]);
    const renderStatusIcon = (0, external_react_namespaceObject.useMemo)(()=>{
        switch(getStatus){
            case 'loading':
                return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(LoadingSpinner, {});
            case 'error':
                return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ErrorIconStyled, {});
            case 'success':
                return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SuccessIconStyled, {});
            default:
                return null;
        }
    }, [
        getStatus
    ]);
    const getStatusText = (0, external_react_namespaceObject.useMemo)(()=>{
        const status = getStatus;
        const toolCallName = toolName?.replace(/_/g, ' ') || span?.name?.replace('Tool call - ', '').replace(/_/g, ' ') || 'tool';
        if ('loading' === status) return `Running '${toolCallName}'`;
        const endTimeStamp = endTime || span?.data?.endTime;
        const startTimeStamp = startTime || span?.data?.startTime;
        const duration = endTimeStamp && startTimeStamp ? (new Date(endTimeStamp).getTime() - new Date(startTimeStamp).getTime()) / 1000 : 0;
        return `Ran '${toolCallName}' for ${duration.toFixed(2)} seconds`;
    }, [
        getStatus,
        toolName,
        span,
        startTime,
        endTime
    ]);
    const handleKeyDown = (0, external_react_namespaceObject.useCallback)((event)=>{
        if ('Enter' === event.key || ' ' === event.key) {
            event.preventDefault();
            setToolCallExpanded(!toolCallExpanded);
        }
    }, [
        toolCallExpanded
    ]);
    if (displayMode === external_ApToolCall_types_cjs_namespaceObject.ConversationalDisplayModeTypes.ToolNameOnly) return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(Container, {
        ref: ref,
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(Header, {
            children: [
                renderStatusIcon,
                " ",
                getStatusText
            ]
        })
    });
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(Container, {
        ref: ref,
        children: [
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(Header, {
                onClick: ()=>setToolCallExpanded(!toolCallExpanded),
                onKeyDown: handleKeyDown,
                role: "button",
                tabIndex: 0,
                "aria-expanded": toolCallExpanded,
                children: [
                    renderStatusIcon,
                    " ",
                    getStatusText,
                    /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ArrowIcon, {
                        fontSize: "small",
                        expanded: toolCallExpanded
                    })
                ]
            }),
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(SectionsContainer, {
                expanded: toolCallExpanded,
                "aria-hidden": !toolCallExpanded,
                ...!toolCallExpanded && {
                    inert: true
                },
                children: [
                    (input || span && getAttributes(span.data).arguments) && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ToolCallSection_cjs_namespaceObject.ToolCallSection, {
                        type: "input",
                        title: _({
                            id: 'tool-call.input'
                        }),
                        isExpanded: expandedSections['input'],
                        onToggle: ()=>setExpandedSections((prev)=>({
                                    ...prev,
                                    input: !prev['input']
                                })),
                        data: input || (span ? getAttributes(span.data).arguments : void 0)
                    }),
                    displayMode === external_ApToolCall_types_cjs_namespaceObject.ConversationalDisplayModeTypes.FullTrace && span?.children?.length ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ToolCallSection_cjs_namespaceObject.ToolCallSection, {
                        type: "traces",
                        title: _({
                            id: 'tool-call.traces'
                        }),
                        isExpanded: expandedSections['traces'],
                        onToggle: ()=>setExpandedSections((prev)=>({
                                    ...prev,
                                    traces: !prev['traces']
                                })),
                        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(TraceItemsContainer, {
                            children: getVisibleChildren(span).map((child)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(TraceItemContent, {
                                    child: child,
                                    depth: 0
                                }, child.key))
                        })
                    }) : null,
                    taskUrls.length > 0 ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ToolCallSection_cjs_namespaceObject.ToolCallSection, {
                        type: "escalation",
                        title: _({
                            id: 'tool-call.escalation'
                        }),
                        isExpanded: expandedSections['escalation'],
                        onToggle: ()=>setExpandedSections((prev)=>({
                                    ...prev,
                                    escalation: !prev['escalation']
                                })),
                        data: {
                            taskUrls
                        }
                    }) : null,
                    (isError && output || span && getAttributes(span.data).error) && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ToolCallSection_cjs_namespaceObject.ToolCallSection, {
                        type: "errors",
                        title: _({
                            id: 'tool-call.errors'
                        }),
                        isExpanded: expandedSections['errors'],
                        onToggle: ()=>setExpandedSections((prev)=>({
                                    ...prev,
                                    errors: !prev['errors']
                                })),
                        data: isError && output ? output : span ? getAttributes(span.data).error : {}
                    }),
                    (!isError && output || span && getAttributes(span.data).result) && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ToolCallSection_cjs_namespaceObject.ToolCallSection, {
                        type: "output",
                        title: _({
                            id: 'tool-call.output'
                        }),
                        isExpanded: expandedSections['output'],
                        onToggle: ()=>setExpandedSections((prev)=>({
                                    ...prev,
                                    output: !prev['output']
                                })),
                        data: output || (span ? getAttributes(span.data).result : {}) || {}
                    })
                ]
            })
        ]
    });
});
ApToolCall.displayName = 'ApToolCall';
exports.ApToolCall = __webpack_exports__.ApToolCall;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "ApToolCall"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
