"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__, {
    hasResourceNode: ()=>hasResourceNode,
    useNodes: ()=>useNodes,
    useSelectedNodeId: ()=>useSelectedNodeId,
    AgentFlowProvider: ()=>AgentFlowProvider,
    useAgentFlowStore: ()=>useAgentFlowStore,
    useSelectedNode: ()=>useSelectedNode,
    useEdges: ()=>useEdges,
    createAgentFlowStore: ()=>createAgentFlowStore
});
const react_cjs_namespaceObject = require("../../../xyflow/react.cjs");
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const external_zustand_namespaceObject = require("zustand");
const external_types_cjs_namespaceObject = require("../../../types.cjs");
const auto_layout_cjs_namespaceObject = require("../../../utils/auto-layout.cjs");
const props_helpers_cjs_namespaceObject = require("../../../utils/props-helpers.cjs");
const resource_operations_cjs_namespaceObject = require("../../../utils/resource-operations.cjs");
const BaseCanvas_constants_cjs_namespaceObject = require("../../BaseCanvas/BaseCanvas.constants.cjs");
const external_AgentFlow_constants_cjs_namespaceObject = require("../AgentFlow.constants.cjs");
const createVirtualNodes = (agentNode)=>{
    const agentWidth = agentNode.measured?.width ?? agentNode.width ?? 320;
    const agentHeight = agentNode.measured?.height ?? agentNode.height ?? 140;
    const agentCenterX = agentNode.position.x + agentWidth / 2;
    return [
        {
            id: '__virtual_top__',
            type: 'resource',
            position: {
                x: agentCenterX - auto_layout_cjs_namespaceObject.RESOURCE_NODE_SIZE / 2,
                y: agentNode.position.y - BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupDistanceVertical - auto_layout_cjs_namespaceObject.RESOURCE_NODE_SIZE
            },
            data: {
                type: external_AgentFlow_constants_cjs_namespaceObject.ResourceNodeType.MemorySpace,
                name: '',
                description: '',
                isVirtual: true
            },
            width: auto_layout_cjs_namespaceObject.RESOURCE_NODE_SIZE,
            height: auto_layout_cjs_namespaceObject.RESOURCE_NODE_SIZE,
            style: {
                opacity: 0,
                pointerEvents: 'none'
            },
            draggable: false,
            selectable: false
        },
        {
            id: '__virtual_bottom__',
            type: 'resource',
            position: {
                x: agentCenterX - auto_layout_cjs_namespaceObject.RESOURCE_NODE_SIZE / 2,
                y: agentNode.position.y + agentHeight + BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupDistanceVertical
            },
            data: {
                type: external_AgentFlow_constants_cjs_namespaceObject.ResourceNodeType.Context,
                name: '',
                description: '',
                isVirtual: true
            },
            width: auto_layout_cjs_namespaceObject.RESOURCE_NODE_SIZE,
            height: auto_layout_cjs_namespaceObject.RESOURCE_NODE_SIZE,
            style: {
                opacity: 0,
                pointerEvents: 'none'
            },
            draggable: false,
            selectable: false
        }
    ];
};
const getSelectedNodeId = (props, state)=>{
    const { initialSelectedResource, onSelectResource, setSpanForSelectedNode } = props;
    const { nodes } = state;
    if (!initialSelectedResource) {
        onSelectResource?.('agent');
        return 'agent';
    }
    const node = nodes.find(({ id, data })=>data?.type === initialSelectedResource.type && id.startsWith(`agent${props_helpers_cjs_namespaceObject.NODE_ID_DELIMITER}${initialSelectedResource.name}:`));
    if (!node) return null;
    setSpanForSelectedNode?.(node, nodes);
    onSelectResource?.(node.id);
    return node.id;
};
const clearNodeAnimations = (node)=>{
    if (!node.style?.transition) return node;
    const { transition: _, ...cleanStyle } = node.style;
    return {
        ...node,
        style: cleanStyle
    };
};
const shouldCreateSpacing = (insertIndex, siblingCount, originalIndex)=>{
    const isInsertingBetween = insertIndex > 0 && insertIndex < siblingCount;
    const isMovingToEdge = void 0 !== originalIndex && (0 === insertIndex || insertIndex === siblingCount) && originalIndex !== insertIndex;
    return isInsertingBetween || isMovingToEdge;
};
const hasExistingSpacing = (nodes, draggedNodeType, draggedNodeId)=>nodes.some((node)=>(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node) && node.data.type === draggedNodeType && node.id !== draggedNodeId && node.data.originalPosition);
const applyTransitionToNode = (node, draggedNodeId)=>{
    if (node.style?.transition || node.id === draggedNodeId) return node;
    return {
        ...node,
        style: {
            ...node.style,
            transition: BaseCanvas_constants_cjs_namespaceObject.BASE_CANVAS_DEFAULTS.transitions["default"].cssValue
        }
    };
};
const calculateSpacingPositions = (siblingNodes, insertIndex, draggedNode, agentNode)=>{
    const positions = {};
    const isVertical = false;
    const isEdgeInsertion = 0 === insertIndex || insertIndex === siblingNodes.length;
    if (isEdgeInsertion) {
        const agentWidth = agentNode.measured?.width ?? agentNode.width ?? 0;
        const agentHeight = agentNode.measured?.height ?? agentNode.height ?? 0;
        const agentCenterX = agentNode.position.x + agentWidth / 2;
        const agentCenterY = agentNode.position.y + agentHeight / 2;
        for (const [index, node] of siblingNodes.entries()){
            const nodeWidth = node.measured?.width ?? node.width ?? 0;
            const nodeHeight = node.measured?.height ?? node.height ?? 0;
            if (isVertical) {
                const baseY = agentCenterY - nodeHeight / 2 + (index + (0 === insertIndex ? 1 : 0) - siblingNodes.length / 2) * BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupSpacing;
                if ('tool' === draggedNode.data.type) positions[node.id] = {
                    x: agentNode.position.x + agentWidth + BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupDistanceHorizontal,
                    y: baseY
                };
                else positions[node.id] = {
                    x: agentNode.position.x - nodeWidth - BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupDistanceHorizontal,
                    y: baseY
                };
            } else {
                const baseX = agentCenterX - nodeWidth / 2 + (index + (0 === insertIndex ? 1 : 0) - siblingNodes.length / 2) * BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupSpacing;
                if ('escalation' === draggedNode.data.type) positions[node.id] = {
                    x: baseX,
                    y: agentNode.position.y - nodeHeight - BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupDistanceVertical
                };
                else positions[node.id] = {
                    x: baseX,
                    y: agentNode.position.y + agentHeight + BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupDistanceVertical
                };
            }
        }
        return positions;
    }
    const previewOrder = [
        ...siblingNodes.slice(0, insertIndex),
        null,
        ...siblingNodes.slice(insertIndex)
    ];
    const agentWidth = agentNode.measured?.width ?? agentNode.width ?? 0;
    const agentHeight = agentNode.measured?.height ?? agentNode.height ?? 0;
    const agentCenterX = agentNode.position.x + agentWidth / 2;
    const agentCenterY = agentNode.position.y + agentHeight / 2;
    for (const [index, node] of previewOrder.entries()){
        if (!node) continue;
        const nodeWidth = node.measured?.width ?? node.width ?? 0;
        const nodeHeight = node.measured?.height ?? node.height ?? 0;
        if (isVertical) {
            const baseY = agentCenterY - nodeHeight / 2 + (index - (previewOrder.length - 1) / 2) * BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupSpacing;
            if ('tool' === draggedNode.data.type) positions[node.id] = {
                x: agentNode.position.x + agentWidth + BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupDistanceHorizontal,
                y: baseY
            };
            else positions[node.id] = {
                x: agentNode.position.x - nodeWidth - BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupDistanceHorizontal,
                y: baseY
            };
        } else {
            const baseX = agentCenterX - nodeWidth / 2 + (index - (previewOrder.length - 1) / 2) * BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupSpacing;
            if ('escalation' === draggedNode.data.type) positions[node.id] = {
                x: baseX,
                y: agentNode.position.y - nodeHeight - BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupDistanceVertical
            };
            else positions[node.id] = {
                x: baseX,
                y: agentNode.position.y + agentHeight + BaseCanvas_constants_cjs_namespaceObject.FLOW_LAYOUT.groupDistanceVertical
            };
        }
    }
    return positions;
};
const createSpacingState = (nodes, edges, draggedNodeId, spacingPositions)=>{
    const spacedNodes = nodes.map((node)=>{
        if (!(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node) || node.id === draggedNodeId) return node;
        const newPosition = spacingPositions[node.id];
        if (!newPosition) return node;
        const nodeWithTransition = applyTransitionToNode(node, draggedNodeId);
        return {
            ...nodeWithTransition,
            position: newPosition,
            data: {
                ...node.data,
                originalPosition: node.data.originalPosition ?? node.position
            }
        };
    });
    const animatedEdges = edges.map((edge)=>{
        if (edge.source === draggedNodeId || edge.target === draggedNodeId) return edge;
        return (0, resource_operations_cjs_namespaceObject.addAnimationClasses)([
            edge
        ])[0];
    });
    return {
        nodes: spacedNodes,
        edges: animatedEdges
    };
};
const createCollapseState = (nodes, edges, draggedNodeId, draggedNodeType)=>{
    const collapsedNodes = nodes.map((node)=>{
        if (!(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node) || node.data.type !== draggedNodeType || node.id === draggedNodeId || !node.data.originalPosition) return node;
        const nodeWithTransition = applyTransitionToNode(node, draggedNodeId);
        return {
            ...nodeWithTransition,
            position: node.data.originalPosition
        };
    });
    const animatedEdges = edges.map((edge)=>{
        if (edge.source === draggedNodeId || edge.target === draggedNodeId) return edge;
        return (0, resource_operations_cjs_namespaceObject.addAnimationClasses)([
            edge
        ])[0];
    });
    return {
        nodes: collapsedNodes,
        edges: animatedEdges
    };
};
const hasResourceNode = (node, resource)=>node?.id?.endsWith(`:${resource.id}`);
const findNodeForSuggestion = (suggestion, _suggestionGroup, nodes)=>{
    if (!suggestion) return null;
    if ('add' === suggestion.type) return nodes.find((node)=>(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node) && node.data.suggestionId === suggestion.id) ?? null;
    if ('update' === suggestion.type && suggestion.resourceId) {
        if ('agent' === suggestion.resourceId) return nodes.find((node)=>(0, external_types_cjs_namespaceObject.isAgentFlowAgentNode)(node)) ?? null;
        return nodes.find((node)=>{
            if (!(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node)) return false;
            const resourceId = node.id.split(':').pop();
            return resourceId === suggestion.resourceId;
        }) ?? null;
    }
    if ('delete' === suggestion.type && suggestion.resourceIdToDelete) return nodes.find((node)=>{
        if (!(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node)) return false;
        const resourceId = node.id.split(':').pop();
        return resourceId === suggestion.resourceIdToDelete;
    }) ?? null;
    return null;
};
const syncStickyNoteChangesToProps = (nodes, props)=>{
    if (!props.onUpdateStickyNote || !props.stickyNotes) return;
    for (const node of nodes){
        if (!(0, external_types_cjs_namespaceObject.isStickyNoteNode)(node)) continue;
        const propStickyNote = props.stickyNotes.find((sn)=>sn.id === node.id);
        if (!propStickyNote) continue;
        const updates = {};
        if (node.data.content !== propStickyNote.content) updates.content = node.data.content ?? '';
        if (node.data.color && node.data.color !== propStickyNote.color) updates.color = node.data.color;
        const currentWidth = node.width ?? node.measured?.width;
        const currentHeight = node.height ?? node.measured?.height;
        if (currentWidth && currentHeight && (currentWidth !== propStickyNote.size.width || currentHeight !== propStickyNote.size.height)) updates.size = {
            width: currentWidth,
            height: currentHeight
        };
        if (Object.keys(updates).length > 0) props.onUpdateStickyNote(node.id, updates);
    }
};
const createStickyNoteNodes = (stickyNotes, existingNodes)=>{
    if (!stickyNotes || 0 === stickyNotes.length) return [];
    return stickyNotes.map((stickyNote)=>{
        const existingNode = existingNodes?.find((n)=>n.id === stickyNote.id);
        return {
            id: stickyNote.id,
            type: 'stickyNote',
            position: existingNode?.position ?? stickyNote.position,
            width: stickyNote.size.width,
            height: stickyNote.size.height,
            data: {
                color: stickyNote.color,
                content: stickyNote.content
            },
            selected: existingNode?.selected ?? false,
            draggable: true,
            selectable: true
        };
    });
};
const easeOutCubic = (t)=>--t * t * t + 1;
const computeNodesAndEdgesWithSuggestions = (props, existingNodes)=>{
    const { nodes: baseNodes, edges: baseEdges } = (0, props_helpers_cjs_namespaceObject.computeNodesAndEdges)(props, void 0, existingNodes);
    const agentNode = baseNodes.find(external_types_cjs_namespaceObject.isAgentFlowAgentNode);
    if (!agentNode) return {
        nodes: baseNodes,
        edges: baseEdges
    };
    const virtualNodes = createVirtualNodes(agentNode);
    baseNodes.push(...virtualNodes);
    const stickyNoteNodes = createStickyNoteNodes(props.stickyNotes, existingNodes);
    baseNodes.push(...stickyNoteNodes);
    if (!props.suggestionGroup || 0 === props.suggestionGroup.suggestions.length) return {
        nodes: baseNodes,
        edges: baseEdges
    };
    const { nodes: suggestionNodes, edges: suggestionEdges } = (0, props_helpers_cjs_namespaceObject.computeSuggestionNodesAndEdges)(props.suggestionGroup, props, agentNode, props.resources, existingNodes);
    const markedNodes = baseNodes.map((node)=>{
        for (const suggestion of props.suggestionGroup.suggestions)if ('update' === suggestion.type && suggestion.resourceId) {
            if ((0, external_types_cjs_namespaceObject.isAgentFlowAgentNode)(node) && 'agent' === suggestion.resourceId) return {
                ...node,
                data: {
                    ...node.data,
                    suggestionVersion: props.suggestionGroup?.metadata?.version,
                    isSuggestion: !suggestion.isStandalone,
                    suggestionId: suggestion.id,
                    suggestionType: 'update',
                    isPlaceholder: false
                }
            };
            if ((0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node)) {
                const resourceId = node.id.split(':').pop();
                if (resourceId === suggestion.resourceId) return {
                    ...node,
                    data: {
                        ...node.data,
                        suggestionVersion: props.suggestionGroup?.metadata?.version,
                        isSuggestion: !suggestion.isStandalone,
                        suggestionId: suggestion.id,
                        suggestionType: 'update',
                        isPlaceholder: false
                    }
                };
            }
        } else if ('delete' === suggestion.type && suggestion.resourceIdToDelete) {
            if ((0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node)) {
                const resourceId = node.id.split(':').pop();
                if (resourceId === suggestion.resourceIdToDelete) return {
                    ...node,
                    data: {
                        ...node.data,
                        suggestionVersion: props.suggestionGroup?.metadata?.version,
                        isSuggestion: !suggestion.isStandalone,
                        suggestionId: suggestion.id,
                        suggestionType: 'delete',
                        isPlaceholder: false
                    },
                    style: {
                        ...node.style,
                        opacity: 0.4
                    }
                };
            }
        }
        return node;
    });
    const allNodes = [
        ...markedNodes,
        ...suggestionNodes
    ];
    const allEdges = [
        ...baseEdges,
        ...suggestionEdges
    ];
    const arrangedNodes = (0, auto_layout_cjs_namespaceObject.autoArrangeNodes)(allNodes, allEdges, props.agentNodePosition, props.resourceNodePositions);
    return {
        nodes: arrangedNodes,
        edges: allEdges
    };
};
const createAgentFlowStore = (initialProps)=>(0, external_zustand_namespaceObject.createStore)()((set, get)=>{
        const { nodes: initialNodes, edges: initialEdges } = computeNodesAndEdgesWithSuggestions(initialProps);
        const cancelOrganizeAnimation = ()=>{
            const frameId = get().organizeAnimationFrameId;
            if (null !== frameId) {
                cancelAnimationFrame(frameId);
                set({
                    organizeAnimationFrameId: null
                });
            }
        };
        const animateNodesToPositions = (currentNodes, targetNodes, duration, onUpdate, onComplete)=>{
            cancelOrganizeAnimation();
            const startPositions = new Map(currentNodes.map((node)=>[
                    node.id,
                    {
                        ...node.position
                    }
                ]));
            const endPositions = new Map(targetNodes.map((node)=>[
                    node.id,
                    {
                        ...node.position
                    }
                ]));
            const deltas = new Map();
            for (const [id, start] of startPositions){
                const end = endPositions.get(id);
                if (end) deltas.set(id, {
                    x: end.x - start.x,
                    y: end.y - start.y
                });
            }
            const startTime = performance.now();
            const step = (currentTime)=>{
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);
                const easedProgress = easeOutCubic(progress);
                const interpolatedNodes = targetNodes.map((targetNode)=>{
                    const start = startPositions.get(targetNode.id);
                    const delta = deltas.get(targetNode.id);
                    if (!start || !delta) return targetNode;
                    return {
                        ...targetNode,
                        position: {
                            x: start.x + delta.x * easedProgress,
                            y: start.y + delta.y * easedProgress
                        }
                    };
                });
                onUpdate(interpolatedNodes);
                if (progress < 1) set({
                    organizeAnimationFrameId: requestAnimationFrame(step)
                });
                else {
                    set({
                        organizeAnimationFrameId: null
                    });
                    onComplete?.();
                }
            };
            set({
                organizeAnimationFrameId: requestAnimationFrame(step)
            });
        };
        return {
            props: initialProps,
            handlePropsUpdate: (newProps)=>{
                const state = get();
                const hadExplicitPositions = void 0 !== state.props.agentNodePosition || Object.keys(state.props.resourceNodePositions ?? {}).length > 0;
                const nowHasNoExplicitPositions = void 0 === newProps.agentNodePosition && 0 === Object.keys(newProps.resourceNodePositions ?? {}).length;
                const isOrganizeOperation = hadExplicitPositions && nowHasNoExplicitPositions;
                const currentResourceIds = new Set(state.props.resources.map((r)=>r.id));
                const newResourceIds = new Set(newProps.resources.map((r)=>r.id));
                const addedIds = new Set([
                    ...newResourceIds
                ].filter((id)=>!currentResourceIds.has(id)));
                const removedIds = new Set([
                    ...currentResourceIds
                ].filter((id)=>!newResourceIds.has(id)));
                const resourcesAddedOrRemoved = addedIds.size > 0 || removedIds.size > 0;
                const { nodes: allNewNodes, edges: newEdges } = computeNodesAndEdgesWithSuggestions(newProps, state.nodes);
                const updatedNodes = allNewNodes.map((newNode)=>{
                    const oldNode = state.nodes.find((oldNode)=>{
                        if ('agent' === newNode.type && 'agent' === oldNode.type) return newNode.data.parentNodeId === oldNode.data.parentNodeId;
                        if ((0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(newNode) && (0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(oldNode)) {
                            const newResourceId = newNode.id.split(':').pop();
                            const oldResourceId = oldNode.id.split(':').pop();
                            return newResourceId === oldResourceId;
                        }
                        if ((0, external_types_cjs_namespaceObject.isStickyNoteNode)(newNode) && (0, external_types_cjs_namespaceObject.isStickyNoteNode)(oldNode)) return newNode.id === oldNode.id;
                        return false;
                    });
                    if (oldNode) return {
                        ...newNode,
                        position: oldNode.position,
                        selected: oldNode.selected,
                        style: oldNode.style,
                        measured: oldNode.measured,
                        width: oldNode.width ?? newNode.width,
                        height: oldNode.height ?? newNode.height
                    };
                    if (resourcesAddedOrRemoved) {
                        const isFirstAddedResource = (0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(newNode) && [
                            ...addedIds
                        ][0] && newProps.resources.find((r)=>r.id === [
                                ...addedIds
                            ][0] && hasResourceNode(newNode, r));
                        return {
                            ...newNode,
                            selected: Boolean(isFirstAddedResource)
                        };
                    }
                    return newNode;
                });
                let finalNodes = updatedNodes;
                if (isOrganizeOperation || resourcesAddedOrRemoved) finalNodes = (0, auto_layout_cjs_namespaceObject.autoArrangeNodes)(updatedNodes, newEdges, newProps.agentNodePosition, newProps.resourceNodePositions).map((node)=>({
                        ...node,
                        selected: node.id === state.selectedNodeId
                    }));
                let firstNewNodeId = null;
                if (resourcesAddedOrRemoved) {
                    const firstAddedResource = addedIds.size > 0 ? finalNodes.find((node)=>node.selected) : null;
                    if (firstAddedResource) firstNewNodeId = firstAddedResource.id;
                }
                const suggestionGroupChanged = state.props.suggestionGroup?.id !== newProps.suggestionGroup?.id;
                let newSuggestionIndex = state.currentSuggestionIndex;
                if (suggestionGroupChanged && newProps.suggestionGroup?.suggestions) {
                    const firstNonStandalone = newProps.suggestionGroup.suggestions.find((s)=>!s.isStandalone);
                    newSuggestionIndex = firstNonStandalone ? newProps.suggestionGroup.suggestions.findIndex((s)=>s.id === firstNonStandalone.id) : 0;
                }
                if (isOrganizeOperation) {
                    const agentNodeForEdges = updatedNodes.find(external_types_cjs_namespaceObject.isAgentFlowAgentNode);
                    const startingEdges = agentNodeForEdges ? newEdges.map((edge)=>{
                        const targetNode = updatedNodes.find((node)=>node.id === edge.target);
                        if (!targetNode || !(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(targetNode)) return edge;
                        return (0, props_helpers_cjs_namespaceObject.createResourceEdge)(agentNodeForEdges, targetNode, newProps);
                    }) : newEdges;
                    set({
                        props: newProps,
                        nodes: updatedNodes,
                        edges: startingEdges,
                        selectedNodeId: firstNewNodeId || state.selectedNodeId,
                        currentSuggestionIndex: newSuggestionIndex
                    });
                    animateNodesToPositions(updatedNodes, finalNodes, BaseCanvas_constants_cjs_namespaceObject.BASE_CANVAS_DEFAULTS.organizeAnimationDuration, (animatedNodes)=>{
                        set({
                            nodes: animatedNodes
                        });
                    }, ()=>{
                        set({
                            nodes: finalNodes
                        });
                        get().recalculateEdges();
                    });
                } else {
                    set({
                        props: newProps,
                        nodes: finalNodes,
                        edges: newEdges,
                        selectedNodeId: firstNewNodeId || state.selectedNodeId,
                        currentSuggestionIndex: newSuggestionIndex
                    });
                    get().recalculateEdges();
                }
                if (firstNewNodeId && newProps.onSelectResource) newProps.onSelectResource(firstNewNodeId);
                if (addedIds.size > 0 && state.props.suggestionGroup) {
                    const standalonePlaceholder = state.props.suggestionGroup.suggestions.find((s)=>s.isStandalone && 'add' === s.type && s.resource);
                    if (standalonePlaceholder) {
                        const placeholderResourceId = standalonePlaceholder.resource?.id;
                        const nonPlaceholderResourceAdded = placeholderResourceId && !addedIds.has(placeholderResourceId) && addedIds.size > 0;
                        if (nonPlaceholderResourceAdded) newProps.onActOnSuggestion?.(standalonePlaceholder.id, 'accept');
                    }
                }
                const oldStandalonePlaceholders = state.props.suggestionGroup?.suggestions.filter((s)=>s.isStandalone && 'add' === s.type && s.resource) ?? [];
                const newStandalonePlaceholders = newProps.suggestionGroup?.suggestions.filter((s)=>s.isStandalone && 'add' === s.type && s.resource) ?? [];
                if (newStandalonePlaceholders.length > oldStandalonePlaceholders.length) {
                    const newPlaceholder = newStandalonePlaceholders.find((newP)=>!oldStandalonePlaceholders.some((oldP)=>oldP.id === newP.id));
                    if (newPlaceholder?.resource) {
                        const currentState = get();
                        const placeholderNode = currentState.nodes.find((node)=>(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node) && node.data.suggestionId === newPlaceholder.id);
                        if (placeholderNode) {
                            currentState.setSelectedNodeId(placeholderNode.id, {
                                skipPlaceholderClickHandler: true
                            });
                            newProps.onSelectResource?.(placeholderNode.id);
                        }
                    }
                }
            },
            nodes: initialNodes,
            edges: initialEdges,
            selectedNodeId: null,
            setSelectedNodeId: (nodeId, options)=>{
                const state = get();
                const selectedNode = state.nodes.find((node)=>node.id === nodeId);
                if (selectedNode && (0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(selectedNode)) {
                    const isStandalonePlaceholder = !selectedNode.data.isSuggestion && selectedNode.data.suggestionId && selectedNode.data.isPlaceholder;
                    if (isStandalonePlaceholder && !options?.skipPlaceholderClickHandler && state.props.onPlaceholderNodeClick) return void state.props.onPlaceholderNodeClick(selectedNode.data.type, selectedNode.data);
                }
                let newSuggestionIndex = state.currentSuggestionIndex;
                if (selectedNode && (0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(selectedNode) && selectedNode.data.suggestionId) {
                    const suggestionGroup = state.props.suggestionGroup;
                    if (suggestionGroup?.suggestions) {
                        const suggestion = suggestionGroup.suggestions.find((s)=>s.id === selectedNode.data.suggestionId);
                        if (suggestion && !suggestion.isStandalone) {
                            const suggestionIndex = suggestionGroup.suggestions.findIndex((s)=>s.id === selectedNode.data.suggestionId);
                            if (-1 !== suggestionIndex) newSuggestionIndex = suggestionIndex;
                        }
                    }
                }
                set((state)=>({
                        selectedNodeId: nodeId,
                        currentSuggestionIndex: newSuggestionIndex,
                        nodes: state.nodes.map((node)=>{
                            const shouldBeSelected = node.id === nodeId;
                            if (node.selected === shouldBeSelected) return node;
                            return {
                                ...node,
                                selected: shouldBeSelected
                            };
                        })
                    }));
            },
            openMenuNodeId: null,
            setOpenMenuNodeId: (nodeId)=>{
                set({
                    openMenuNodeId: nodeId
                });
            },
            paneContextMenu: null,
            openPaneContextMenu: (position, flowPosition)=>{
                set({
                    paneContextMenu: {
                        position,
                        flowPosition
                    }
                });
            },
            closePaneContextMenu: ()=>{
                set({
                    paneContextMenu: null
                });
            },
            updateNode: (nodeId, updates)=>{
                set((state)=>({
                        nodes: state.nodes.map((node)=>node.id === nodeId ? {
                                ...node,
                                data: {
                                    ...node.data,
                                    ...updates
                                }
                            } : node)
                    }));
            },
            deleteNode: (nodeId)=>{
                const { props } = get();
                if ('design' === props.mode) {
                    if (props.onRemoveResource) {
                        const nodeToDelete = get().nodes.find((node)=>node.id === nodeId);
                        if (nodeToDelete && (0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(nodeToDelete)) {
                            const resourceToRemove = props.resources.find((r)=>hasResourceNode(nodeToDelete, r));
                            if (resourceToRemove) props.onRemoveResource(resourceToRemove);
                        }
                    }
                }
            },
            reorderNodes: (draggedNodeId, targetNodeId)=>{
                set((state)=>{
                    const draggedNode = state.nodes.find((node)=>node.id === draggedNodeId);
                    const targetNode = state.nodes.find((node)=>node.id === targetNodeId);
                    if (!draggedNode || !targetNode || !(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(draggedNode) || !(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(targetNode)) return state;
                    const sameTypeNodes = state.nodes.filter((node)=>'resource' === node.type && node.data.type === draggedNode.data.type).sort((a, b)=>(a.data.order || 0) - (b.data.order || 0));
                    const draggedIndex = sameTypeNodes.findIndex((node)=>node.id === draggedNodeId);
                    const targetIndex = sameTypeNodes.findIndex((node)=>node.id === targetNodeId);
                    if (-1 === draggedIndex || -1 === targetIndex) return state;
                    const reorderedNodes = [
                        ...sameTypeNodes
                    ];
                    const [draggedItem] = reorderedNodes.splice(draggedIndex, 1);
                    reorderedNodes.splice(targetIndex, 0, draggedItem);
                    const updatedNodes = state.nodes.map((node)=>{
                        if ((0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node) && node.data.type === draggedNode.data.type) {
                            const newIndex = reorderedNodes.findIndex((n)=>n.id === node.id);
                            return {
                                ...node,
                                data: {
                                    ...node.data,
                                    order: newIndex
                                }
                            };
                        }
                        return node;
                    });
                    return {
                        ...state,
                        nodes: updatedNodes
                    };
                });
            },
            insertNodeAfter: (draggedNodeId, targetNodeId)=>{
                set((state)=>{
                    const draggedNode = state.nodes.find((node)=>node.id === draggedNodeId);
                    const targetNode = state.nodes.find((node)=>node.id === targetNodeId);
                    if (!draggedNode || !targetNode || !(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(draggedNode) || !(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(targetNode)) return state;
                    const sameTypeNodes = state.nodes.filter((node)=>'resource' === node.type && node.data.type === draggedNode.data.type).sort((a, b)=>(a.data.order || 0) - (b.data.order || 0));
                    const otherNodes = sameTypeNodes.filter((node)=>node.id !== draggedNodeId);
                    const targetIndex = otherNodes.findIndex((node)=>node.id === targetNodeId);
                    if (-1 === targetIndex) return state;
                    const reorderedNodes = [
                        ...otherNodes.slice(0, targetIndex + 1),
                        draggedNode,
                        ...otherNodes.slice(targetIndex + 1)
                    ];
                    const updatedNodes = state.nodes.map((node)=>{
                        if ((0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node) && node.data.type === draggedNode.data.type) {
                            const newIndex = reorderedNodes.findIndex((n)=>n.id === node.id);
                            return {
                                ...node,
                                data: {
                                    ...node.data,
                                    order: newIndex
                                }
                            };
                        }
                        return node;
                    });
                    return {
                        ...state,
                        nodes: updatedNodes
                    };
                });
            },
            onNodesChange: (changes)=>{
                const { props, nodes } = get();
                if (0 === changes.length) return;
                const removeChanges = changes.filter((change)=>'remove' === change.type);
                if (removeChanges.length > 0 && 'design' === props.mode) {
                    for (const removeChange of removeChanges){
                        const nodeToDelete = nodes.find((n)=>n.id === removeChange.id);
                        if (nodeToDelete) {
                            if ('agent' === nodeToDelete.type) continue;
                            if ((0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(nodeToDelete) && props.onRemoveResource) {
                                const resourceToRemove = props.resources.find((r)=>hasResourceNode(nodeToDelete, r));
                                if (resourceToRemove) props.onRemoveResource(resourceToRemove);
                            }
                            if ((0, external_types_cjs_namespaceObject.isStickyNoteNode)(nodeToDelete) && props.onRemoveStickyNote) props.onRemoveStickyNote(nodeToDelete.id);
                        }
                    }
                    const allowedRemoveChanges = removeChanges.filter((removeChange)=>{
                        const nodeToDelete = nodes.find((n)=>n.id === removeChange.id);
                        if (!nodeToDelete) return true;
                        if ('agent' === nodeToDelete.type) return false;
                        return true;
                    });
                    if (0 === allowedRemoveChanges.length) return;
                    const nonRemoveChanges = changes.filter((change)=>'remove' !== change.type);
                    const filteredChanges = [
                        ...nonRemoveChanges,
                        ...allowedRemoveChanges
                    ];
                    if (0 === filteredChanges.length) return;
                    const updatedNodes = (0, react_cjs_namespaceObject.applyNodeChanges)(filteredChanges, nodes);
                    if (updatedNodes === nodes) return;
                    set({
                        nodes: updatedNodes
                    });
                    return;
                }
                const hasSelectionChanges = changes.some((change)=>'selected' in change);
                if (hasSelectionChanges) {
                    const selectionChange = changes.find((change)=>'selected' in change);
                    if (selectionChange && 'selected' in selectionChange) {
                        const newSelectedId = selectionChange.selected ? selectionChange.id : null;
                        const updatedNodes = (0, react_cjs_namespaceObject.applyNodeChanges)(changes, nodes);
                        if (updatedNodes === nodes && newSelectedId === get().selectedNodeId) return;
                        set({
                            selectedNodeId: newSelectedId,
                            nodes: updatedNodes
                        });
                        syncStickyNoteChangesToProps(updatedNodes, props);
                        return;
                    }
                }
                const filteredChanges = changes.filter((change)=>!('selected' in change));
                if (0 === filteredChanges.length) return;
                const onlyDimensionChanges = filteredChanges.every((change)=>'dimensions' === change.type);
                if (onlyDimensionChanges) {
                    const updatedNodes = (0, react_cjs_namespaceObject.applyNodeChanges)(filteredChanges, nodes);
                    let dimensionsChanged = false;
                    for (const updated of updatedNodes){
                        const original = nodes.find((n)=>n.id === updated.id);
                        if (!original) {
                            dimensionsChanged = true;
                            break;
                        }
                        const oldMeasuredWidth = original.measured?.width;
                        const oldMeasuredHeight = original.measured?.height;
                        const newMeasuredWidth = updated.measured?.width;
                        const newMeasuredHeight = updated.measured?.height;
                        const oldExplicitWidth = original.width;
                        const oldExplicitHeight = original.height;
                        const newExplicitWidth = updated.width;
                        const newExplicitHeight = updated.height;
                        const measuredChanged = oldMeasuredWidth !== newMeasuredWidth || oldMeasuredHeight !== newMeasuredHeight;
                        const explicitChanged = oldExplicitWidth !== newExplicitWidth || oldExplicitHeight !== newExplicitHeight;
                        if (measuredChanged || explicitChanged) {
                            dimensionsChanged = true;
                            break;
                        }
                    }
                    if (dimensionsChanged) {
                        set({
                            nodes: updatedNodes
                        });
                        syncStickyNoteChangesToProps(updatedNodes, props);
                    }
                    return;
                }
                const currentSelectedId = get().selectedNodeId;
                const updatedNodes = (0, react_cjs_namespaceObject.applyNodeChanges)(filteredChanges, nodes);
                const hasPositionChanges = filteredChanges.some((change)=>'position' === change.type);
                const finalNodes = updatedNodes.map((updatedNode)=>{
                    const shouldBeSelected = updatedNode.id === currentSelectedId;
                    if (updatedNode.selected === shouldBeSelected) return updatedNode;
                    return {
                        ...updatedNode,
                        selected: shouldBeSelected
                    };
                });
                set({
                    nodes: finalNodes
                });
                syncStickyNoteChangesToProps(finalNodes, props);
                if (hasPositionChanges) get().recalculateEdges();
            },
            onEdgesChange: (changes)=>{
                const filteredChanges = changes.filter((change)=>{
                    if ('remove' !== change.type) return true;
                    const edgeToRemove = get().edges.find((edge)=>edge.id === change.id);
                    if (!edgeToRemove) return true;
                    const sourceNode = get().nodes.find((node)=>node.id === edgeToRemove.source);
                    const targetNode = get().nodes.find((node)=>node.id === edgeToRemove.target);
                    const isSourceAgent = sourceNode?.type === 'agent';
                    const isTargetAgent = targetNode?.type === 'agent';
                    if (!isSourceAgent && !isTargetAgent) return true;
                    if (isSourceAgent && !isTargetAgent) return !targetNode;
                    if (!isSourceAgent && isTargetAgent) return !sourceNode;
                    return false;
                });
                set((state)=>({
                        edges: (0, react_cjs_namespaceObject.applyEdgeChanges)(filteredChanges, state.edges)
                    }));
            },
            onConnect: (connection)=>{
                set((state)=>({
                        edges: (0, react_cjs_namespaceObject.addEdge)(connection, state.edges)
                    }));
            },
            recalculateEdges: ()=>{
                const state = get();
                const agentNode = state.nodes.find(external_types_cjs_namespaceObject.isAgentFlowAgentNode);
                if (!agentNode) return;
                const updatedEdges = state.edges.map((edge)=>{
                    const targetNode = state.nodes.find((node)=>node.id === edge.target);
                    if (!targetNode || !(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(targetNode)) return edge;
                    return (0, props_helpers_cjs_namespaceObject.createResourceEdge)(agentNode, targetNode, state.props);
                });
                set({
                    edges: updatedEdges
                });
            },
            isDragging: false,
            draggedNodeId: null,
            dragPreview: {
                draggedNodeId: null,
                insertAfterNodeId: null,
                previewPositions: {}
            },
            organizeAnimationFrameId: null,
            setDragging: (isDragging, draggedNodeId)=>{
                set({
                    isDragging,
                    draggedNodeId
                });
            },
            autoArrange: ()=>{
                const state = get();
                const arrangedNodes = (0, auto_layout_cjs_namespaceObject.autoArrangeNodes)(state.nodes, state.edges, state.props.agentNodePosition, state.props.resourceNodePositions).map((node)=>({
                        ...node,
                        selected: node.id === state.selectedNodeId
                    }));
                set({
                    nodes: arrangedNodes
                });
                get().recalculateEdges();
            },
            clearDragAndAutoArrange: ()=>{
                set({
                    isDragging: false,
                    draggedNodeId: null,
                    dragPreview: {
                        draggedNodeId: null,
                        insertAfterNodeId: null,
                        previewPositions: {}
                    }
                });
                get().autoArrange();
            },
            setDragPreview: (draggedNodeId, insertAfterNodeId)=>{
                const state = get();
                if (!draggedNodeId) {
                    const previousDraggedNodeId = state.dragPreview.draggedNodeId;
                    const clearedNodes = state.nodes.map((node)=>{
                        if (!(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node) || !node.data.originalPosition) return node;
                        return {
                            ...node,
                            data: {
                                ...node.data,
                                originalPosition: void 0
                            }
                        };
                    });
                    const clearedEdges = state.edges.map((edge)=>{
                        if (edge.source === previousDraggedNodeId || edge.target === previousDraggedNodeId) return (0, resource_operations_cjs_namespaceObject.removeAnimationClasses)([
                            edge
                        ])[0];
                        return edge;
                    });
                    set({
                        nodes: clearedNodes,
                        edges: clearedEdges,
                        dragPreview: {
                            draggedNodeId: null,
                            insertAfterNodeId: null,
                            previewPositions: {}
                        }
                    });
                    return;
                }
                const clearedNodes = state.nodes.map((node)=>node.id === draggedNodeId ? clearNodeAnimations(node) : node);
                const clearedEdges = state.edges.map((edge)=>{
                    if (edge.source === draggedNodeId || edge.target === draggedNodeId) return (0, resource_operations_cjs_namespaceObject.removeAnimationClasses)([
                        edge
                    ])[0];
                    return edge;
                });
                set({
                    nodes: clearedNodes,
                    edges: clearedEdges
                });
                const updatedState = get();
                const draggedNode = updatedState.nodes.find((n)=>n.id === draggedNodeId);
                if (!draggedNode || !(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(draggedNode)) return;
                const allSameTypeNodes = updatedState.nodes.filter((node)=>'resource' === node.type && node.data.type === draggedNode.data.type).sort((a, b)=>(a.data.order || 0) - (b.data.order || 0));
                const originalIndex = allSameTypeNodes.findIndex((n)=>n.id === draggedNodeId);
                const siblingNodes = allSameTypeNodes.filter((node)=>node.id !== draggedNodeId);
                if (0 === siblingNodes.length) return;
                if (1 === siblingNodes.length) {
                    const siblingNode = siblingNodes[0];
                    const shouldInsertBefore = null === insertAfterNodeId;
                    const insertIndex = shouldInsertBefore ? 0 : 1;
                    const updatedAgentNode = updatedState.nodes.find(external_types_cjs_namespaceObject.isAgentFlowAgentNode);
                    if (!updatedAgentNode) return;
                    const spacingPositions = calculateSpacingPositions([
                        siblingNode
                    ], insertIndex, draggedNode, updatedAgentNode);
                    const { nodes: spacedNodes, edges: animatedEdges } = createSpacingState(updatedState.nodes, updatedState.edges, draggedNodeId, spacingPositions);
                    set({
                        nodes: spacedNodes,
                        edges: animatedEdges,
                        dragPreview: {
                            draggedNodeId,
                            insertAfterNodeId,
                            previewPositions: {}
                        }
                    });
                    return;
                }
                let insertIndex = 0;
                if (insertAfterNodeId) {
                    const afterIndex = siblingNodes.findIndex((n)=>n.id === insertAfterNodeId);
                    insertIndex = afterIndex >= 0 ? afterIndex + 1 : 0;
                }
                const isInsertingBetween = shouldCreateSpacing(insertIndex, siblingNodes.length, originalIndex >= 0 ? originalIndex : void 0);
                if (!isInsertingBetween) {
                    if (hasExistingSpacing(updatedState.nodes, draggedNode.data.type, draggedNodeId)) {
                        const { nodes: collapsedNodes, edges: animatedEdges } = createCollapseState(updatedState.nodes, updatedState.edges, draggedNodeId, draggedNode.data.type);
                        set({
                            nodes: collapsedNodes,
                            edges: animatedEdges,
                            dragPreview: {
                                draggedNodeId,
                                insertAfterNodeId,
                                previewPositions: {}
                            }
                        });
                    } else {
                        const nodesWithTracking = updatedState.nodes.map((node)=>{
                            if ((0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node) && node.data.type === draggedNode.data.type && node.id !== draggedNodeId) return {
                                ...node,
                                data: {
                                    ...node.data,
                                    originalPosition: node.data.originalPosition ?? node.position
                                }
                            };
                            return node;
                        });
                        set({
                            nodes: nodesWithTracking,
                            dragPreview: {
                                draggedNodeId,
                                insertAfterNodeId,
                                previewPositions: {}
                            }
                        });
                    }
                    return;
                }
                const agentNode = updatedState.nodes.find(external_types_cjs_namespaceObject.isAgentFlowAgentNode);
                if (!agentNode) return;
                const spacingPositions = calculateSpacingPositions(siblingNodes, insertIndex, draggedNode, agentNode);
                const { nodes: spacedNodes, edges: animatedEdges } = createSpacingState(updatedState.nodes, updatedState.edges, draggedNodeId, spacingPositions);
                set({
                    nodes: spacedNodes,
                    edges: animatedEdges,
                    dragPreview: {
                        draggedNodeId,
                        insertAfterNodeId,
                        previewPositions: {}
                    }
                });
            },
            expandAgent: (resourceId, agentDefinition)=>{
                const currentState = get();
                const resourceNode = currentState.nodes.find((node)=>(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(node) && node.id === resourceId);
                if (!resourceNode || !(0, external_types_cjs_namespaceObject.isAgentFlowResourceNode)(resourceNode) || 'tool' !== resourceNode.data.type || 'Agent' !== resourceNode.data.projectType) return;
                if (!agentDefinition.rawAgentDefinition) return;
                const nestedResources = agentDefinition.agentResources;
                const nestedAgentProps = {
                    mode: currentState.props.mode,
                    definition: agentDefinition.rawAgentDefinition,
                    spans: [],
                    name: resourceNode.data.name,
                    description: resourceNode.data.description,
                    resources: nestedResources,
                    activeResourceIds: []
                };
                const { nodes: nestedNodes, edges: nestedEdges } = (0, props_helpers_cjs_namespaceObject.computeNodesAndEdges)(nestedAgentProps, resourceNode.id, currentState.nodes);
                const agentNode = nestedNodes.find((node)=>'agent' === node.type);
                if (!agentNode) return;
                const connectionEdge = {
                    id: `${resourceId}::${agentNode.id}`,
                    source: resourceNode.id,
                    target: agentNode.id,
                    type: 'default',
                    sourceHandle: 'right',
                    targetHandle: 'left',
                    data: {
                        label: null
                    },
                    animated: false,
                    selectable: false
                };
                set((state)=>{
                    const newNodes = [
                        ...state.nodes,
                        ...nestedNodes
                    ];
                    const newEdges = [
                        ...state.edges,
                        ...nestedEdges,
                        connectionEdge
                    ];
                    return {
                        nodes: newNodes,
                        edges: newEdges,
                        selectedNodeId: agentNode.id
                    };
                });
                get().autoArrangeAndFitView();
            },
            collapseAgent: (resourceId)=>{
                const state = get();
                const nodesToRemove = state.nodes.filter((node)=>node.id.startsWith(`${resourceId}${props_helpers_cjs_namespaceObject.NODE_ID_DELIMITER}`));
                const edgesToRemove = state.edges.filter((edge)=>nodesToRemove.some((node)=>edge.source === node.id || edge.target === node.id));
                set({
                    nodes: state.nodes.filter((node)=>!nodesToRemove.some((n)=>n.id === node.id)),
                    edges: state.edges.filter((edge)=>!edgesToRemove.some((e)=>e.id === edge.id))
                });
                get().autoArrangeAndFitView();
            },
            fitView: ()=>{
                window.dispatchEvent(new CustomEvent('agentFlowFitView'));
            },
            autoArrangeAndFitView: ()=>{
                const state = get();
                const allMeasured = state.nodes.every((node)=>node.measured);
                if (allMeasured) {
                    get().autoArrange();
                    requestAnimationFrame(()=>{
                        get().fitView();
                    });
                } else {
                    const checkMeasurements = ()=>{
                        const currentState = get();
                        const nodesMeasured = currentState.nodes.every((node)=>node.measured);
                        if (nodesMeasured) {
                            get().autoArrange();
                            requestAnimationFrame(()=>{
                                get().fitView();
                            });
                        } else requestAnimationFrame(checkMeasurements);
                    };
                    requestAnimationFrame(checkMeasurements);
                }
            },
            actOnSuggestion: (suggestionId, action)=>{
                const { props, currentSuggestionIndex } = get();
                if (!props.suggestionGroup?.suggestions) return void props.onActOnSuggestion?.(suggestionId, action);
                const suggestions = props.suggestionGroup.suggestions;
                const removedSuggestion = suggestions.find((s)=>s.id === suggestionId);
                const nonStandaloneSuggestions = suggestions.filter((s)=>!s.isStandalone);
                const currentSuggestion = suggestions[currentSuggestionIndex];
                let nextIndex = currentSuggestionIndex;
                if (removedSuggestion && !removedSuggestion.isStandalone) {
                    const currentNonStandaloneIndex = currentSuggestion?.isStandalone ? -1 : nonStandaloneSuggestions.findIndex((s)=>s.id === currentSuggestion?.id);
                    const removedNonStandaloneIndex = nonStandaloneSuggestions.findIndex((s)=>s.id === suggestionId);
                    if (-1 !== removedNonStandaloneIndex) {
                        if (removedNonStandaloneIndex < currentNonStandaloneIndex) {
                            const newNonStandaloneIndex = Math.max(0, currentNonStandaloneIndex - 1);
                            const adjustedNonStandalone = nonStandaloneSuggestions.filter((s)=>s.id !== suggestionId);
                            if (adjustedNonStandalone[newNonStandaloneIndex]) nextIndex = suggestions.findIndex((s)=>s.id === adjustedNonStandalone[newNonStandaloneIndex]?.id);
                        } else if (removedNonStandaloneIndex === currentNonStandaloneIndex) {
                            const adjustedNonStandalone = nonStandaloneSuggestions.filter((s)=>s.id !== suggestionId);
                            if (adjustedNonStandalone.length > 0) {
                                const newNonStandaloneIndex = Math.min(currentNonStandaloneIndex, adjustedNonStandalone.length - 1);
                                nextIndex = suggestions.findIndex((s)=>s.id === adjustedNonStandalone[newNonStandaloneIndex]?.id);
                            } else nextIndex = -1;
                        }
                    }
                }
                set({
                    currentSuggestionIndex: nextIndex
                });
                props.onActOnSuggestion?.(suggestionId, action);
                Promise.resolve().then(()=>{
                    const state = get();
                    const updatedSuggestions = state.props.suggestionGroup?.suggestions;
                    if (updatedSuggestions && updatedSuggestions.length > 0) {
                        const updatedNonStandalone = updatedSuggestions.filter((s)=>!s.isStandalone);
                        if (updatedNonStandalone.length > 0) {
                            let nextSuggestion = updatedSuggestions[state.currentSuggestionIndex];
                            if (!nextSuggestion || nextSuggestion.isStandalone) {
                                nextSuggestion = updatedNonStandalone[0];
                                if (nextSuggestion) {
                                    const newIndex = updatedSuggestions.findIndex((s)=>s.id === nextSuggestion.id);
                                    set({
                                        currentSuggestionIndex: newIndex
                                    });
                                }
                            }
                            if (nextSuggestion && !nextSuggestion.isStandalone) {
                                const node = findNodeForSuggestion(nextSuggestion, state.props.suggestionGroup, state.nodes);
                                if (node) {
                                    state.setSelectedNodeId(node.id);
                                    state.props.onSelectResource?.(node.id);
                                }
                            }
                        }
                    }
                });
            },
            actOnSuggestionGroup: (suggestionGroupId, action)=>{
                const { props } = get();
                if (props.suggestionGroup && props.suggestionGroup.id === suggestionGroupId) {
                    const nonStandaloneSuggestions = props.suggestionGroup.suggestions.filter((s)=>!s.isStandalone);
                    if (0 === nonStandaloneSuggestions.length) return;
                }
                props.onActOnSuggestionGroup?.(suggestionGroupId, action);
            },
            currentSuggestionIndex: 0,
            setCurrentSuggestionIndex: (index)=>{
                set({
                    currentSuggestionIndex: index
                });
            },
            navigateToNextSuggestion: ()=>{
                const { props, nodes, currentSuggestionIndex, setSelectedNodeId } = get();
                if (!props.suggestionGroup?.suggestions || 0 === props.suggestionGroup.suggestions.length) return;
                const nonStandaloneSuggestions = props.suggestionGroup.suggestions.filter((s)=>!s.isStandalone);
                if (0 === nonStandaloneSuggestions.length) return;
                const currentSuggestion = props.suggestionGroup.suggestions[currentSuggestionIndex];
                const currentNonStandaloneIndex = currentSuggestion?.isStandalone ? -1 : nonStandaloneSuggestions.findIndex((s)=>s.id === currentSuggestion?.id);
                const nextNonStandaloneIndex = (currentNonStandaloneIndex + 1) % nonStandaloneSuggestions.length;
                const nextSuggestion = nonStandaloneSuggestions[nextNonStandaloneIndex];
                if (!nextSuggestion) return;
                const nextIndex = props.suggestionGroup.suggestions.findIndex((s)=>s.id === nextSuggestion.id);
                if (-1 === nextIndex) return;
                set({
                    currentSuggestionIndex: nextIndex
                });
                const node = findNodeForSuggestion(nextSuggestion, props.suggestionGroup, nodes);
                if (node) {
                    setSelectedNodeId(node.id);
                    props.onSelectResource?.(node.id);
                }
            },
            navigateToPreviousSuggestion: ()=>{
                const { props, nodes, currentSuggestionIndex, setSelectedNodeId } = get();
                if (!props.suggestionGroup?.suggestions || 0 === props.suggestionGroup.suggestions.length) return;
                const nonStandaloneSuggestions = props.suggestionGroup.suggestions.filter((s)=>!s.isStandalone);
                if (0 === nonStandaloneSuggestions.length) return;
                const currentSuggestion = props.suggestionGroup.suggestions[currentSuggestionIndex];
                const currentNonStandaloneIndex = currentSuggestion?.isStandalone ? 0 : nonStandaloneSuggestions.findIndex((s)=>s.id === currentSuggestion?.id);
                const prevNonStandaloneIndex = (currentNonStandaloneIndex - 1 + nonStandaloneSuggestions.length) % nonStandaloneSuggestions.length;
                const prevSuggestion = nonStandaloneSuggestions[prevNonStandaloneIndex];
                if (!prevSuggestion) return;
                const prevIndex = props.suggestionGroup.suggestions.findIndex((s)=>s.id === prevSuggestion.id);
                if (-1 === prevIndex) return;
                set({
                    currentSuggestionIndex: prevIndex
                });
                const node = findNodeForSuggestion(prevSuggestion, props.suggestionGroup, nodes);
                if (node) {
                    setSelectedNodeId(node.id);
                    props.onSelectResource?.(node.id);
                }
            },
            createResourcePlaceholder: (type)=>{
                const { props } = get();
                if (props.onRequestResourcePlaceholder) {
                    const cleanedSuggestionGroup = props.suggestionGroup ? {
                        ...props.suggestionGroup,
                        suggestions: props.suggestionGroup.suggestions.filter((s)=>!s.isStandalone)
                    } : null;
                    const partialResource = props.onRequestResourcePlaceholder(type, cleanedSuggestionGroup);
                    if (null === partialResource) return void props.onAddResource?.(type);
                    return;
                }
                props.onAddResource?.(type);
            },
            addStickyNote: (data = {})=>{
                const state = get();
                const { props } = state;
                if (!props.onAddStickyNote) return;
                const agentNode = state.nodes.find(external_types_cjs_namespaceObject.isAgentFlowAgentNode);
                if (!agentNode) return;
                const agentWidth = agentNode.measured?.width ?? agentNode.width ?? 320;
                const defaultPosition = {
                    x: agentNode.position.x + agentWidth + 100,
                    y: agentNode.position.y
                };
                const stickyNoteNodeId = `sticky-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
                props.onAddStickyNote({
                    id: stickyNoteNodeId,
                    content: data.content ?? '',
                    position: data.position ?? defaultPosition,
                    size: {
                        width: 304,
                        height: 288
                    },
                    color: data.color ?? 'yellow'
                });
                state.setSelectedNodeId(stickyNoteNodeId);
            }
        };
    });
const AgentFlowContext = (0, external_react_namespaceObject.createContext)(null);
const AgentFlowProvider = ({ children, ...props })=>{
    const [store] = (0, external_react_namespaceObject.useState)(createAgentFlowStore(props));
    (0, external_react_namespaceObject.useEffect)(()=>{
        store.setState({
            ...store.getState(),
            selectedNodeId: getSelectedNodeId(props, store.getState())
        });
    }, []);
    (0, external_react_namespaceObject.useEffect)(()=>{
        store.getState().handlePropsUpdate(props);
    }, [
        props
    ]);
    return external_react_default().createElement(AgentFlowContext.Provider, {
        value: store
    }, children);
};
function useAgentFlowStore(selector) {
    const store = (0, external_react_namespaceObject.useContext)(AgentFlowContext);
    if (!store) throw new Error('useAgentFlowStore must be used within AgentFlowProvider');
    const selectorFn = selector ?? ((state)=>state);
    return (0, external_zustand_namespaceObject.useStore)(store, selectorFn);
}
const useNodes = ()=>useAgentFlowStore((state)=>state.nodes);
const useEdges = ()=>useAgentFlowStore((state)=>state.edges);
const useSelectedNodeId = ()=>useAgentFlowStore((state)=>state.selectedNodeId);
const useSelectedNode = ()=>useAgentFlowStore((state)=>{
        if (!state.selectedNodeId) return null;
        return state.nodes.find((node)=>node.id === state.selectedNodeId) ?? null;
    });
exports.AgentFlowProvider = __webpack_exports__.AgentFlowProvider;
exports.createAgentFlowStore = __webpack_exports__.createAgentFlowStore;
exports.hasResourceNode = __webpack_exports__.hasResourceNode;
exports.useAgentFlowStore = __webpack_exports__.useAgentFlowStore;
exports.useEdges = __webpack_exports__.useEdges;
exports.useNodes = __webpack_exports__.useNodes;
exports.useSelectedNode = __webpack_exports__.useSelectedNode;
exports.useSelectedNodeId = __webpack_exports__.useSelectedNodeId;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AgentFlowProvider",
    "createAgentFlowStore",
    "hasResourceNode",
    "useAgentFlowStore",
    "useEdges",
    "useNodes",
    "useSelectedNode",
    "useSelectedNodeId"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
