UNPKG

@copilotkit/react-core

Version:

<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />

7,619 lines 280 kB
"use client";

(function(global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ?  factory(exports, require('react'), require('@copilotkit/core'), require('@ag-ui/client'), require('@copilotkit/shared'), require('react/jsx-runtime'), require('zod'), require('@lit-labs/react'), require('@copilotkit/a2ui-renderer'), require('zod-to-json-schema'), require('react-dom'), require('react-markdown'), require('@copilotkit/runtime-client-gql')) :
  typeof define === 'function' && define.amd ? define(['exports', 'react', '@copilotkit/core', '@ag-ui/client', '@copilotkit/shared', 'react/jsx-runtime', 'zod', '@lit-labs/react', '@copilotkit/a2ui-renderer', 'zod-to-json-schema', 'react-dom', 'react-markdown', '@copilotkit/runtime-client-gql'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitReactCore = {}), global.React,global.CopilotKitCore,global.AgUIClient,global.CopilotKitShared,global.ReactJsxRuntime,global.Zod,global._lit_labs_react,global.CopilotKitA2UIRenderer,global.zod_to_json_schema,global.ReactDOM,global.ReactMarkdown,global.CopilotKitRuntimeClientGQL));
})(this, function(exports, react, _copilotkit_core, _ag_ui_client, _copilotkit_shared, react_jsx_runtime, zod, _lit_labs_react, _copilotkit_a2ui_renderer, zod_to_json_schema, react_dom, react_markdown, _copilotkit_runtime_client_gql) {
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
//#region \0rolldown/runtime.js
	var __create = Object.create;
	var __defProp = Object.defineProperty;
	var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
	var __getOwnPropNames = Object.getOwnPropertyNames;
	var __getProtoOf = Object.getPrototypeOf;
	var __hasOwnProp = Object.prototype.hasOwnProperty;
	var __copyProps = (to, from, except, desc) => {
		if (from && typeof from === "object" || typeof from === "function") {
			for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
				key = keys[i];
				if (!__hasOwnProp.call(to, key) && key !== except) {
					__defProp(to, key, {
						get: ((k) => from[k]).bind(null, key),
						enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
					});
				}
			}
		}
		return to;
	};
	var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
		value: mod,
		enumerable: true
	}) : target, mod));

//#endregion
react = __toESM(react);
react_markdown = __toESM(react_markdown);

//#region src/v2/lib/shallow-stable-ref.ts
/**
	* Shallow equality comparison for objects.
	*/
	function shallowEqual(obj1, obj2) {
		const keys1 = Object.keys(obj1);
		const keys2 = Object.keys(obj2);
		if (keys1.length !== keys2.length) return false;
		for (const key of keys1) if (obj1[key] !== obj2[key]) return false;
		return true;
	}
	/**
	* Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
	* class instances, and other exotic objects that happen to have typeof "object".
	*/
	function isPlainObject(obj) {
		return obj !== null && typeof obj === "object" && Object.prototype.toString.call(obj) === "[object Object]";
	}
	/**
	* Returns the same reference as long as the value is shallowly equal to the
	* previous render's value.
	*
	* - Identical references bail out immediately (O(1)).
	* - Plain objects ({}) are shallow-compared key-by-key.
	* - Arrays, Dates, class instances, functions, and primitives are compared by
	*   reference only — shallowEqual is never called on non-plain objects, which
	*   avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).
	*
	* Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow
	* equality check isn't defeated by a new object reference on every render.
	*/
	function useShallowStableRef(value) {
		const ref = (0, react.useRef)(value);
		if (ref.current === value) return ref.current;
		if (isPlainObject(ref.current) && isPlainObject(value)) {
			if (shallowEqual(ref.current, value)) return ref.current;
		}
		ref.current = value;
		return ref.current;
	}

//#endregion
//#region src/v2/providers/CopilotChatConfigurationProvider.tsx
	const CopilotChatDefaultLabels = {
		chatInputPlaceholder: "Type a message...",
		chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
		chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
		chatInputToolbarFinishTranscribeButtonLabel: "Finish",
		chatInputToolbarAddButtonLabel: "Add attachments",
		chatInputToolbarToolsButtonLabel: "Tools",
		assistantMessageToolbarCopyCodeLabel: "Copy",
		assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
		assistantMessageToolbarCopyMessageLabel: "Copy",
		assistantMessageToolbarInspectorLabel: "View in Inspector",
		assistantMessageToolbarInspectorLocalOnlyLabel: "Local Only",
		assistantMessageToolbarThumbsUpLabel: "Good response",
		assistantMessageToolbarThumbsDownLabel: "Bad response",
		assistantMessageToolbarReadAloudLabel: "Read aloud",
		assistantMessageToolbarRegenerateLabel: "Regenerate",
		userMessageToolbarCopyMessageLabel: "Copy",
		userMessageToolbarEditMessageLabel: "Edit",
		chatDisclaimerText: "AI can make mistakes. Please verify important information.",
		chatToggleOpenLabel: "Open chat",
		chatToggleCloseLabel: "Close chat",
		modalHeaderTitle: "CopilotKit Chat",
		welcomeMessageText: "How can I help you today?"
	};
	/**
	* Mobile breakpoint below which the chat modal and the thread-list drawer are
	* mutually exclusive. At or above this width both surfaces may coexist. This
	* mirrors the `(max-width: 767px)` / `(min-width: 768px)` split already used by
	* CopilotChatInput and CopilotSidebarView.
	*/
	const MOBILE_MAX_WIDTH_PX = 767;
	/**
	* Reports whether the current viewport is in the mobile range (`<768px`), where
	* the chat modal and drawer must not be open simultaneously. SSR-safe and
	* defensive against environments without `matchMedia` (treated as desktop, so
	* no mutual-exclusion constraint is applied).
	*
	* @returns `true` when the viewport is mobile-width, `false` otherwise.
	*/
	function isMobileViewport() {
		if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
		return window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH_PX}px)`).matches;
	}
	const CopilotChatConfiguration = (0, react.createContext)(null);
	const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
		const parentConfig = (0, react.useContext)(CopilotChatConfiguration);
		const stableLabels = useShallowStableRef(labels);
		const mergedLabels = (0, react.useMemo)(() => ({
			...CopilotChatDefaultLabels,
			...parentConfig?.labels,
			...stableLabels
		}), [stableLabels, parentConfig?.labels]);
		const resolvedAgentId = agentId ?? parentConfig?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
		const threadIdPropIsAuthoritative = threadId !== void 0 && hasExplicitThreadId !== false;
		const isThreadIdControlled = threadIdPropIsAuthoritative;
		const [activeThreadOverride, setActiveThreadOverride] = (0, react.useState)(null);
		const resolvedThreadId = (0, react.useMemo)(() => {
			if (threadIdPropIsAuthoritative) return threadId;
			if (activeThreadOverride) return activeThreadOverride.threadId;
			if (parentConfig?.threadId) return parentConfig.threadId;
			if (threadId) return threadId;
			return (0, _copilotkit_shared.randomUUID)();
		}, [
			threadIdPropIsAuthoritative,
			threadId,
			parentConfig?.threadId,
			activeThreadOverride
		]);
		const resolvedHasExplicitThreadId = (threadIdPropIsAuthoritative ? true : activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false) || !!parentConfig?.hasExplicitThreadId;
		const [internalModalOpen, setInternalModalOpen] = (0, react.useState)(isModalDefaultOpen ?? true);
		const hasExplicitDefault = isModalDefaultOpen !== void 0;
		const setAndSync = (0, react.useCallback)((open) => {
			setInternalModalOpen(open);
			parentConfig?.setModalOpen(open);
		}, [parentConfig?.setModalOpen]);
		const isMounted = (0, react.useRef)(false);
		(0, react.useEffect)(() => {
			if (!hasExplicitDefault) return;
			if (!isMounted.current) {
				isMounted.current = true;
				return;
			}
			if (parentConfig?.isModalOpen === void 0) return;
			setInternalModalOpen(parentConfig.isModalOpen);
		}, [parentConfig?.isModalOpen, hasExplicitDefault]);
		const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : parentConfig?.isModalOpen ?? internalModalOpen;
		const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : parentConfig?.setModalOpen ?? setInternalModalOpen;
		const [ownDrawerOpen, setOwnDrawerOpen] = (0, react.useState)(false);
		const [ownDrawerCount, setOwnDrawerCount] = (0, react.useState)(0);
		const modalCloseRef = (0, react.useRef)(() => {});
		modalCloseRef.current = resolvedSetModalOpen;
		const registeredModalClosersRef = (0, react.useRef)([]);
		const ownRegisterModalCloser = (0, react.useCallback)((closeModal) => {
			registeredModalClosersRef.current.push(closeModal);
			return () => {
				registeredModalClosersRef.current = registeredModalClosersRef.current.filter((entry) => entry !== closeModal);
			};
		}, []);
		const ownSetDrawerOpen = (0, react.useCallback)((open) => {
			setOwnDrawerOpen(open);
			if (open && isMobileViewport()) {
				const registered = registeredModalClosersRef.current;
				(registered.length > 0 ? registered[registered.length - 1] : modalCloseRef.current)(false);
			}
		}, []);
		const ownRegisterDrawer = (0, react.useCallback)(() => {
			setOwnDrawerCount((count) => count + 1);
			return () => {
				setOwnDrawerCount((count) => Math.max(0, count - 1));
			};
		}, []);
		const resolvedDrawerOpen = parentConfig ? parentConfig.drawerOpen : ownDrawerOpen;
		const resolvedSetDrawerOpen = parentConfig ? parentConfig.setDrawerOpen : ownSetDrawerOpen;
		const resolvedDrawerRegistered = parentConfig ? parentConfig.drawerRegistered : ownDrawerCount > 0;
		const resolvedRegisterDrawer = parentConfig ? parentConfig.registerDrawer : ownRegisterDrawer;
		const resolvedRegisterModalCloser = parentConfig ? parentConfig.ɵregisterModalCloser : ownRegisterModalCloser;
		(0, react.useEffect)(() => {
			if (!hasExplicitDefault) return;
			return resolvedRegisterModalCloser(resolvedSetModalOpen);
		}, [
			hasExplicitDefault,
			resolvedRegisterModalCloser,
			resolvedSetModalOpen
		]);
		const isThreadIdControlledRef = (0, react.useRef)(isThreadIdControlled);
		isThreadIdControlledRef.current = isThreadIdControlled;
		const ownSetActiveThreadId = (0, react.useCallback)((id, options) => {
			setActiveThreadOverride({
				threadId: id,
				explicit: options?.explicit ?? true
			});
		}, []);
		const ownStartNewThread = (0, react.useCallback)(() => {
			setActiveThreadOverride({
				threadId: (0, _copilotkit_shared.randomUUID)(),
				explicit: false
			});
		}, []);
		const parentSetActiveThreadId = parentConfig?.setActiveThreadId;
		const parentStartNewThread = parentConfig?.startNewThread;
		const resolvedSetActiveThreadId = (0, react.useCallback)((id, options) => {
			if (isThreadIdControlledRef.current) {
				console.warn("[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
				return;
			}
			if (parentSetActiveThreadId) {
				parentSetActiveThreadId(id, options);
				return;
			}
			ownSetActiveThreadId(id, options);
		}, [parentSetActiveThreadId, ownSetActiveThreadId]);
		const resolvedStartNewThread = (0, react.useCallback)(() => {
			if (isThreadIdControlledRef.current) {
				console.warn("[CopilotKit] Ignoring startNewThread(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
				return;
			}
			if (parentStartNewThread) {
				parentStartNewThread();
				return;
			}
			ownStartNewThread();
		}, [parentStartNewThread, ownStartNewThread]);
		const setModalOpenWithDrawerExclusion = (0, react.useCallback)((open) => {
			if (open && isMobileViewport()) resolvedSetDrawerOpen(false);
			resolvedSetModalOpen(open);
		}, [resolvedSetModalOpen, resolvedSetDrawerOpen]);
		const configurationValue = (0, react.useMemo)(() => ({
			labels: mergedLabels,
			agentId: resolvedAgentId,
			threadId: resolvedThreadId,
			hasExplicitThreadId: resolvedHasExplicitThreadId,
			isModalOpen: resolvedIsModalOpen,
			setModalOpen: setModalOpenWithDrawerExclusion,
			drawerOpen: resolvedDrawerOpen,
			setDrawerOpen: resolvedSetDrawerOpen,
			drawerRegistered: resolvedDrawerRegistered,
			registerDrawer: resolvedRegisterDrawer,
			ɵregisterModalCloser: resolvedRegisterModalCloser,
			setActiveThreadId: resolvedSetActiveThreadId,
			startNewThread: resolvedStartNewThread
		}), [
			mergedLabels,
			resolvedAgentId,
			resolvedThreadId,
			resolvedHasExplicitThreadId,
			resolvedIsModalOpen,
			setModalOpenWithDrawerExclusion,
			resolvedDrawerOpen,
			resolvedSetDrawerOpen,
			resolvedDrawerRegistered,
			resolvedRegisterDrawer,
			resolvedRegisterModalCloser,
			resolvedSetActiveThreadId,
			resolvedStartNewThread
		]);
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfiguration.Provider, {
			value: configurationValue,
			children
		});
	};
	const useCopilotChatConfiguration = () => {
		return (0, react.useContext)(CopilotChatConfiguration);
	};

//#endregion
//#region src/v2/lib/react-core.ts
	var CopilotKitCoreReact = class extends _copilotkit_core.CopilotKitCore {
		constructor(config) {
			super(config);
			this._renderToolCalls = [];
			this._hookRenderToolCalls = /* @__PURE__ */ new Map();
			this._cachedMergedRenderToolCalls = null;
			this._renderCustomMessages = [];
			this._renderActivityMessages = [];
			this._interruptElement = null;
			this._renderToolCalls = config.renderToolCalls ?? [];
			this._renderCustomMessages = config.renderCustomMessages ?? [];
			this._renderActivityMessages = config.renderActivityMessages ?? [];
		}
		get renderCustomMessages() {
			return this._renderCustomMessages;
		}
		get renderActivityMessages() {
			return this._renderActivityMessages;
		}
		get renderToolCalls() {
			if (this._hookRenderToolCalls.size === 0) return this._renderToolCalls;
			if (this._cachedMergedRenderToolCalls) return this._cachedMergedRenderToolCalls;
			const merged = /* @__PURE__ */ new Map();
			for (const rc of this._renderToolCalls) merged.set(`${rc.agentId ?? ""}:${rc.name}`, rc);
			for (const [key, rc] of this._hookRenderToolCalls) merged.set(key, rc);
			this._cachedMergedRenderToolCalls = Array.from(merged.values());
			return this._cachedMergedRenderToolCalls;
		}
		setRenderActivityMessages(renderers) {
			this._renderActivityMessages = renderers;
		}
		setRenderCustomMessages(renderers) {
			this._renderCustomMessages = renderers;
		}
		setRenderToolCalls(renderToolCalls) {
			this._renderToolCalls = renderToolCalls;
			this._cachedMergedRenderToolCalls = null;
			this._notifyRenderToolCallsChanged();
		}
		addHookRenderToolCall(entry) {
			const key = `${entry.agentId ?? ""}:${entry.name}`;
			this._hookRenderToolCalls.set(key, entry);
			this._cachedMergedRenderToolCalls = null;
			this._notifyRenderToolCallsChanged();
		}
		removeHookRenderToolCall(name, agentId) {
			const key = `${agentId ?? ""}:${name}`;
			if (this._hookRenderToolCalls.delete(key)) {
				this._cachedMergedRenderToolCalls = null;
				this._notifyRenderToolCallsChanged();
			}
		}
		_notifyRenderToolCallsChanged() {
			this.notifySubscribers((subscriber) => {
				const reactSubscriber = subscriber;
				if (reactSubscriber.onRenderToolCallsChanged) reactSubscriber.onRenderToolCallsChanged({
					copilotkit: this,
					renderToolCalls: this.renderToolCalls
				});
			}, "Subscriber onRenderToolCallsChanged error:");
		}
		get interruptElement() {
			return this._interruptElement;
		}
		setInterruptElement(element) {
			this._interruptElement = element;
			this.notifySubscribers((subscriber) => {
				subscriber.onInterruptElementChanged?.({
					copilotkit: this,
					interruptElement: this._interruptElement
				});
			}, "Subscriber onInterruptElementChanged error:");
		}
		subscribe(subscriber) {
			return super.subscribe(subscriber);
		}
		/**
		* Wait for pending React state updates before the follow-up agent run.
		*
		* When a frontend tool handler calls setState(), React 18 batches the update
		* and schedules a commit via its internal scheduler (MessageChannel). The
		* useAgentContext hook registers context via useLayoutEffect, which runs
		* synchronously after React commits that batch.
		*
		* Awaiting a zero-delay timeout yields to the macrotask queue. React's
		* MessageChannel task runs first, committing the pending state and running
		* useLayoutEffect (which updates the context store). The follow-up runAgent
		* call then reads fresh context.
		*/
		async waitForPendingFrameworkUpdates() {
			await new Promise((resolve) => setTimeout(resolve, 0));
		}
	};

//#endregion
//#region src/v2/context.ts
	const CopilotKitContext = (0, react.createContext)(null);
	const useCopilotKit = () => {
		const context = (0, react.useContext)(CopilotKitContext);
		const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
		if (!context) throw new Error("useCopilotKit must be used within CopilotKitProvider");
		(0, react.useEffect)(() => {
			const subscription = context.copilotkit.subscribe({
				onRuntimeConnectionStatusChanged: () => {
					forceUpdate();
				},
				onHeadersChanged: () => {
					forceUpdate();
				}
			});
			return () => {
				subscription.unsubscribe();
			};
		}, []);
		return context;
	};
	const LicenseContext = (0, react.createContext)({
		status: null,
		license: null,
		checkFeature: () => true,
		getLimit: () => null
	});

//#endregion
//#region src/v2/hooks/use-render-tool-call.tsx
/**
	* Memoized component that renders a single tool call.
	* This prevents unnecessary re-renders when parent components update
	* but the tool call data hasn't changed.
	*/
	const ToolCallRenderer = react.default.memo(function ToolCallRenderer({ toolCall, toolMessage, RenderComponent, isExecuting }) {
		const args = (0, react.useMemo)(() => (0, _copilotkit_shared.partialJSONParse)(toolCall.function.arguments), [toolCall.function.arguments]);
		const toolName = toolCall.function.name;
		if (toolMessage) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
			name: toolName,
			toolCallId: toolCall.id,
			args,
			status: _copilotkit_core.ToolCallStatus.Complete,
			result: toolMessage.content
		});
		else if (isExecuting) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
			name: toolName,
			toolCallId: toolCall.id,
			args,
			status: _copilotkit_core.ToolCallStatus.Executing,
			result: void 0
		});
		else return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
			name: toolName,
			toolCallId: toolCall.id,
			args,
			status: _copilotkit_core.ToolCallStatus.InProgress,
			result: void 0
		});
	}, (prevProps, nextProps) => {
		if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;
		if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name) return false;
		if (prevProps.toolCall.function.arguments !== nextProps.toolCall.function.arguments) return false;
		if (prevProps.toolMessage?.content !== nextProps.toolMessage?.content) return false;
		if (prevProps.isExecuting !== nextProps.isExecuting) return false;
		if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;
		return true;
	});
	/**
	* Hook that returns a function to render tool calls based on the render functions
	* defined in CopilotKitProvider.
	*
	* @returns A function that takes a tool call and optional tool message and returns the rendered component
	*/
	function useRenderToolCall$1() {
		const { copilotkit, executingToolCallIds } = useCopilotKit();
		const agentId = useCopilotChatConfiguration()?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
		const renderToolCalls = (0, react.useSyncExternalStore)((callback) => {
			return copilotkit.subscribe({ onRenderToolCallsChanged: callback }).unsubscribe;
		}, () => copilotkit.renderToolCalls, () => copilotkit.renderToolCalls);
		return (0, react.useCallback)(({ toolCall, toolMessage }) => {
			const exactMatches = renderToolCalls.filter((rc) => rc.name === toolCall.function.name);
			const renderConfig = exactMatches.find((rc) => rc.agentId === agentId) || exactMatches.find((rc) => !rc.agentId) || exactMatches[0] || renderToolCalls.find((rc) => rc.name === "*");
			if (!renderConfig) return null;
			const RenderComponent = renderConfig.render;
			return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolCallRenderer, {
				toolCall,
				toolMessage,
				RenderComponent,
				isExecuting: executingToolCallIds.has(toolCall.id)
			}, toolCall.id);
		}, [
			renderToolCalls,
			executingToolCallIds,
			agentId
		]);
	}

//#endregion
//#region src/v2/components/CopilotKitInspector.tsx
	const CopilotKitInspector = ({ core, openRequest, ...rest }) => {
		const [InspectorComponent, setInspectorComponent] = react.useState(null);
		const inspectorRef = react.useRef(null);
		react.useEffect(() => {
			let mounted = true;
			import("@copilotkit/web-inspector").then((mod) => {
				mod.defineWebInspector?.();
				const Component = (0, _lit_labs_react.createComponent)({
					tagName: mod.WEB_INSPECTOR_TAG,
					elementClass: mod.WebInspectorElement,
					react
				});
				if (mounted) setInspectorComponent(() => Component);
			});
			return () => {
				mounted = false;
			};
		}, []);
		react.useEffect(() => {
			if (openRequest) inspectorRef.current?.openInspector("message_toolbar", openRequest);
		}, [InspectorComponent, openRequest]);
		if (!InspectorComponent) return null;
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(InspectorComponent, {
			ref: inspectorRef,
			...rest,
			core: core ?? null
		});
	};
	CopilotKitInspector.displayName = "CopilotKitInspector";

//#endregion
//#region src/v2/components/CopilotKitInspectorContext.tsx
	const CopilotKitInspectorContext = react.createContext({
		isLocalInspectorEnabled: false,
		openInspector: () => void 0
	});
	const CopilotKitInspectorContextProvider = CopilotKitInspectorContext.Provider;

//#endregion
//#region src/v2/components/license-warning-banner.tsx
	const LICENSE_BANNER_OFFSET_PX = 52;
	const LICENSE_BANNER_OFFSET_VAR = "--copilotkit-license-banner-offset";
	const BANNER_STYLES = {
		base: {
			position: "fixed",
			bottom: "8px",
			left: "50%",
			transform: "translateX(-50%)",
			zIndex: 99999,
			display: "inline-flex",
			alignItems: "center",
			gap: "12px",
			whiteSpace: "nowrap",
			padding: "8px 16px",
			fontSize: "13px",
			fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif",
			borderRadius: "6px",
			boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)"
		},
		info: {
			backgroundColor: "#eff6ff",
			border: "1px solid #93c5fd",
			color: "#1e40af"
		},
		warning: {
			backgroundColor: "#fffbeb",
			border: "1px solid #fbbf24",
			color: "#92400e"
		},
		critical: {
			backgroundColor: "#fef2f2",
			border: "1px solid #fca5a5",
			color: "#991b1b"
		}
	};
	function getSeverityStyle(severity) {
		switch (severity) {
			case "warning": return BANNER_STYLES.warning;
			case "critical": return BANNER_STYLES.critical;
			default: return BANNER_STYLES.info;
		}
	}
	function BannerShell({ severity, message, actionLabel, actionUrl, onDismiss }) {
		(0, react.useEffect)(() => {
			if (typeof document === "undefined") return;
			const root = document.documentElement;
			root.style.setProperty(LICENSE_BANNER_OFFSET_VAR, `${LICENSE_BANNER_OFFSET_PX}px`);
			return () => {
				root.style.removeProperty(LICENSE_BANNER_OFFSET_VAR);
			};
		}, []);
		return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
			style: {
				...BANNER_STYLES.base,
				...getSeverityStyle(severity)
			},
			children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: message }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				style: {
					display: "flex",
					gap: "8px",
					alignItems: "center"
				},
				children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
					href: actionUrl,
					target: "_blank",
					rel: "noopener noreferrer",
					style: {
						fontWeight: 600,
						textDecoration: "underline",
						color: "inherit"
					},
					children: actionLabel
				}), onDismiss && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
					onClick: onDismiss,
					style: {
						background: "none",
						border: "none",
						cursor: "pointer",
						color: "inherit",
						fontSize: "16px"
					},
					children: "×"
				})]
			})]
		});
	}
	function LicenseWarningBanner({ type, featureName, expiryDate, graceRemaining, onDismiss }) {
		switch (type) {
			case "no_license": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BannerShell, {
				severity: "info",
				message: "Powered by CopilotKit",
				actionLabel: "Get a license",
				actionUrl: "https://copilotkit.ai/pricing",
				onDismiss
			});
			case "feature_unlicensed": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BannerShell, {
				severity: "warning",
				message: `⚠ The "${featureName}" feature requires a CopilotKit license.`,
				actionLabel: "Get a license",
				actionUrl: "https://copilotkit.ai/pricing",
				onDismiss
			});
			case "expiring": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BannerShell, {
				severity: "warning",
				message: `Your CopilotKit license expires in ${graceRemaining} day${graceRemaining !== 1 ? "s" : ""}. Please renew.`,
				actionLabel: "Renew",
				actionUrl: "https://dashboard.operations.copilotkit.ai",
				onDismiss
			});
			case "expired": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BannerShell, {
				severity: "critical",
				message: `Your CopilotKit license expired${expiryDate ? ` on ${expiryDate}` : ""}. Please renew at copilotkit.ai/pricing`,
				actionLabel: "Renew now",
				actionUrl: "https://copilotkit.ai/pricing",
				onDismiss
			});
			case "invalid": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BannerShell, {
				severity: "critical",
				message: "Invalid CopilotKit license token. Please check your configuration.",
				actionLabel: "Get a license",
				actionUrl: "https://copilotkit.ai/pricing",
				onDismiss
			});
			default: return null;
		}
	}

//#endregion
//#region src/v2/components/MCPAppsActivityRenderer.tsx
/**
	* Run an MCP app `ui/message` follow-up, scoped to the thread it was enqueued
	* for (issue #5819).
	*
	* The MCP request queue delays follow-up work until the agent is idle. There is
	* a single shared registry agent per id, and switching threads overwrites its
	* `threadId`/`messages` in place. So if the host switches threads while a
	* follow-up is queued, running it now would execute against — and stream into —
	* the now-foreground thread.
	*
	* - **Same thread** (the common case): run on the shared agent, unchanged.
	* - **Thread changed**: the shared agent has moved on, so the follow-up can no
	*   longer run in its originating thread's context. Drop it rather than leak it
	*   into the current thread. (The MCP app already received its `ui/message` ack
	*   at enqueue time; only the optional agent turn is skipped.)
	*
	* @internal exported for testing.
	*/
	async function ɵrunMcpFollowUp({ host, agent, capturedThreadId }) {
		const currentThreadId = agent.threadId || "default";
		const originThreadId = capturedThreadId || "default";
		if (currentThreadId === originThreadId) return host.runAgent({ agent });
		console.warn(`[MCPAppsRenderer] ui/message follow-up dropped: the thread changed (${originThreadId} → ${currentThreadId}) between enqueue and execution, so running it would leak into the now-foreground thread.`);
		return {
			result: void 0,
			newMessages: []
		};
	}
	const PROTOCOL_VERSION = "2025-06-18";
	function buildSandboxHTML(extraCspDomains) {
		const baseScriptSrc = "'self' 'wasm-unsafe-eval' 'unsafe-inline' 'unsafe-eval' blob: data: http://localhost:* https://localhost:*";
		const baseFrameSrc = "* blob: data: http://localhost:* https://localhost:*";
		const extra = extraCspDomains?.length ? " " + extraCspDomains.join(" ") : "";
		return `<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src * data: blob: 'unsafe-inline'; media-src * blob: data:; font-src * blob: data:; script-src ${baseScriptSrc + extra}; style-src * blob: data: 'unsafe-inline'; connect-src *; frame-src ${baseFrameSrc + extra}; base-uri 'self';" />
<style>html,body{margin:0;padding:0;height:100%;width:100%;overflow:hidden}*{box-sizing:border-box}iframe{background-color:transparent;border:none;padding:0;overflow:hidden;width:100%;height:100%}</style>
</head>
<body>
<script>
if(window.self===window.top){throw new Error("This file must be used in an iframe.")}
const inner=document.createElement("iframe");
inner.style="width:100%;height:100%;border:none;";
inner.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms");
document.body.appendChild(inner);
window.addEventListener("message",async(event)=>{
if(event.source===window.parent){
if(event.data&&event.data.method==="ui/notifications/sandbox-resource-ready"){
const{html,sandbox}=event.data.params;
if(typeof sandbox==="string")inner.setAttribute("sandbox",sandbox);
if(typeof html==="string")inner.srcdoc=html;
}else if(inner&&inner.contentWindow){
inner.contentWindow.postMessage(event.data,"*");
}
}else if(event.source===inner.contentWindow){
window.parent.postMessage(event.data,"*");
}
});
window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-ready",params:{}},"*");
<\/script>
</body>
</html>`;
	}
	/**
	* Queue for serializing MCP app requests to an agent.
	* Ensures requests wait for the agent to stop running and are processed one at a time.
	*/
	var MCPAppsRequestQueue = class {
		constructor() {
			this.queues = /* @__PURE__ */ new Map();
			this.processing = /* @__PURE__ */ new Map();
		}
		/**
		* Add a request to the queue for a specific agent thread.
		* Returns a promise that resolves when the request completes.
		*/
		async enqueue(agent, request) {
			const threadId = agent.threadId || "default";
			return new Promise((resolve, reject) => {
				let queue = this.queues.get(threadId);
				if (!queue) {
					queue = [];
					this.queues.set(threadId, queue);
				}
				queue.push({
					execute: request,
					resolve,
					reject
				});
				this.processQueue(threadId, agent);
			});
		}
		async processQueue(threadId, agent) {
			if (this.processing.get(threadId)) return;
			this.processing.set(threadId, true);
			try {
				const queue = this.queues.get(threadId);
				if (!queue) return;
				while (queue.length > 0) {
					const item = queue[0];
					try {
						await this.waitForAgentIdle(agent);
						const result = await item.execute();
						item.resolve(result);
					} catch (error) {
						item.reject(error instanceof Error ? error : new Error(String(error)));
					}
					queue.shift();
				}
			} finally {
				this.processing.set(threadId, false);
			}
		}
		waitForAgentIdle(agent) {
			return new Promise((resolve) => {
				if (!agent.isRunning) {
					resolve();
					return;
				}
				let done = false;
				const finish = () => {
					if (done) return;
					done = true;
					clearInterval(checkInterval);
					sub.unsubscribe();
					resolve();
				};
				const sub = agent.subscribe({
					onRunFinalized: finish,
					onRunFailed: finish
				});
				const checkInterval = setInterval(() => {
					if (!agent.isRunning) finish();
				}, 500);
			});
		}
	};
	const mcpAppsRequestQueue = new MCPAppsRequestQueue();
	/**
	* Activity type for MCP Apps events - must match the middleware's MCPAppsActivityType
	*/
	const MCPAppsActivityType = "mcp-apps";
	const MCPAppsActivityContentSchema = zod.z.object({
		result: zod.z.object({
			content: zod.z.array(zod.z.any()).optional(),
			structuredContent: zod.z.any().optional(),
			isError: zod.z.boolean().optional()
		}),
		resourceUri: zod.z.string(),
		serverHash: zod.z.string(),
		serverId: zod.z.string().optional(),
		toolInput: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
	});
	function isRequest(msg) {
		return "id" in msg && "method" in msg;
	}
	function isNotification(msg) {
		return !("id" in msg) && "method" in msg;
	}
	/**
	* MCP Apps Extension Activity Renderer
	*
	* Renders MCP Apps UI in a sandboxed iframe with full protocol support.
	* Fetches resource content on-demand via proxied MCP requests.
	*/
	const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, agent }) {
		const { copilotkit } = useCopilotKit();
		const containerRef = (0, react.useRef)(null);
		const iframeRef = (0, react.useRef)(null);
		const [iframeReady, setIframeReady] = (0, react.useState)(false);
		const [error, setError] = (0, react.useState)(null);
		const [isLoading, setIsLoading] = (0, react.useState)(true);
		const [iframeSize, setIframeSize] = (0, react.useState)({});
		const [fetchedResource, setFetchedResource] = (0, react.useState)(null);
		const contentRef = (0, react.useRef)(content);
		contentRef.current = content;
		const agentRef = (0, react.useRef)(agent);
		agentRef.current = agent;
		const fetchStateRef = (0, react.useRef)({
			inProgress: false,
			promise: null,
			resourceUri: null
		});
		const sendToIframe = (0, react.useCallback)((msg) => {
			if (iframeRef.current?.contentWindow) {
				console.log("[MCPAppsRenderer] Sending to iframe:", msg);
				iframeRef.current.contentWindow.postMessage(msg, "*");
			}
		}, []);
		const sendResponse = (0, react.useCallback)((id, result) => {
			sendToIframe({
				jsonrpc: "2.0",
				id,
				result
			});
		}, [sendToIframe]);
		const sendErrorResponse = (0, react.useCallback)((id, code, message) => {
			sendToIframe({
				jsonrpc: "2.0",
				id,
				error: {
					code,
					message
				}
			});
		}, [sendToIframe]);
		const sendNotification = (0, react.useCallback)((method, params) => {
			sendToIframe({
				jsonrpc: "2.0",
				method,
				params: params || {}
			});
		}, [sendToIframe]);
		(0, react.useEffect)(() => {
			const { resourceUri, serverHash, serverId } = content;
			if (fetchStateRef.current.inProgress && fetchStateRef.current.resourceUri === resourceUri) {
				fetchStateRef.current.promise?.then((resource) => {
					if (resource) {
						setFetchedResource(resource);
						setIsLoading(false);
					}
				}).catch((err) => {
					setError(err instanceof Error ? err : new Error(String(err)));
					setIsLoading(false);
				});
				return;
			}
			if (!agent) {
				setError(/* @__PURE__ */ new Error("No agent available to fetch resource"));
				setIsLoading(false);
				return;
			}
			fetchStateRef.current.inProgress = true;
			fetchStateRef.current.resourceUri = resourceUri;
			const fetchPromise = (async () => {
				try {
					const resource = (await mcpAppsRequestQueue.enqueue(agent, () => agent.runAgent({ forwardedProps: { __proxiedMCPRequest: {
						serverHash,
						serverId,
						method: "resources/read",
						params: { uri: resourceUri }
					} } }))).result?.contents?.[0];
					if (!resource) throw new Error("No resource content in response");
					return resource;
				} catch (err) {
					console.error("[MCPAppsRenderer] Failed to fetch resource:", err);
					throw err;
				} finally {
					fetchStateRef.current.inProgress = false;
				}
			})();
			fetchStateRef.current.promise = fetchPromise;
			fetchPromise.then((resource) => {
				if (resource) {
					setFetchedResource(resource);
					setIsLoading(false);
				}
			}).catch((err) => {
				setError(err instanceof Error ? err : new Error(String(err)));
				setIsLoading(false);
			});
		}, [agent, content]);
		(0, react.useEffect)(() => {
			if (isLoading || !fetchedResource) return;
			const container = containerRef.current;
			if (!container) return;
			let mounted = true;
			let messageHandler = null;
			let initialListener = null;
			let createdIframe = null;
			const setup = async () => {
				try {
					const iframe = document.createElement("iframe");
					createdIframe = iframe;
					iframe.style.width = "100%";
					iframe.style.height = "100px";
					iframe.style.border = "none";
					iframe.style.backgroundColor = "transparent";
					iframe.style.display = "block";
					iframe.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms");
					iframe.setAttribute("data-testid", "mcp-app-iframe");
					iframe.setAttribute("title", "Interactive MCP application");
					const sandboxReady = new Promise((resolve) => {
						initialListener = (event) => {
							if (event.source === iframe.contentWindow) {
								if (event.data?.method === "ui/notifications/sandbox-proxy-ready") {
									if (initialListener) {
										window.removeEventListener("message", initialListener);
										initialListener = null;
									}
									resolve();
								}
							}
						};
						window.addEventListener("message", initialListener);
					});
					if (!mounted) {
						if (initialListener) {
							window.removeEventListener("message", initialListener);
							initialListener = null;
						}
						return;
					}
					const cspDomains = fetchedResource._meta?.ui?.csp?.resourceDomains;
					iframe.srcdoc = buildSandboxHTML(cspDomains);
					iframeRef.current = iframe;
					container.appendChild(iframe);
					await sandboxReady;
					if (!mounted) return;
					console.log("[MCPAppsRenderer] Sandbox proxy ready");
					messageHandler = async (event) => {
						if (event.source !== iframe.contentWindow) return;
						const msg = event.data;
						if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0") return;
						console.log("[MCPAppsRenderer] Received from iframe:", msg);
						if (isRequest(msg)) switch (msg.method) {
							case "ui/initialize":
								sendResponse(msg.id, {
									protocolVersion: PROTOCOL_VERSION,
									hostInfo: {
										name: "CopilotKit MCP Apps Host",
										version: "1.0.0"
									},
									hostCapabilities: {
										openLinks: {},
										logging: {}
									},
									hostContext: {
										theme: "light",
										platform: "web"
									}
								});
								break;
							case "ui/message": {
								const currentAgent = agentRef.current;
								if (!currentAgent) {
									console.warn("[MCPAppsRenderer] ui/message: No agent available");
									sendResponse(msg.id, { isError: false });
									break;
								}
								try {
									const params = msg.params;
									const role = params.role || "user";
									const textContent = params.content?.filter((c) => c.type === "text" && c.text).map((c) => c.text).join("\n") || "";
									if (textContent) currentAgent.addMessage({
										id: crypto.randomUUID(),
										role,
										content: textContent
									});
									sendResponse(msg.id, { isError: false });
									if ((params.followUp ?? role === "user") && textContent) {
										const capturedThreadId = currentAgent.threadId || "default";
										mcpAppsRequestQueue.enqueue(currentAgent, () => ɵrunMcpFollowUp({
											host: copilotkit,
											agent: currentAgent,
											capturedThreadId
										})).catch((err) => console.error("[MCPAppsRenderer] ui/message agent run failed:", err));
									}
								} catch (err) {
									console.error("[MCPAppsRenderer] ui/message error:", err);
									sendResponse(msg.id, { isError: true });
								}
								break;
							}
							case "ui/open-link": {
								const url = msg.params?.url;
								if (url) {
									window.open(url, "_blank", "noopener,noreferrer");
									sendResponse(msg.id, { isError: false });
								} else sendErrorResponse(msg.id, -32602, "Missing url parameter");
								break;
							}
							case "tools/call": {
								const { serverHash, serverId } = contentRef.current;
								const currentAgent = agentRef.current;
								if (!serverHash) {
									sendErrorResponse(msg.id, -32603, "No server hash available for proxying");
									break;
								}
								if (!currentAgent) {
									sendErrorResponse(msg.id, -32603, "No agent available for proxying");
									break;
								}
								try {
									const runResult = await mcpAppsRequestQueue.enqueue(currentAgent, () => currentAgent.runAgent({ forwardedProps: { __proxiedMCPRequest: {
										serverHash,
										serverId,
										method: "tools/call",
										params: msg.params
									} } }));
									sendResponse(msg.id, runResult.result || {});
								} catch (err) {
									console.error("[MCPAppsRenderer] tools/call error:", err);
									sendErrorResponse(msg.id, -32603, String(err));
								}
								break;
							}
							default: sendErrorResponse(msg.id, -32601, `Method not found: ${msg.method}`);
						}
						if (isNotification(msg)) switch (msg.method) {
							case "ui/notifications/initialized":
								console.log("[MCPAppsRenderer] Inner iframe initialized");
								if (mounted) setIframeReady(true);
								break;
							case "ui/notifications/size-changed": {
								const { width, height } = msg.params || {};
								console.log("[MCPAppsRenderer] Size change:", {
									width,
									height
								});
								if (mounted) setIframeSize({
									width: typeof width === "number" ? width : void 0,
									height: typeof height === "number" ? height : void 0
								});
								break;
							}
							case "notifications/message":
								console.log("[MCPAppsRenderer] App log:", msg.params);
								break;
						}
					};
					window.addEventListener("message", messageHandler);
					let html;
					if (fetchedResource.text) html = fetchedResource.text;
					else if (fetchedResource.blob) html = atob(fetchedResource.blob);
					else throw new Error("Resource has no text or blob content");
					sendNotification("ui/notifications/sandbox-resource-ready", { html });
				} catch (err) {
					console.error("[MCPAppsRenderer] Setup error:", err);
					if (mounted) setError(err instanceof Error ? err : new Error(String(err)));
				}
			};
			setup();
			return () => {
				mounted = false;
				if (initialListener) {
					window.removeEventListener("message", initialListener);
					initialListener = null;
				}
				if (messageHandler) window.removeEventListener("message", messageHandler);
				if (createdIframe) {
					createdIframe.remove();
					createdIframe = null;
				}
				iframeRef.current = null;
			};
		}, [
			isLoading,
			fetchedResource,
			sendNotification,
			sendResponse,
			sendErrorResponse
		]);
		(0, react.useEffect)(() => {
			if (iframeRef.current) {
				if (iframeSize.width !== void 0) {
					iframeRef.current.style.minWidth = `min(${iframeSize.width}px, 100%)`;
					iframeRef.current.style.width = "100%";
				}
				if (iframeSize.height !== void 0) iframeRef.current.style.height = `${iframeSize.height}px`;
			}
		}, [iframeSize]);
		(0, react.useEffect)(() => {
			if (iframeReady && content.toolInput) {
				console.log("[MCPAppsRenderer] Sending tool input:", content.toolInput);
				sendNotification("ui/notifications/tool-input", { arguments: content.toolInput });
			}
		}, [
			iframeReady,
			content.toolInput,
			sendNotification
		]);
		(0, react.useEffect)(() => {
			if (iframeReady && content.result) {
				console.log("[MCPAppsRenderer] Sending tool result:", content.result);
				sendNotification("ui/notifications/tool-result", content.result);
			}
		}, [
			iframeReady,
			content.result,
			sendNotification
		]);
		const borderStyle = fetchedResource?._meta?.ui?.prefersBorder === true ? {
			borderRadius: "8px",
			backgroundColor: "#f9f9f9",
			border: "1px solid #e0e0e0"
		} : {};
		return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
			ref: containerRef,
			style: {
				width: "100%",
				height: iframeSize.height ? `${iframeSize.height}px` : "auto",
				minHeight: "100px",
				overflow: "hidden",
				position: "relative",
				...borderStyle
			},
			children: [isLoading && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
				style: {
					padding: "1rem",
					color: "#666"
				},
				children: "Loading..."
			}), error && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				style: {
					color: "red",
					padding: "1rem"
				},
				children: ["Error: ", error.message]
			})]
		});
	};

//#endregion
//#region src/v2/providers/SandboxFunctionsContext.ts
	const SandboxFunctionsContext = (0, react.createContext)([]);
	function useSandboxFunctions() {
		return (0, react.useContext)(SandboxFunctionsContext);
	}

//#endregion
//#region src/v2/lib/processPartialHtml.ts
/**
	* Extracts all complete `<style>` blocks from the raw HTML.
	* Returns the concatenated style tags, suitable for injection into `<head>`.
	*/
	function extractCompleteStyles(html) {
		const matches = html.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi);
		return matches ? matches.join("") : "";
	}
	/**
	* Processes raw accumulated HTML for safe preview via innerHTML injection.
	* Pure function, no DOM dependencies.
	*
	* Pipeline (order matters):
	* 1. Strip incomplete tag at end
	* 2. Strip complete <style>, <script>, and <head> blocks
	* 3. Strip incomplete <style>/<script>/<head> blocks
	* 4. Strip incomplete HTML entities
	* 5. Extract body content (or use full string if no <body>)
	*/
	function processPartialHtml(html) {
		let result = html;
		result = result.replace(/<[^>]*$/, "");
		result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*?<\/\1>/gi, "");
		result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*$/gi, "");
		result = result.replace(/&[a-zA-Z0-9#]*$/, "");
		const bodyMatch = result.match(/<body[^>]*>([\s\S]*)/i);
		if (bodyMatch) {
			result = bodyMatch[1];
			result = result.replace(/<\/body>[\s\S]*/i, "");
		}
		return result;
	}

//#endregion
//#region src/v2/components/OpenGenerativeUIRenderer.tsx
	const OpenGenerativeUIActivityType = "open-generative-ui";
	const OpenGenerativeUIContentSchema = zod.z.object({
		initialHeight: zod.z.number().optional(),
		generating: zod.z.boolean().optional(),
		css: zod.z.string().optional(),
		cssComplete: zod.z.boolean().optional(),
		html: zod.z.array(zod.z.string()).optional(),
		htmlComplete: zod.z.boolean().optional(),
		jsFunctions: zod.z.string().optional(),
		jsFunctionsComplete: zod.z.boolean().optional(),
		jsExpressions: zod.z.array(zod.z.string()).optional(),
		jsExpressionsComplete: zod.z.boolean().optional()
	});
	/**
	* Schema for the generateSandboxedUi tool call arguments.
	* Used by the frontend tool renderer to display placeholder messages.
	*/
	const GenerateSandboxedUiArgsSchema = zod.z.object({
		initialHeight: zod.z.number().optional(),
		placeholderMessages: zod.z.array(zod.z.string()).optional(),
		css: zod.z.string().optional(),
		html: zod.z.string().optional(),
		jsFunctions: zod.z.string().optional(),
		jsExpressions: zod.z.array(zod.z.string()).optional()
	});
	const THROTTLE_MS = 1e3;
	/**
	* Returns true when the inner component should re-render immediately
	* (no throttle delay).
	*/
	function shouldFlushImmediately(prev, next) {
		if (next.cssComplete && (!prev || !prev.cssComplete)) return true;
		if (next.htmlComplete) return true;
		if (next.generating === false) return true;
		if (next.jsFunctions && (!prev || !prev.jsFunctions)) return true;
		if ((next.jsExpressions?.length ?? 0) > (prev?.jsExpressions?.length ?? 0)) return true;
		if (next.html?.length && (!prev || !prev.html?.length)) return true;
		return false;
	}
	/**
	* Outer wrapper — absorbs every parent re-render but only forwards
	* throttled content snapshots to the memoized inner component.
	*/
	const OpenGenerativeUIActivityRenderer = function OpenGenerativeUIActivityRenderer({ content }) {
		const latestContentRef = (0, react.useRef)(content);
		latestContentRef.current = content;
		const [throttledContent, setThrottledContent] = (0, react.useState)(content);
		const throttledContentRef = (0, react.useRef)(throttledContent);
		const timerRef = (0, react.useRef)(null);
		if (throttledContentRef.current !== content) {
			if (shouldFlushImmediately(throttledContentRef.current, content)) {
				if (timerRef.current !== null) {
					clearTimeout(timerRef.current);
					timerRef.current = null;
				}
				throttledContentRef.current = content;
				setThrottledContent(content);
			}
		}
		const flush = (0, react.useCallback)(() => {
			timerRef.current = null;
			const latest = latestContentRef.current;
			throttledContentRef.current = latest;
			setThrottledContent(latest);
		}, []);
		(0, react.useEffect)(() => {
			if (throttledContentRef.current === content) return;
			if (timerRef.current === null) timerRef.current = setTimeout(flush, THROTTLE_MS);
		}, [content, flush]);
		(0, react.useEffect)(() => {
			return () => {
				if (timerRef.current !== null) clearTimeout(timerRef.current);
			};
		}, []);
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OpenGenerativeUIActivityRendererInner, { content: throttledContent });
	};
	function ensureHead(html) {
		if (/<head[\s>]/i.test(html)) return html;
		return `<head></head>${html}`;
	}
	function injectCssIntoHtml(html, css) {
		const headCloseIdx = html.indexOf("</head>");
		if (headCloseIdx !== -1) return html.slice(0, headCloseIdx) + `<style>${css}</style>` + html.slice(headCloseIdx);
		return `<head><style>${css}</style></head>${html}`;
	}
	const OpenGenerativeUIActivityRendererInner = react.default.memo(function OpenGenerativeUIActivityRendererInner({ content }) {
		const initialHeight = content.initialHeight ?? 200;
		const [autoHeight, setAutoHeight] = (0, react.useState)(null);
		const sandboxFunctions = useSandboxFunctions();
		const localApi = (0, react.useMemo)(() => {
			const api = {};
			for (const fn of sandboxFunctions) api[fn.name] = fn.handler;
			return api;
		}, [sandboxFunctions]);
		const fullHtml = content.htmlComplete && content.html?.length ? content.html.join("") : void 0;
		const css = content.cssComplete ? content.css : void 0;
		const cssReady = !!content.cssComplete;
		const partialHtml = !content.htmlComplete && content.html?.length ? content.html.join("") : void 0;
		const previewBody = partialHtml ? processPartialHtml(partialHtml) : void 0;
		const previewStyles = partialHtml ? extractCompleteStyles(partialHtml) : "";
		const hasPreview = cssReady && !!previewBody?.trim();
		const hasVisibleSandbox = !!fullHtml || hasPreview;
		const containerRef = (0, react.useRef)(null);
		const sandboxRef = (0, react.useRef)(null);
		const previewSandboxRef = (0, react.useRef)(null);
		const previewReadyRef = (0, react.useRef)(false);
		const sandboxReadyRef = (0, react.useRef)(false);
		const executedIndexRef = (0, react.useRef)(0);
		const pendingQueueRef = (0, react.useRef)([]);
		const jsFunctionsInjectedRef = (0, react.useRef)(false);
		(0, react.useEffect)(() => {
			const container = containerRef.current;
			if (!container || fullHtml || !hasPreview || previewSandboxRef.current) return;
			let cancelled = false;
			import("@jetbrains/websandbox").then((mod) => {
				if (cancelled) return;
				const sandbox = (mod.default?.default ?? mod.default).create({}, {
					frameContainer: container,
					frameContent: "<head></head><body></body>",
					allowAdditionalAttributes: ""
				});
				previewSandboxRef.current = sandbox;
				sandbox.iframe.style.width = "100%";
				sandbox.iframe.style.height = "100%";
				sandbox.iframe.style.border = "none";
				sandbox.iframe.style.backgroundColor = "transparent";
				sandbox.promise.then(() => {
					if (cancelled) return;
					previewReadyRef.current = true;
					sandbox.run(`
            var s = document.createElement('style');
            s.textContent = 'html, body { overflow: hidden !important; }';
            document.head.appendChild(s);
          `);
					const headParts = [];
					if (css) headParts.push(`<style>${css}</style>`);
					if (previewStyles) headParts.push(previewStyles);
					if (headParts.length) sandbox.run(`document.head.innerHTML = ${JSON.stringify(headParts.join(""))}`);
					if (previewBody) sandbox.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
				});
			}).catch((err) => {
				console.error("[OpenGenerativeUI] Failed to load sandbox module:", err);
			});
			return () => {
				cancelled = true;
			};
		}, [hasPreview, fullHtml]);
		(0, react.useEffect)(() => {
			if (!previewSandboxRef.current || !previewReadyRef.current) return;
			const headParts = [];
			if (css) headParts.push(`<style>${css}</style>`);
			if (previewStyles) headParts.push(previewStyles);
			if (headParts.length) previewSandboxRef.current.run(`document.head.innerHTML = ${JSON.stringify(headParts.join(""))}`);
			if (!previewBody) return;
			previewSandboxRef.current.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
		}, [
			previewBody,
			previewStyles,
			css
		]);
		(0, react.useEffect)(() => {
			const container = containerRef.current;
			if (!container || !fullHtml) return;
			if (previewSandboxRef.current) {
				previewSandboxRef.current.destroy();
				previewSandboxRef.current = null;
				previewReadyRef.current = false;
			}
			let cancelled = false;
			executedIndexRef.current = 0;
			jsFunctionsInjectedRef.current = false;
			sandboxReadyRef.current = false;
			pendingQueueRef.current = [];
			const htmlContent = css ? injectCssIntoHtml(fullHtml, css) : fullHtml;
			import("@jetbrains/websandbox").then((mod) => {
				if (cancelled) return;
				const sandbox = (mod.default?.default ?? mod.default).create(localApi, {
					frameContainer: container,
					frameContent: ensureHead(htmlContent),
					allowAdditionalAttributes: ""
				});
				sandboxRef.current = sandbox;
				sandbox.iframe.style.width = "100%";
				sandbox.iframe.style.height = "100%";
				sandbox.iframe.style.border = "none";
				sandbox.iframe.style.backgroundColor = "transparent";
				sandbox.promise.then(() => {
					if (cancelled) return;
					sandboxReadyRef.current = true;
					sandbox.run(`
            var s = document.createElement('style');
            s.textContent = 'html, body { overflow: hidden !important; }';
            document.head.appendChild(s);
          `);
					const queue = pendingQueueRef.current;
					pendingQueueRef.current = [];
					for (const code of queue) sandbox.run(code);
				});
			}).catch((err) => {
				console.error("[OpenGenerativeUI] Failed to load sandbox module:", err);
			});
			return () => {
				cancelled = true;
				if (previewSandboxRef.current) {
					previewSandboxRef.current.destroy();
					previewSandboxRef.current = null;
					previewReadyRef.current = false;
				}
				if (sandboxRef.current) {
					sandboxRef.current.destroy();
					sandboxRef.current = null;
				}
				sandboxReadyRef.current = false;
				setAutoHeight(null);
			};
		}, [
			fullHtml,
			css,
			localApi
		]);
		(0, react.useEffect)(() => {
			if (!content.jsFunctions || jsFunctionsInjectedRef.current) return;
			jsFunctionsInjectedRef.current = true;
			const sandbox = sandboxRef.current;
			if (sandboxReadyRef.current && sandbox) sandbox.run(content.jsFunctions);
			else pendingQueueRef.current.push(content.jsFunctions);
		}, [content.jsFunctions]);
		(0, react.useEffect)(() => {
			const expressions = content.jsExpressions;
			if (!expressions || expressions.length === 0) return;
			const startIndex = executedIndexRef.current;
			if (startIndex >= expressions.length) return;
			const newExprs = expressions.slice(startIndex);
			executedIndexRef.current = expressions.length;
			const sandbox = sandboxRef.current;
			if (sandboxReadyRef.current && sandbox) (async () => {
				for (const expr of newExprs) await sandbox.run(expr);
			})();
			else pendingQueueRef.current.push(...newExprs);
		}, [content.jsExpressions?.length]);
		const generationDone = content.generating === false;
		(0, react.useEffect)(() => {
			const sandbox = sandboxRef.current;
			if (!generationDone || !sandbox) return;
			let handled = false;
			const onMessage = (e) => {
				if (handled) return;
				if (e.source === sandbox.iframe.contentWindow && e.data?.type === "__ck_resize") {
					handled = true;
					setAutoHeight(e.data.height);
					window.removeEventListener("message", onMessage);
				}
			};
			window.addEventListener("message", onMessage);
			const measureOnce = `
        (function() {
          var s = document.createElement('style');
          s.textContent = 'body { height: auto !important; min-height: 0 !important; }';
          document.head.appendChild(s);
          var h = document.body.scrollHeight;
          var cs = getComputedStyle(document.body);
          h += parseFloat(cs.marginTop) || 0;
          h += parseFloat(cs.marginBottom) || 0;
          s.remove();
          parent.postMessage({ type: "__ck_resize", height: Math.ceil(h) }, "*");
        })();
      `;
			if (sandboxReadyRef.current) sandbox.run(measureOnce);
			else pendingQueueRef.current.push(measureOnce);
			return () => {
				window.removeEventListener("message", onMessage);
			};
		}, [generationDone]);
		const height = autoHeight ?? initialHeight;
		const isGenerating = content.generating !== false;
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
			ref: containerRef,
			style: {
				position: "relative",
				width: "100%",
				height: `${height}px`,
				borderRadius: "8px",
				backgroundColor: hasVisibleSandbox ? "transparent" : "#f5f5f5",
				border: hasVisibleSandbox ? "none" : "1px solid #e0e0e0",
				display: hasVisibleSandbox ? "block" : "flex",
				alignItems: hasVisibleSandbox ? void 0 : "center",
				justifyContent: hasVisibleSandbox ? void 0 : "center",
				overflow: "hidden"
			},
			children: isGenerating && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				style: {
					position: "absolute",
					inset: 0,
					zIndex: 10,
					pointerEvents: "all",
					backgroundColor: "rgba(255, 255, 255, 0.5)",
					display: "flex",
					alignItems: "center",
					justifyContent: "center"
				},
				children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
					width: "48",
					height: "48",
					viewBox: "0 0 24 24",
					fill: "none",
					style: { animation: "ck-spin 1s linear infinite" },
					children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
						cx: "12",
						cy: "12",
						r: "10",
						stroke: "#e0e0e0",
						strokeWidth: "3"
					}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
						d: "M12 2a10 10 0 0 1 10 10",
						stroke: "#999",
						strokeWidth: "3",
						strokeLinecap: "round"
					})]
				}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { children: `@keyframes ck-spin { to { transform: rotate(360deg) } }` })]
			})
		});
	}, (prev, next) => prev.content === next.content);
	/**
	* Frontend tool renderer for generateSandboxedUi.
	* Displays placeholder messages while the UI is being generated.
	*/
	const OpenGenerativeUIToolRenderer = function OpenGenerativeUIToolRenderer(props) {
		const [visibleMessageIndex, setVisibleMessageIndex] = (0, react.useState)(0);
		const prevMessageCountRef = (0, react.useRef)(0);
		const messages = props.args.placeholderMessages;
		(0, react.useEffect)(() => {
			if (!messages || messages.length === 0) return;
			if (messages.length !== prevMessageCountRef.current) {
				prevMessageCountRef.current = messages.length;
				setVisibleMessageIndex(messages.length - 1);
			}
			if (props.status === _copilotkit_core.ToolCallStatus.Complete) return;
			const timer = setInterval(() => {
				setVisibleMessageIndex((i) => (i + 1) % messages.length);
			}, 5e3);
			return () => clearInterval(timer);
		}, [messages?.length, props.status]);
		if (props.status === _copilotkit_core.ToolCallStatus.Complete) return null;
		if (!messages || messages.length === 0) return null;
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
			style: {
				padding: "8px 12px",
				color: "#999",
				fontSize: "14px"
			},
			children: messages[visibleMessageIndex] ?? messages[0]
		});
	};

//#endregion
//#region src/v2/a2ui/A2UIRecoveryStates.tsx
/**
	* The pre-paint lifecycle fields the middleware stamps onto the `a2ui-surface`
	* activity content (alongside `a2ui_operations` on paint). `.passthrough()` keeps
	* `a2ui_operations` and any future fields intact.
	*/
	const A2UILifecycleFields = {
		status: zod.z.enum([
			"building",
			"retrying",
			"failed"
		]).optional(),
		attempt: zod.z.number().optional(),
		maxAttempts: zod.z.number().optional(),
		progressTokens: zod.z.number().optional(),
		error: zod.z.string().optional(),
		errors: zod.z.array(zod.z.any()).optional(),
		attempts: zod.z.array(zod.z.any()).optional(),
		debugExposure: zod.z.enum([
			"hidden",
			"collapsed",
			"verbose"
		]).optional()
	};
	/** Server-stamped debugExposure wins; else the client option; else "collapsed". */
	function resolveDebugExposure(content, optionDebugExposure) {
		return content?.debugExposure ?? optionDebugExposure;
	}
	/** building: the generic skeleton + optional live token count. */
	function A2UIBuildingState({ content }) {
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIGeneratingSkeleton, {
			label: "Building interface",
			tokens: typeof content?.progressTokens === "number" ? content.progressTokens : void 0
		});
	}
	/**
	* retrying: stays the generic skeleton through fast/transient retries; only once
	* the retry is perceptible (after `showAfterMs`, or once `attempt` crosses
	* `showAfterAttempts`) does the sub-label reveal "Retrying generation… (N/M)".
	*/
	function A2UIRetryingState({ content, showAfterMs, showAfterAttempts, debugExposure }) {
		const attempt = typeof content?.attempt === "number" ? content.attempt : void 0;
		const maxAttempts = typeof content?.maxAttempts === "number" ? content.maxAttempts : void 0;
		const immediate = attempt !== void 0 && attempt >= showAfterAttempts;
		const [revealed, setRevealed] = (0, react.useState)(immediate);
		(0, react.useEffect)(() => {
			if (immediate) {
				setRevealed(true);
				return;
			}
			const timer = setTimeout(() => setRevealed(true), showAfterMs);
			return () => clearTimeout(timer);
		}, [immediate, showAfterMs]);
		const tokens = typeof content?.progressTokens === "number" ? content.progressTokens : void 0;
		if (!revealed) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIGeneratingSkeleton, {
			label: "Building interface",
			tokens
		});
		const label = attempt !== void 0 && maxAttempts !== void 0 ? `Retrying generation… (${attempt}/${maxAttempts} attempts)` : "Retrying generation…";
		const errors = Array.isArray(content?.errors) ? content.errors : [];
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIGeneratingSkeleton, {
			label,
			tokens,
			children: debugExposure !== "hidden" && errors.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIDebugDetails, {
				label: "validation issues",
				open: debugExposure === "verbose",
				payload: {
					attempt: content?.attempt,
					errors
				}
			})
		});
	}
	/** failed: a clean hard-failure card that replaces the skeleton in place. */
	function A2UIRecoveryFailure({ content, debugExposure }) {
		return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
			className: "cpk:rounded-lg cpk:border cpk:border-amber-200 cpk:bg-amber-50 cpk:p-3 cpk:text-sm cpk:text-amber-800",
			children: [
				/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
					className: "cpk:font-medium",
					children: "Couldn't generate the UI"
				}),
				/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
					className: "cpk:mt-1 cpk:text-xs cpk:text-amber-700",
					children: "Something went wrong rendering this. You can keep chatting and try again."
				}),
				debugExposure !== "hidden" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIDebugDetails, {
					label: "developer details",
					open: debugExposure === "verbose",
					payload: {
						error: content?.error,
						attempts: content?.attempts
					}
				})
			]
		});
	}
	/**
	* Animated wireframe skeleton with a label, an optional live token count, and an
	* optional debug-detail slot below it. Pure CSS animation (no data dependency).
	* The `tokens` count drives a progressive reveal of skeleton rows.
	*/
	function A2UIGeneratingSkeleton({ label, tokens, children }) {
		const phase = tokens == null ? 3 : tokens < 50 ? 0 : tokens < 200 ? 1 : tokens < 400 ? 2 : 3;
		return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
			style: {
				margin: "12px 0",
				maxWidth: 320
			},
			children: [
				/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
					style: {
						position: "relative",
						overflow: "hidden",
						borderRadius: 12,
						border: "1px solid rgba(228,228,231,0.8)",
						backgroundColor: "#fff",
						boxShadow: "0 1px 2px rgba(0,0,0,0.04)",
						padding: "16px 18px 14px"
					},
					children: [
						/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
							style: {
								display: "flex",
								alignItems: "center",
								gap: 8,
								marginBottom: 12
							},
							children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
								style: {
									display: "flex",
									gap: 4
								},
								children: [
									/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, {}),
									/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, {}),
									/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, {})
								]
							}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
								w: 64,
								h: 6,
								bg: "#e4e4e7",
								opacity: phase >= 1 ? 1 : .4,
								transition: "opacity 0.5s"
							})]
						}),
						/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
							style: {
								display: "grid",
								gap: 7
							},
							children: [
								/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Row, {
									show: phase >= 0,
									children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
										w: 36,
										h: 7,
										bg: "rgba(147,197,253,0.7)",
										anim: 0
									}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
										w: 80,
										h: 7,
										bg: "rgba(219,234,254,0.8)",
										anim: .2
									})]
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Row, {
									show: phase >= 0,
									delay: .1,
									children: [
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Spacer, {}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, {}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 100,
											h: 7,
											bg: "rgba(24,24,27,0.2)",
											anim: .3
										})
									]
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Row, {
									show: phase >= 1,
									delay: .15,
									children: [
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Spacer, {}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 48,
											h: 7,
											bg: "rgba(24,24,27,0.15)",
											anim: .1
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 40,
											h: 7,
											bg: "rgba(153,246,228,0.6)",
											anim: .5
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 56,
											h: 7,
											bg: "rgba(147,197,253,0.6)",
											anim: .3
										})
									]
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Row, {
									show: phase >= 1,
									delay: .2,
									children: [
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Spacer, {}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, {}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 60,
											h: 7,
											bg: "rgba(24,24,27,0.15)",
											anim: .4
										})
									]
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Row, {
									show: phase >= 2,
									delay: .25,
									children: [
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 40,
											h: 7,
											bg: "rgba(153,246,228,0.5)",
											anim: .2
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, {}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 48,
											h: 7,
											bg: "rgba(24,24,27,0.15)",
											anim: .6
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 64,
											h: 7,
											bg: "rgba(147,197,253,0.5)",
											anim: .1
										})
									]
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Row, {
									show: phase >= 2,
									delay: .3,
									children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
										w: 36,
										h: 7,
										bg: "rgba(147,197,253,0.6)",
										anim: .5
									}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
										w: 36,
										h: 7,
										bg: "rgba(24,24,27,0.12)",
										anim: .7
									})]
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Row, {
									show: phase >= 3,
									delay: .35,
									children: [
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, {}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 44,
											h: 7,
											bg: "rgba(24,24,27,0.18)",
											anim: .3
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dot, {}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 56,
											h: 7,
											bg: "rgba(153,246,228,0.5)",
											anim: .8
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Bar, {
											w: 48,
											h: 7,
											bg: "rgba(147,197,253,0.5)",
											anim: .4
										})
									]
								})
							]
						}),
						/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
							pointerEvents: "none",
							position: "absolute",
							inset: 0,
							background: "linear-gradient(105deg, transparent 0%, transparent 40%, rgba(255,255,255,0.6) 50%, transparent 60%, transparent 100%)",
							backgroundSize: "250% 100%",
							animation: "cpk-a2ui-sweep 3s ease-in-out infinite"
						} })
					]
				}),
				/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
					style: {
						display: "flex",
						alignItems: "center",
						justifyContent: "center",
						gap: 8,
						marginTop: 8
					},
					children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
						style: {
							fontSize: 12,
							color: "#a1a1aa",
							letterSpacing: "0.025em"
						},
						children: label
					}), typeof tokens === "number" && tokens > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
						style: {
							fontSize: 11,
							color: "#d4d4d8",
							fontVariantNumeric: "tabular-nums"
						},
						children: [
							"~",
							tokens.toLocaleString(),
							" tokens"
						]
					})]
				}),
				children,
				/* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { children: `
        @keyframes cpk-a2ui-fade {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.5; }
        }
        @keyframes cpk-a2ui-sweep {
          0% { background-position: 250% 0; }
          100% { background-position: -250% 0; }
        }
      ` })
			]
		});
	}
	function A2UIDebugDetails({ label, open, payload }) {
		return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", {
			open,
			className: "cpk:mt-2 cpk:text-xs",
			children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", {
				className: "cpk:cursor-pointer cpk:text-gray-500",
				children: label
			}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
				className: "cpk:mt-1 cpk:overflow-auto cpk:rounded cpk:bg-gray-100 cpk:p-2 cpk:text-gray-700",
				style: { fontSize: 11 },
				children: JSON.stringify(payload, null, 2)
			})]
		});
	}
	function Dot() {
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
			width: 7,
			height: 7,
			borderRadius: "50%",
			backgroundColor: "#d4d4d8",
			flexShrink: 0
		} });
	}
	function Spacer() {
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: { width: 12 } });
	}
	function Bar({ w, h, bg, anim, opacity, transition }) {
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
			width: w,
			height: h,
			borderRadius: 9999,
			backgroundColor: bg,
			...anim !== void 0 ? { animation: `cpk-a2ui-fade 2.4s ease-in-out ${anim}s infinite` } : {},
			...opacity !== void 0 ? { opacity } : {},
			...transition ? { transition } : {}
		} });
	}
	function Row({ children, show, delay = 0 }) {
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
			style: {
				display: "flex",
				alignItems: "center",
				gap: 6,
				opacity: show ? 1 : 0,
				transition: `opacity 0.4s ${delay}s`
			},
			children
		});
	}

//#endregion
//#region src/v2/a2ui/A2UIMessageRenderer.tsx
/**
	* The container key used to wrap A2UI operations for explicit detection.
	* Must match A2UI_OPERATIONS_KEY in @ag-ui/a2ui-middleware and copilotkit.a2ui (Python).
	*/
	const A2UI_OPERATIONS_KEY = "a2ui_operations";
	let initialized = false;
	function ensureInitialized() {
		if (!initialized) {
			(0, _copilotkit_a2ui_renderer.initializeDefaultCatalog)();
			(0, _copilotkit_a2ui_renderer.injectStyles)();
			initialized = true;
		}
	}
	/**
	* The `a2ui-surface` activity carries the WHOLE generative-UI lifecycle on one
	* stable messageId (OSS-162): pre-paint `status` ("building" | "retrying" |
	* "failed") with recovery detail, then `a2ui_operations` on paint. The states
	* swap in place, so the painted surface replaces the skeleton with no extra
	* coordination. `.passthrough()` preserves operations + any future fields.
	*/
	const A2UISurfaceContentSchema = zod.z.object({
		a2ui_operations: zod.z.array(zod.z.any()).optional(),
		...A2UILifecycleFields
	}).passthrough();
	function createA2UIMessageRenderer(options) {
		const { theme, catalog, loadingComponent, recovery, onAction } = options;
		const showAfterMs = recovery?.showAfterMs ?? 2e3;
		const showAfterAttempts = recovery?.showAfterAttempts ?? 2;
		const optionDebugExposure = recovery?.debugExposure ?? "collapsed";
		return {
			activityType: "a2ui-surface",
			content: A2UISurfaceContentSchema,
			render: ({ content, agent }) => {
				ensureInitialized();
				const [operations, setOperations] = (0, react.useState)([]);
				const { copilotkit } = useCopilotKit();
				const lastContentRef = (0, react.useRef)(null);
				(0, react.useEffect)(() => {
					if (content === lastContentRef.current) return;
					lastContentRef.current = content;
					const incoming = content?.[A2UI_OPERATIONS_KEY];
					if (!content || !Array.isArray(incoming)) {
						setOperations([]);
						return;
					}
					setOperations(incoming);
				}, [content]);
				const groupedOperations = (0, react.useMemo)(() => {
					const groups = /* @__PURE__ */ new Map();
					for (const operation of operations) {
						const surfaceId = getOperationSurfaceId(operation) ?? _copilotkit_a2ui_renderer.DEFAULT_SURFACE_ID;
						if (!groups.has(surfaceId)) groups.set(surfaceId, []);
						groups.get(surfaceId).push(operation);
					}
					return groups;
				}, [operations]);
				const hasOps = groupedOperations.size > 0;
				const renderLifecycle = (c) => {
					const status = c?.status;
					const debugExposure = resolveDebugExposure(c, optionDebugExposure);
					if (status === "failed") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIRecoveryFailure, {
						content: c,
						debugExposure
					});
					if (status === "retrying") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIRetryingState, {
						content: c,
						showAfterMs,
						showAfterAttempts,
						debugExposure
					});
					if (loadingComponent) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(loadingComponent, {});
					return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIBuildingState, { content: c });
				};
				const lastLoaderContentRef = (0, react.useRef)(null);
				if (!(Array.isArray(content?.[A2UI_OPERATIONS_KEY]) && content[A2UI_OPERATIONS_KEY].length > 0)) lastLoaderContentRef.current = content;
				const [surfaceReady, setSurfaceReady] = (0, react.useState)(false);
				const readyRef = (0, react.useRef)(false);
				const markSurfaceReady = (0, react.useCallback)(() => {
					if (readyRef.current) return;
					readyRef.current = true;
					requestAnimationFrame(() => setSurfaceReady(true));
				}, []);
				(0, react.useEffect)(() => {
					if (!hasOps) {
						setSurfaceReady(false);
						readyRef.current = false;
						return;
					}
					const t = setTimeout(() => setSurfaceReady(true), 8e3);
					return () => clearTimeout(t);
				}, [hasOps]);
				if (!hasOps) return renderLifecycle(content);
				const surfaces = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
					className: "cpk:flex cpk:min-h-0 cpk:flex-1 cpk:flex-col cpk:gap-6 cpk:overflow-auto cpk:py-6",
					children: Array.from(groupedOperations.entries()).map(([surfaceId, ops]) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ReactSurfaceHost, {
						surfaceId,
						operations: ops,
						theme,
						agent,
						copilotkit,
						catalog,
						onAction,
						onReady: markSurfaceReady
					}, surfaceId))
				});
				return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
					style: { position: "relative" },
					children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						"aria-hidden": !surfaceReady,
						style: surfaceReady ? void 0 : {
							position: "absolute",
							inset: 0,
							opacity: 0,
							pointerEvents: "none"
						},
						children: surfaces
					}), !surfaceReady && renderLifecycle(lastLoaderContentRef.current ?? content)]
				});
			}
		};
	}
	/**
	* Orchestrates a single A2UI user action: runs the optional `onAction`
	* interceptor first, then forwards to the agent unless the interceptor
	* suppressed it (returned `null`). Exported for unit testing; the wiring lives
	* in {@link ReactSurfaceHost}.
	*/
	async function runA2UIAction({ message, agent, copilotkit, onAction }) {
		if (!agent) return;
		const action = message.userAction;
		const forward = async (forwardAction) => {
			const a2uiAction = forwardAction !== void 0 ? {
				...message,
				userAction: forwardAction
			} : message;
			try {
				copilotkit.setProperties({
					...copilotkit.properties,
					a2uiAction
				});
				await copilotkit.runAgent({ agent });
			} finally {
				if (copilotkit.properties) {
					const { a2uiAction: _omit, ...rest } = copilotkit.properties;
					copilotkit.setProperties(rest);
				}
			}
		};
		if (onAction && action) {
			const result = await onAction(action, forward);
			if (result === null) return;
			if (result) {
				await forward(result);
				return;
			}
		}
		await forward();
	}
	/**
	* Renders a single A2UI surface using the React renderer.
	* Wraps A2UIProvider + A2UIRenderer and bridges actions back to CopilotKit.
	*/
	function ReactSurfaceHost({ surfaceId, operations, theme, agent, copilotkit, catalog, onAction, onReady }) {
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
			className: "cpk:flex cpk:w-full cpk:flex-none cpk:flex-col cpk:gap-4",
			children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_copilotkit_a2ui_renderer.A2UIProvider, {
				onAction: (0, react.useCallback)((message) => runA2UIAction({
					message,
					agent,
					copilotkit,
					onAction
				}), [
					agent,
					copilotkit,
					onAction
				]),
				theme,
				catalog,
				children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceMessageProcessor, {
					surfaceId,
					operations,
					onReady
				}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UISurfaceOrError, { surfaceId })]
			})
		});
	}
	/**
	* Renders the A2UI surface, or an error message if processing failed.
	* Must be a child of A2UIProvider to access the error state.
	*/
	function A2UISurfaceOrError({ surfaceId }) {
		const error = (0, _copilotkit_a2ui_renderer.useA2UIError)();
		if (error) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
			className: "cpk:rounded-lg cpk:border cpk:border-red-200 cpk:bg-red-50 cpk:p-3 cpk:text-sm cpk:text-red-700",
			children: ["A2UI render error: ", error]
		});
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkit_a2ui_renderer.A2UIRenderer, {
			surfaceId,
			className: "cpk:flex cpk:flex-1"
		});
	}
	/**
	* Processes A2UI operations into the provider's message processor.
	* Must be a child of A2UIProvider to access the actions context.
	*/
	function SurfaceMessageProcessor({ surfaceId, operations, onReady }) {
		const { processMessages, getSurface } = (0, _copilotkit_a2ui_renderer.useA2UIActions)();
		const lastHashRef = (0, react.useRef)("");
		(0, react.useEffect)(() => {
			const hash = JSON.stringify(operations);
			if (hash === lastHashRef.current) return;
			lastHashRef.current = hash;
			processMessages(getSurface(surfaceId) ? operations.filter((op) => !op?.createSurface) : operations);
			if (onReady && surfaceHasRenderableContent(operations)) onReady();
		}, [
			processMessages,
			getSurface,
			surfaceId,
			operations,
			onReady
		]);
		return null;
	}
	/**
	* Whether the surface's operations are enough to paint a visible card yet.
	* A data-bound surface references its data via `path` and renders nothing until
	* the data model has ≥1 value; a static surface (no path refs) paints from its
	* components alone. Used to time the loader→surface cross-over to actual content
	* arrival rather than a fixed delay. (OSS-162)
	*/
	function surfaceHasRenderableContent(operations) {
		const componentOps = operations.filter((o) => o?.updateComponents);
		if (!componentOps.length) return false;
		if (!JSON.stringify(componentOps).includes("\"path\"")) return true;
		return operations.some((o) => {
			const v = o?.updateDataModel?.value;
			if (!v || typeof v !== "object") return false;
			return Object.values(v).some((x) => Array.isArray(x) ? x.length > 0 : x !== null && x !== void 0 && x !== "");
		});
	}
	function getOperationSurfaceId(operation) {
		if (!operation || typeof operation !== "object") return null;
		if (typeof operation.surfaceId === "string") return operation.surfaceId;
		return operation?.createSurface?.surfaceId ?? operation?.updateComponents?.surfaceId ?? operation?.updateDataModel?.surfaceId ?? operation?.deleteSurface?.surfaceId ?? null;
	}

//#endregion
//#region src/v2/types/defineToolCallRenderer.ts
	function defineToolCallRenderer(def) {
		const argsSchema = def.name === "*" && !def.args ? zod.z.any() : def.args;
		return {
			name: def.name,
			args: argsSchema,
			render: def.render,
			...def.agentId ? { agentId: def.agentId } : {}
		};
	}

//#endregion
//#region src/v2/a2ui/A2UIToolCallRenderer.tsx
/**
	* Tool name used by the dynamic A2UI generation secondary LLM.
	*/
	const RENDER_A2UI_TOOL_NAME = "render_a2ui";
	/**
	* Registers a no-op renderer for the `render_a2ui` tool call so its raw streamed
	* args are never surfaced in the transcript.
	*
	* The generation skeleton / retry / failure UX is NO LONGER owned here (OSS-162):
	* the A2UI middleware drives the whole lifecycle on the `a2ui-surface` activity
	* (one stable messageId, building → retrying → failed → painted), rendered in
	* place by `createA2UIMessageRenderer`. Owning a skeleton per tool call caused a
	* duplicate skeleton on retries / multi-call generations and a skeleton that
	* lingered after the surface painted — both fixed by retiring it here.
	*
	* Users can still override with their own `useRenderTool({ name: "render_a2ui" })`
	* (hook-based entries take priority over this prop-based registration).
	*/
	function A2UIBuiltInToolCallRenderer() {
		const { copilotkit } = useCopilotKit();
		(0, react.useEffect)(() => {
			const renderer = defineToolCallRenderer({
				name: RENDER_A2UI_TOOL_NAME,
				args: zod.z.any(),
				render: () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {})
			});
			const existing = copilotkit._renderToolCalls ?? [];
			copilotkit.setRenderToolCalls([...existing.filter((rc) => rc.name !== RENDER_A2UI_TOOL_NAME), renderer]);
		}, [copilotkit]);
		return null;
	}

//#endregion
//#region src/v2/a2ui/A2UICatalogContext.tsx
/**
	* Renders agent context describing the available A2UI catalog and custom components.
	* Only mount this component when A2UI is enabled.
	*
	* The entries are scoped to the agents the runtime applies A2UI to
	* (`copilotkit.a2uiAgents`, #5369), so agents outside that list don't receive
	* the catalog/schema/guidelines payload on their runs.
	*
	* When `includeSchema` is true, the full component schemas (JSON Schema) are also
	* sent as context using the same description key as the A2UI middleware, so the
	* middleware can optionally overwrite it with a server-side schema.
	*/
	function A2UICatalogContext({ catalog, includeSchema }) {
		const { copilotkit } = useCopilotKit();
		const capabilitiesValue = (0, react.useMemo)(() => (0, _copilotkit_a2ui_renderer.buildCatalogContextValue)(catalog), [catalog]);
		const schemaValue = (0, react.useMemo)(() => includeSchema !== false ? JSON.stringify((0, _copilotkit_a2ui_renderer.extractCatalogComponentSchemas)(catalog)) : null, [catalog, includeSchema]);
		const a2uiAgentsKey = copilotkit?.a2uiAgents?.join(",");
		(0, react.useLayoutEffect)(() => {
			if (!copilotkit) return;
			const agentIds = copilotkit.a2uiAgents;
			const scope = agentIds ? { agentIds } : {};
			const ids = [];
			ids.push(copilotkit.addContext({
				description: "A2UI catalog capabilities: available catalog IDs and custom component definitions the client can render.",
				value: capabilitiesValue,
				...scope
			}));
			if (schemaValue) {
				ids.push(copilotkit.addContext({
					description: _copilotkit_a2ui_renderer.A2UI_SCHEMA_CONTEXT_DESCRIPTION,
					value: schemaValue,
					...scope
				}));
				ids.push(copilotkit.addContext({
					description: "A2UI generation guidelines — protocol rules, tool arguments, path rules, data model format, and form/two-way-binding instructions.",
					value: _copilotkit_shared.A2UI_DEFAULT_GENERATION_GUIDELINES,
					...scope
				}));
				ids.push(copilotkit.addContext({
					description: "A2UI design guidelines — visual design rules, component hierarchy tips, and action handler patterns.",
					value: _copilotkit_shared.A2UI_DEFAULT_DESIGN_GUIDELINES,
					...scope
				}));
			}
			return () => {
				for (const id of ids) copilotkit.removeContext(id);
			};
		}, [
			copilotkit,
			capabilitiesValue,
			schemaValue,
			a2uiAgentsKey
		]);
		return null;
	}

//#endregion
//#region src/v2/providers/CopilotKitProvider.tsx
	const zodToJsonSchemaAdapter = (schema, options) => {
		const refStrategy = options?.$refStrategy;
		return (0, zod_to_json_schema.zodToJsonSchema)(schema, refStrategy === "root" || refStrategy === "relative" || refStrategy === "none" || refStrategy === "seen" ? { $refStrategy: refStrategy } : {});
	};
	const HEADER_NAME = "X-CopilotCloud-Public-Api-Key";
	const COPILOT_CLOUD_CHAT_URL$1 = "https://api.cloud.copilotkit.ai/copilotkit/v1";
	const EMPTY_HEADERS = Object.freeze({});
	const EMPTY_PROPERTIES = Object.freeze({});
	const EMPTY_AGENTS = Object.freeze({});
	const DEFAULT_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:

- Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.
- Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.
- Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.
- Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.
- Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).
- Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
- Minimal transitions (150ms) for hover/focus states only. No decorative animations.
- Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
	const GENERATE_SANDBOXED_UI_DESCRIPTION = "Generate sandboxed UI. IMPORTANT: The generated code runs in a sandboxed iframe WITHOUT same-origin access. Do NOT use localStorage, sessionStorage, document.cookie, IndexedDB, or fetch/XMLHttpRequest to same-origin URLs. To communicate with the host application, use Websandbox.connection.remote.<functionName>(args) which returns a Promise.\n\nYou CAN use external libraries from CDNs by including <script> or <link> tags in the HTML <head> (e.g., Chart.js, D3, Three.js, x-data-spreadsheet, etc.). CDN resources load normally inside the sandbox.\n\nPARAMETER ORDER IS CRITICAL — generate parameters in exactly this order:\n1. initialHeight + placeholderMessages (shown to user while generating)\n2. css (all styles FIRST — the user sees a placeholder until CSS is complete)\n3. html (streams in live — the user watches the UI build as HTML is generated)\n4. jsFunctions (reusable helper functions)\n5. jsExpressions (applied one-by-one — the user sees each expression take effect)";
	function useStableArrayProp(prop, warningMessage, isMeaningfulChange) {
		const empty = (0, react.useMemo)(() => [], []);
		const value = prop ?? empty;
		const initial = (0, react.useRef)(value);
		(0, react.useEffect)(() => {
			if (warningMessage && value !== initial.current && (isMeaningfulChange ? isMeaningfulChange(initial.current, value) : true)) console.error(warningMessage);
		}, [value, warningMessage]);
		return value;
	}
	const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY_HEADERS, credentials, publicApiKey, publicLicenseKey, licenseToken, properties = EMPTY_PROPERTIES, agents__unsafe_dev_only: agents = EMPTY_AGENTS, selfManagedAgents = EMPTY_AGENTS, renderToolCalls, renderActivityMessages, renderCustomMessages, frontendTools, humanInTheLoop, openGenerativeUI, showDevConsole = false, useSingleEndpoint, onError, a2ui, defaultThrottleMs, inspectorDefaultAnchor, debug }) => {
		const [shouldRenderInspector, setShouldRenderInspector] = (0, react.useState)(false);
		const [isLocalInspectorEnabled, setIsLocalInspectorEnabled] = (0, react.useState)(false);
		const [inspectorOpenRequest, setInspectorOpenRequest] = (0, react.useState)(null);
		const [runtimeA2UIEnabled, setRuntimeA2UIEnabled] = (0, react.useState)(false);
		const [runtimeOpenGenUIEnabled, setRuntimeOpenGenUIEnabled] = (0, react.useState)(false);
		const [catalogToggleVersion, setCatalogToggleVersion] = (0, react.useState)(0);
		const openGenUIActive = runtimeOpenGenUIEnabled || !!openGenerativeUI;
		const a2uiCatalogProvided = !!a2ui?.catalog;
		const a2uiActive = runtimeA2UIEnabled || a2uiCatalogProvided;
		const [runtimeLicenseStatus, setRuntimeLicenseStatus] = (0, react.useState)(void 0);
		(0, react.useEffect)(() => {
			if (typeof window === "undefined") return;
			const isLocalhost = new Set(["localhost", "127.0.0.1"]).has(window.location?.hostname ?? "");
			const canShowLocalInspectorAction = process.env.NODE_ENV === "development" && isLocalhost;
			if (showDevConsole === true) {
				setShouldRenderInspector(true);
				setIsLocalInspectorEnabled(canShowLocalInspectorAction);
			} else if (showDevConsole === "auto") if (isLocalhost) {
				setShouldRenderInspector(true);
				setIsLocalInspectorEnabled(canShowLocalInspectorAction);
			} else {
				setShouldRenderInspector(false);
				setIsLocalInspectorEnabled(false);
			}
			else {
				setShouldRenderInspector(false);
				setIsLocalInspectorEnabled(false);
			}
		}, [showDevConsole]);
		const requestInspectorOpen = (0, react.useCallback)((request) => {
			setInspectorOpenRequest({ ...request });
		}, []);
		const inspectorContextValue = (0, react.useMemo)(() => ({
			isLocalInspectorEnabled,
			openInspector: requestInspectorOpen
		}), [isLocalInspectorEnabled, requestInspectorOpen]);
		const renderToolCallsList = useStableArrayProp(renderToolCalls, "renderToolCalls must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.", (initial, next) => {
			const key = (rc) => `${rc?.agentId ?? ""}:${rc?.name ?? ""}`;
			const setFrom = (arr) => new Set(arr.map(key));
			const a = setFrom(initial);
			const b = setFrom(next);
			if (a.size !== b.size) return true;
			for (const k of a) if (!b.has(k)) return true;
			return false;
		});
		const renderCustomMessagesList = useStableArrayProp(renderCustomMessages, "renderCustomMessages must be a stable array.");
		const renderActivityMessagesList = useStableArrayProp(renderActivityMessages, "renderActivityMessages must be a stable array.");
		const copilotkitRef = (0, react.useRef)(null);
		const rawCatalog = a2ui?.catalog;
		const filteredCatalog = (0, react.useMemo)(() => {
			if (!rawCatalog) return rawCatalog;
			if (!(rawCatalog instanceof _copilotkit_a2ui_renderer.Catalog)) return rawCatalog;
			const core = copilotkitRef.current;
			return (0, _copilotkit_a2ui_renderer.filterCatalog)(rawCatalog, (name) => core ? core.isCatalogComponentEnabled(name) : true);
		}, [rawCatalog, catalogToggleVersion]);
		const builtInActivityRenderers = (0, react.useMemo)(() => {
			const renderers = [{
				activityType: MCPAppsActivityType,
				content: MCPAppsActivityContentSchema,
				render: MCPAppsActivityRenderer
			}];
			if (openGenUIActive) renderers.push({
				activityType: OpenGenerativeUIActivityType,
				content: OpenGenerativeUIContentSchema,
				render: OpenGenerativeUIActivityRenderer
			});
			if (a2uiActive) renderers.unshift(createA2UIMessageRenderer({
				theme: a2ui?.theme ?? _copilotkit_a2ui_renderer.viewerTheme,
				catalog: filteredCatalog,
				loadingComponent: a2ui?.loadingComponent,
				recovery: a2ui?.recovery
			}));
			return renderers;
		}, [
			a2uiActive,
			openGenUIActive,
			a2ui,
			filteredCatalog
		]);
		const allActivityRenderers = (0, react.useMemo)(() => {
			return [...renderActivityMessagesList, ...builtInActivityRenderers];
		}, [renderActivityMessagesList, builtInActivityRenderers]);
		const resolvedPublicKey = publicApiKey ?? publicLicenseKey;
		const mergedAgents = (0, react.useMemo)(() => ({
			...agents,
			...selfManagedAgents
		}), [agents, selfManagedAgents]);
		const hasLocalAgents = mergedAgents && Object.keys(mergedAgents).length > 0;
		const hasSelfManagedAgents = Object.keys(selfManagedAgents).length > 0;
		(0, react.useEffect)(() => {
			if (hasSelfManagedAgents && !resolvedPublicKey) console.warn("[CopilotKit] `selfManagedAgents` is part of CopilotKit's Enterprise Intelligence offering. Provide a `publicLicenseKey` for production use — contact the CopilotKit team about licensing.");
		}, [hasSelfManagedAgents, resolvedPublicKey]);
		const headers = typeof headersProp === "function" ? headersProp() : headersProp;
		const mergedHeaders = (0, react.useMemo)(() => {
			if (!resolvedPublicKey) return headers;
			if (headers[HEADER_NAME]) return headers;
			return {
				...headers,
				[HEADER_NAME]: resolvedPublicKey
			};
		}, [headers, resolvedPublicKey]);
		if (!runtimeUrl && !resolvedPublicKey && !hasLocalAgents) {
			const message = "Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'";
			if (process.env.NODE_ENV === "production") throw new Error(message);
			else console.warn(message);
		}
		const chatApiEndpoint = runtimeUrl ?? (resolvedPublicKey ? COPILOT_CLOUD_CHAT_URL$1 : void 0);
		const frontendToolsList = useStableArrayProp(frontendTools, "frontendTools must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.");
		const humanInTheLoopList = useStableArrayProp(humanInTheLoop, "humanInTheLoop must be a stable array. If you want to dynamically add or remove human-in-the-loop tools, use `useHumanInTheLoop` instead.");
		const sandboxFunctionsList = useStableArrayProp(openGenerativeUI?.sandboxFunctions, "openGenerativeUI.sandboxFunctions must be a stable array.");
		const processedHumanInTheLoopTools = (0, react.useMemo)(() => {
			const processedTools = [];
			const processedRenderToolCalls = [];
			humanInTheLoopList.forEach((tool) => {
				const frontendTool = {
					name: tool.name,
					description: tool.description,
					parameters: tool.parameters,
					followUp: tool.followUp,
					...tool.agentId && { agentId: tool.agentId },
					handler: async () => {
						return new Promise((resolve) => {
							console.warn(`Human-in-the-loop tool '${tool.name}' called but no interactive handler is set up.`);
							resolve(void 0);
						});
					}
				};
				processedTools.push(frontendTool);
				if (tool.render) processedRenderToolCalls.push({
					name: tool.name,
					args: tool.parameters,
					render: tool.render,
					...tool.agentId && { agentId: tool.agentId }
				});
			});
			return {
				tools: processedTools,
				renderToolCalls: processedRenderToolCalls
			};
		}, [humanInTheLoopList]);
		const builtInFrontendTools = (0, react.useMemo)(() => {
			if (!openGenUIActive) return [];
			return [{
				name: "generateSandboxedUi",
				description: GENERATE_SANDBOXED_UI_DESCRIPTION,
				parameters: GenerateSandboxedUiArgsSchema,
				handler: async () => "UI generated",
				followUp: true,
				render: OpenGenerativeUIToolRenderer
			}];
		}, [openGenUIActive]);
		const allTools = (0, react.useMemo)(() => {
			const tools = [];
			tools.push(...frontendToolsList);
			tools.push(...builtInFrontendTools);
			tools.push(...processedHumanInTheLoopTools.tools);
			return tools;
		}, [
			frontendToolsList,
			builtInFrontendTools,
			processedHumanInTheLoopTools
		]);
		const allRenderToolCalls = (0, react.useMemo)(() => {
			const combined = [...renderToolCallsList];
			[...frontendToolsList, ...builtInFrontendTools].forEach((tool) => {
				if (tool.render) {
					const args = tool.parameters || (tool.name === "*" ? zod.z.any() : void 0);
					if (args) combined.push({
						name: tool.name,
						args,
						render: tool.render
					});
				}
			});
			combined.push(...processedHumanInTheLoopTools.renderToolCalls);
			return combined;
		}, [
			renderToolCallsList,
			frontendToolsList,
			builtInFrontendTools,
			processedHumanInTheLoopTools
		]);
		if (copilotkitRef.current === null) {
			copilotkitRef.current = new CopilotKitCoreReact({
				runtimeUrl: chatApiEndpoint,
				deferInitialConnection: true,
				runtimeTransport: useSingleEndpoint === true ? "single" : useSingleEndpoint === false ? "rest" : "auto",
				headers: mergedHeaders,
				credentials,
				properties,
				agents__unsafe_dev_only: mergedAgents,
				tools: allTools,
				renderToolCalls: allRenderToolCalls,
				renderActivityMessages: allActivityRenderers,
				renderCustomMessages: renderCustomMessagesList,
				debug
			});
			if (defaultThrottleMs !== void 0) copilotkitRef.current.setDefaultThrottleMs(defaultThrottleMs);
		}
		const copilotkit = copilotkitRef.current;
		(0, react.useEffect)(() => {
			if (!rawCatalog) return;
			if (!(rawCatalog instanceof _copilotkit_a2ui_renderer.Catalog)) return;
			const components = Array.from(rawCatalog.components.values()).map((comp) => ({
				name: comp.name,
				description: void 0,
				schema: comp.schema
			}));
			copilotkit.setCatalogComponents(components);
			const subscription = copilotkit.subscribe({ onCatalogComponentsChanged: () => {
				setCatalogToggleVersion((v) => v + 1);
			} });
			return () => subscription.unsubscribe();
		}, [copilotkit, rawCatalog]);
		(0, react.useEffect)(() => {
			const syncRuntimeInfo = () => {
				setRuntimeA2UIEnabled(copilotkit.a2uiEnabled);
				setRuntimeOpenGenUIEnabled(copilotkit.openGenerativeUIEnabled);
				setRuntimeLicenseStatus(copilotkit.licenseStatus);
			};
			const subscription = copilotkit.subscribe({ onRuntimeConnectionStatusChanged: syncRuntimeInfo });
			syncRuntimeInfo();
			return () => {
				subscription.unsubscribe();
			};
		}, [copilotkit]);
		const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
		(0, react.useEffect)(() => {
			const subscription = copilotkit.subscribe({ onRenderToolCallsChanged: () => {
				forceUpdate();
			} });
			return () => {
				subscription.unsubscribe();
			};
		}, [copilotkit]);
		const [executingToolCallIds, setExecutingToolCallIds] = (0, react.useState)(() => /* @__PURE__ */ new Set());
		(0, react.useEffect)(() => {
			const subscription = copilotkit.subscribe({
				onToolExecutionStart: ({ toolCallId }) => {
					setExecutingToolCallIds((prev) => {
						if (prev.has(toolCallId)) return prev;
						const next = new Set(prev);
						next.add(toolCallId);
						return next;
					});
				},
				onToolExecutionEnd: ({ toolCallId }) => {
					setExecutingToolCallIds((prev) => {
						if (!prev.has(toolCallId)) return prev;
						const next = new Set(prev);
						next.delete(toolCallId);
						return next;
					});
				}
			});
			return () => {
				subscription.unsubscribe();
			};
		}, [copilotkit]);
		const onErrorRef = (0, react.useRef)(onError);
		(0, react.useEffect)(() => {
			onErrorRef.current = onError;
		}, [onError]);
		(0, react.useEffect)(() => {
			const subscription = copilotkit.subscribe({ onError: (event) => {
				if (onErrorRef.current) onErrorRef.current(event);
				else console.error(`[CopilotKit] Error (${event.code}):`, event.error, event.context ?? {});
			} });
			return () => {
				subscription.unsubscribe();
			};
		}, [copilotkit]);
		(0, react.useEffect)(() => {
			copilotkit.setRuntimeUrl(chatApiEndpoint);
			copilotkit.setRuntimeTransport(useSingleEndpoint === true ? "single" : useSingleEndpoint === false ? "rest" : "auto");
			copilotkit.setHeaders(mergedHeaders);
			copilotkit.setCredentials(credentials);
			copilotkit.setProperties(a2uiCatalogProvided ? {
				...properties,
				a2uiCatalogAvailable: true
			} : properties);
			copilotkit.setAgents__unsafe_dev_only(mergedAgents);
			copilotkit.setDebug(debug);
			copilotkit.connect();
		}, [
			copilotkit,
			chatApiEndpoint,
			mergedHeaders,
			credentials,
			properties,
			a2uiCatalogProvided,
			mergedAgents,
			useSingleEndpoint,
			debug
		]);
		const didMountRef = (0, react.useRef)(false);
		(0, react.useEffect)(() => {
			if (!didMountRef.current) return;
			copilotkit.setTools(allTools);
		}, [copilotkit, allTools]);
		(0, react.useEffect)(() => {
			if (!didMountRef.current) return;
			copilotkit.setRenderToolCalls(allRenderToolCalls);
		}, [copilotkit, allRenderToolCalls]);
		(0, react.useEffect)(() => {
			if (!didMountRef.current) return;
			copilotkit.setRenderActivityMessages(allActivityRenderers);
		}, [copilotkit, allActivityRenderers]);
		(0, react.useEffect)(() => {
			if (!didMountRef.current) return;
			copilotkit.setRenderCustomMessages(renderCustomMessagesList);
		}, [copilotkit, renderCustomMessagesList]);
		(0, react.useEffect)(() => {
			didMountRef.current = true;
		}, []);
		(0, react.useEffect)(() => {
			copilotkit.setDefaultThrottleMs(defaultThrottleMs);
		}, [copilotkit, defaultThrottleMs]);
		const designSkill = openGenerativeUI?.designSkill ?? DEFAULT_DESIGN_SKILL;
		(0, react.useLayoutEffect)(() => {
			if (!copilotkit || !openGenUIActive) return;
			const id = copilotkit.addContext({
				description: "Design guidelines for the generateSandboxedUi tool. Follow these when building UI.",
				value: designSkill
			});
			return () => {
				copilotkit.removeContext(id);
			};
		}, [
			copilotkit,
			designSkill,
			openGenUIActive
		]);
		const sandboxFunctionsDescriptors = (0, react.useMemo)(() => {
			if (sandboxFunctionsList.length === 0) return null;
			return JSON.stringify(sandboxFunctionsList.map((fn) => ({
				name: fn.name,
				description: fn.description,
				parameters: (0, _copilotkit_shared.schemaToJsonSchema)(fn.parameters, { zodToJsonSchema: zodToJsonSchemaAdapter })
			})));
		}, [sandboxFunctionsList]);
		(0, react.useLayoutEffect)(() => {
			if (!copilotkit || !sandboxFunctionsDescriptors || !openGenUIActive) return;
			const id = copilotkit.addContext({
				description: "Sandbox functions available in generated sandboxed UI code. Call via: await Websandbox.connection.remote.<functionName>(args)",
				value: sandboxFunctionsDescriptors
			});
			return () => {
				copilotkit.removeContext(id);
			};
		}, [
			copilotkit,
			sandboxFunctionsDescriptors,
			openGenUIActive
		]);
		const contextValue = (0, react.useMemo)(() => ({
			copilotkit,
			executingToolCallIds
		}), [copilotkit, executingToolCallIds]);
		const licenseContextValue = (0, react.useMemo)(() => (0, _copilotkit_shared.createLicenseContextValue)(runtimeLicenseStatus), [runtimeLicenseStatus]);
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SandboxFunctionsContext.Provider, {
			value: sandboxFunctionsList,
			children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitContext.Provider, {
				value: contextValue,
				children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(LicenseContext.Provider, {
					value: licenseContextValue,
					children: [
						a2uiActive && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIBuiltInToolCallRenderer, {}),
						a2uiActive && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UICatalogContext, {
							catalog: filteredCatalog,
							includeSchema: a2ui?.includeSchema
						}),
						/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotKitInspectorContextProvider, {
							value: inspectorContextValue,
							children: [children, shouldRenderInspector ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitInspector, {
								core: copilotkit,
								defaultAnchor: inspectorDefaultAnchor,
								openRequest: inspectorOpenRequest
							}) : null]
						}),
						runtimeLicenseStatus === "none" && !resolvedPublicKey && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "no_license" }),
						runtimeLicenseStatus === "expired" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "expired" }),
						runtimeLicenseStatus === "invalid" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "invalid" }),
						runtimeLicenseStatus === "expiring" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "expiring" })
					]
				})
			})
		});
	};

//#endregion
//#region src/v2/hooks/use-render-custom-messages.tsx
	function useRenderCustomMessages() {
		const { copilotkit } = useCopilotKit();
		const config = useCopilotChatConfiguration();
		if (!config) return null;
		const { agentId, threadId } = config;
		const customMessageRenderers = copilotkit.renderCustomMessages.filter((renderer) => renderer.agentId === void 0 || renderer.agentId === agentId).sort((a, b) => {
			const aHasAgent = a.agentId !== void 0;
			if (aHasAgent === (b.agentId !== void 0)) return 0;
			return aHasAgent ? -1 : 1;
		});
		return function(params) {
			if (!customMessageRenderers.length) return null;
			const { message, position } = params;
			const resolvedRunId = copilotkit.getRunIdForMessage(agentId, threadId, message.id) ?? copilotkit.getRunIdsForThread(agentId, threadId).slice(-1)[0];
			const runId = resolvedRunId ?? `missing-run-id:${message.id}`;
			const agent = copilotkit.getAgent(agentId);
			if (!agent) return null;
			const messagesIdsInRun = resolvedRunId ? agent.messages.filter((msg) => copilotkit.getRunIdForMessage(agentId, threadId, msg.id) === resolvedRunId).map((msg) => msg.id) : [message.id];
			const rawMessageIndex = agent.messages.findIndex((msg) => msg.id === message.id);
			const messageIndex = rawMessageIndex >= 0 ? rawMessageIndex : 0;
			const messageIndexInRun = resolvedRunId ? Math.max(messagesIdsInRun.indexOf(message.id), 0) : 0;
			const numberOfMessagesInRun = resolvedRunId ? messagesIdsInRun.length : 1;
			const stateSnapshot = resolvedRunId ? copilotkit.getStateByRun(agentId, threadId, resolvedRunId) : void 0;
			let result = null;
			for (const renderer of customMessageRenderers) {
				if (!renderer.render) continue;
				const Component = renderer.render;
				result = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Component, {
					message,
					position,
					runId,
					messageIndex,
					messageIndexInRun,
					numberOfMessagesInRun,
					agentId,
					stateSnapshot
				}, `${runId}-${message.id}-${position}`);
				if (result) break;
			}
			return result;
		};
	}

//#endregion
//#region src/v2/hooks/use-frontend-tool.tsx
	const EMPTY_DEPS = [];
	function useFrontendTool$1(tool, deps) {
		const { copilotkit } = useCopilotKit();
		const extraDeps = deps ?? EMPTY_DEPS;
		(0, react.useEffect)(() => {
			const name = tool.name;
			if (copilotkit.getTool({
				toolName: name,
				agentId: tool.agentId
			})) {
				console.warn(`Tool '${name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
				copilotkit.removeTool(name, tool.agentId);
			}
			copilotkit.addTool(tool);
			if (tool.render) copilotkit.addHookRenderToolCall({
				name,
				args: tool.parameters,
				agentId: tool.agentId,
				render: tool.render
			});
			return () => {
				copilotkit.removeTool(name, tool.agentId);
			};
		}, [
			tool.name,
			tool.available,
			copilotkit,
			JSON.stringify(extraDeps)
		]);
	}

//#endregion
//#region src/v2/hooks/use-human-in-the-loop.tsx
	function useHumanInTheLoop$1(tool, deps) {
		const { copilotkit } = useCopilotKit();
		const resolvePromiseRef = (0, react.useRef)(null);
		const cleanupAbortRef = (0, react.useRef)(null);
		const respond = (0, react.useCallback)(async (result) => {
			if (resolvePromiseRef.current) {
				cleanupAbortRef.current?.();
				cleanupAbortRef.current = null;
				resolvePromiseRef.current(result);
				resolvePromiseRef.current = null;
			}
		}, []);
		const handler = (0, react.useCallback)(async (_args, context) => {
			const signal = context?.signal;
			return new Promise((resolve, reject) => {
				if (signal?.aborted) {
					reject(/* @__PURE__ */ new Error("Human-in-the-loop interaction aborted"));
					return;
				}
				resolvePromiseRef.current = resolve;
				if (signal) {
					const onAbort = () => {
						cleanupAbortRef.current = null;
						resolvePromiseRef.current = null;
						reject(/* @__PURE__ */ new Error("Human-in-the-loop interaction aborted"));
					};
					signal.addEventListener("abort", onAbort, { once: true });
					cleanupAbortRef.current = () => {
						signal.removeEventListener("abort", onAbort);
					};
				}
			});
		}, []);
		const RenderComponent = (0, react.useCallback)((props) => {
			const ToolComponent = tool.render;
			if (props.status === _copilotkit_core.ToolCallStatus.InProgress) {
				const enhancedProps = {
					...props,
					name: tool.name,
					description: tool.description || "",
					agentId: tool.agentId,
					respond: void 0
				};
				return react.default.createElement(ToolComponent, enhancedProps);
			} else if (props.status === _copilotkit_core.ToolCallStatus.Executing) {
				const enhancedProps = {
					...props,
					name: tool.name,
					description: tool.description || "",
					agentId: tool.agentId,
					respond
				};
				return react.default.createElement(ToolComponent, enhancedProps);
			} else if (props.status === _copilotkit_core.ToolCallStatus.Complete) {
				const enhancedProps = {
					...props,
					name: tool.name,
					description: tool.description || "",
					agentId: tool.agentId,
					respond: void 0
				};
				return react.default.createElement(ToolComponent, enhancedProps);
			}
			return props;
		}, [
			tool.render,
			tool.name,
			tool.description,
			tool.agentId,
			respond
		]);
		useFrontendTool$1({
			...tool,
			handler,
			render: RenderComponent
		}, deps);
		(0, react.useEffect)(() => {
			return () => {
				copilotkit.removeHookRenderToolCall(tool.name, tool.agentId);
			};
		}, [
			copilotkit,
			tool.name,
			tool.agentId
		]);
	}

//#endregion
//#region src/v2/hooks/use-agent.tsx
	let UseAgentUpdate = /* @__PURE__ */ function(UseAgentUpdate) {
		UseAgentUpdate["OnMessagesChanged"] = "OnMessagesChanged";
		UseAgentUpdate["OnStateChanged"] = "OnStateChanged";
		UseAgentUpdate["OnRunStatusChanged"] = "OnRunStatusChanged";
		return UseAgentUpdate;
	}({});
	const ALL_UPDATES = [
		UseAgentUpdate.OnMessagesChanged,
		UseAgentUpdate.OnStateChanged,
		UseAgentUpdate.OnRunStatusChanged
	];
	function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {}) {
		if (threadId != null && runtimeAgentId == null) throw new Error(`useAgent: \`threadId\` requires \`runtimeAgentId\`. A threadId is written onto a single agent, but an agent resolved by agentId alone is shared, so scoping a thread to it would clobber other useAgent callers. Pass a distinct local \`agentId\` and the runtime agent to route to, e.g. useAgent({ agentId: "chat-1", runtimeAgentId: "${agentId ?? "default"}", threadId }).`);
		if (runtimeAgentId != null && threadId == null) throw new Error(`useAgent: \`runtimeAgentId\` requires \`threadId\`. A proxied agent exists to scope a thread to a private instance; without a threadId it behaves like the shared agent while adding a registration and a local agentId to keep unique. Either pass the thread, e.g. useAgent({ agentId: "${agentId ?? "chat-1"}", runtimeAgentId: "${runtimeAgentId}", threadId }), or bind to the agent directly with useAgent({ agentId: "${runtimeAgentId}" }).`);
		if (runtimeAgentId != null && agentId == null) throw new Error(`useAgent: \`runtimeAgentId\` requires an explicit \`agentId\`. The proxied agent is registered under \`agentId\`, and the usual fallbacks (chat configuration, then "${_copilotkit_shared.DEFAULT_AGENT_ID}") name agents that already exist — registering over one throws or shadows it. Pick a local id for this hook, e.g. useAgent({ agentId: "chat-1", runtimeAgentId: "${runtimeAgentId}", threadId }).`);
		const chatConfig = useCopilotChatConfiguration();
		const resolvedAgentId = agentId ?? chatConfig?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
		const { copilotkit } = useCopilotKit();
		const providerThrottleMs = copilotkit.defaultThrottleMs;
		const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
		const updateFlags = (0, react.useMemo)(() => updates ?? ALL_UPDATES, [JSON.stringify(updates)]);
		const provisionalAgentCache = (0, react.useRef)(/* @__PURE__ */ new Map());
		const [registeredProxyAgent, setRegisteredProxyAgent] = (0, react.useState)(null);
		(0, react.useEffect)(() => {
			if (runtimeAgentId == null) {
				setRegisteredProxyAgent(null);
				return;
			}
			const { agent: proxy, unregister } = copilotkit.registerProxiedAgent({
				agentId: resolvedAgentId,
				runtimeAgentId
			});
			provisionalAgentCache.current.delete(resolvedAgentId);
			setRegisteredProxyAgent(proxy);
			return () => {
				unregister();
				setRegisteredProxyAgent(null);
			};
		}, [
			copilotkit,
			resolvedAgentId,
			runtimeAgentId
		]);
		const { agent, isReady } = (0, react.useMemo)(() => {
			if (runtimeAgentId != null) {
				if (registeredProxyAgent) {
					provisionalAgentCache.current.delete(resolvedAgentId);
					return {
						agent: registeredProxyAgent,
						isReady: true
					};
				}
				const cached = provisionalAgentCache.current.get(resolvedAgentId);
				if (cached) {
					copilotkit.applyHeadersToAgent(cached);
					return {
						agent: cached,
						isReady: false
					};
				}
				const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
					runtimeUrl: copilotkit.runtimeUrl,
					agentId: resolvedAgentId,
					runtimeAgentId,
					transport: copilotkit.runtimeTransport,
					runtimeMode: "pending"
				});
				copilotkit.applyHeadersToAgent(provisional);
				provisionalAgentCache.current.set(resolvedAgentId, provisional);
				return {
					agent: provisional,
					isReady: false
				};
			}
			const existing = copilotkit.getAgent(resolvedAgentId);
			if (existing) {
				provisionalAgentCache.current.delete(resolvedAgentId);
				return {
					agent: existing,
					isReady: true
				};
			}
			const isRuntimeConfigured = copilotkit.runtimeUrl !== void 0;
			const status = copilotkit.runtimeConnectionStatus;
			if (isRuntimeConfigured && (status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Disconnected || status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connecting)) {
				const cached = provisionalAgentCache.current.get(resolvedAgentId);
				if (cached) return {
					agent: cached,
					isReady: false
				};
				const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
					runtimeUrl: copilotkit.runtimeUrl,
					agentId: resolvedAgentId,
					transport: copilotkit.runtimeTransport,
					credentials: copilotkit.credentials,
					runtimeMode: "pending"
				});
				copilotkit.applyHeadersToAgent(provisional);
				provisionalAgentCache.current.set(resolvedAgentId, provisional);
				return {
					agent: provisional,
					isReady: false
				};
			}
			if (isRuntimeConfigured && status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Error) {
				const cached = provisionalAgentCache.current.get(resolvedAgentId);
				if (cached) return {
					agent: cached,
					isReady: false
				};
				const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
					runtimeUrl: copilotkit.runtimeUrl,
					agentId: resolvedAgentId,
					transport: copilotkit.runtimeTransport,
					credentials: copilotkit.credentials,
					runtimeMode: "pending"
				});
				copilotkit.applyHeadersToAgent(provisional);
				provisionalAgentCache.current.set(resolvedAgentId, provisional);
				return {
					agent: provisional,
					isReady: false
				};
			}
			const knownAgents = Object.keys(copilotkit.agents ?? {});
			const runtimePart = isRuntimeConfigured ? `runtimeUrl=${copilotkit.runtimeUrl}` : "no runtimeUrl";
			throw new Error(`useAgent: Agent '${resolvedAgentId}' not found after runtime sync (${runtimePart}). ` + (knownAgents.length ? `Known agents: [${knownAgents.join(", ")}]` : "No agents registered.") + " Verify your runtime /info and/or agents__unsafe_dev_only.");
		}, [
			resolvedAgentId,
			runtimeAgentId,
			registeredProxyAgent,
			copilotkit.agents,
			copilotkit.runtimeConnectionStatus,
			copilotkit.runtimeUrl,
			copilotkit.runtimeTransport,
			copilotkit.credentials,
			JSON.stringify(copilotkit.headers)
		]);
		(0, react.useEffect)(() => {
			if (updateFlags.length === 0) return;
			let active = true;
			const handlers = {};
			let batchScheduled = false;
			const batchedForceUpdate = () => {
				if (!active) return;
				if (!batchScheduled) {
					batchScheduled = true;
					queueMicrotask(() => {
						batchScheduled = false;
						if (active) forceUpdate();
					});
				}
			};
			if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) handlers.onMessagesChanged = batchedForceUpdate;
			if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) handlers.onStateChanged = batchedForceUpdate;
			if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {
				handlers.onRunInitialized = batchedForceUpdate;
				handlers.onRunFinalized = batchedForceUpdate;
				handlers.onRunFailed = batchedForceUpdate;
				handlers.onRunErrorEvent = batchedForceUpdate;
			}
			const subscription = copilotkit.subscribeToAgentWithOptions(agent, handlers, { throttleMs });
			return () => {
				active = false;
				subscription.unsubscribe();
			};
		}, [
			agent,
			forceUpdate,
			throttleMs,
			providerThrottleMs,
			updateFlags
		]);
		(0, react.useEffect)(() => {
			if (agent instanceof _ag_ui_client.HttpAgent) copilotkit.applyHeadersToAgent(agent);
			if (agent instanceof _copilotkit_core.ProxiedCopilotRuntimeAgent) agent.credentials = copilotkit.credentials;
		}, [
			agent,
			JSON.stringify(copilotkit.headers),
			copilotkit.credentials
		]);
		const configThreadId = chatConfig?.threadId;
		const configHasExplicitThreadId = chatConfig?.hasExplicitThreadId;
		const resolvedThreadId = threadId ?? (configHasExplicitThreadId ? configThreadId : void 0);
		(0, react.useEffect)(() => {
			if (!resolvedThreadId) return;
			agent.threadId = resolvedThreadId;
		}, [agent, resolvedThreadId]);
		return {
			agent,
			isReady
		};
	}

//#endregion
//#region src/v2/hooks/use-suggestions.tsx
	function useSuggestions({ agentId } = {}) {
		const { copilotkit } = useCopilotKit();
		const config = useCopilotChatConfiguration();
		const resolvedAgentId = (0, react.useMemo)(() => agentId ?? config?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID, [agentId, config?.agentId]);
		const [suggestions, setSuggestions] = (0, react.useState)(() => {
			return copilotkit.getSuggestions(resolvedAgentId).suggestions;
		});
		const [isLoading, setIsLoading] = (0, react.useState)(() => {
			return copilotkit.getSuggestions(resolvedAgentId).isLoading;
		});
		(0, react.useEffect)(() => {
			const result = copilotkit.getSuggestions(resolvedAgentId);
			setSuggestions(result.suggestions);
			setIsLoading(result.isLoading);
		}, [copilotkit, resolvedAgentId]);
		(0, react.useEffect)(() => {
			const subscription = copilotkit.subscribe({
				onSuggestionsChanged: ({ agentId: changedAgentId, suggestions }) => {
					if (changedAgentId !== resolvedAgentId) return;
					setSuggestions(suggestions);
				},
				onSuggestionsStartedLoading: ({ agentId: changedAgentId }) => {
					if (changedAgentId !== resolvedAgentId) return;
					setIsLoading(true);
				},
				onSuggestionsFinishedLoading: ({ agentId: changedAgentId }) => {
					if (changedAgentId !== resolvedAgentId) return;
					setIsLoading(false);
				},
				onSuggestionsConfigChanged: () => {
					const result = copilotkit.getSuggestions(resolvedAgentId);
					setSuggestions(result.suggestions);
					setIsLoading(result.isLoading);
				}
			});
			return () => {
				subscription.unsubscribe();
			};
		}, [copilotkit, resolvedAgentId]);
		return {
			suggestions,
			reloadSuggestions: (0, react.useCallback)(() => {
				copilotkit.reloadSuggestions(resolvedAgentId);
			}, [copilotkit, resolvedAgentId]),
			clearSuggestions: (0, react.useCallback)(() => {
				copilotkit.clearSuggestions(resolvedAgentId);
			}, [copilotkit, resolvedAgentId]),
			isLoading
		};
	}

//#endregion
//#region src/v2/hooks/use-configure-suggestions.tsx
	function useConfigureSuggestions(config, deps) {
		const { copilotkit } = useCopilotKit();
		const chatConfig = useCopilotChatConfiguration();
		const extraDeps = deps ?? [];
		const resolvedConsumerAgentId = (0, react.useMemo)(() => chatConfig?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID, [chatConfig?.agentId]);
		const rawConsumerAgentId = (0, react.useMemo)(() => config ? config.consumerAgentId : void 0, [config]);
		const normalizationCacheRef = (0, react.useRef)({
			serialized: null,
			config: null
		});
		const { normalizedConfig, serializedConfig } = (0, react.useMemo)(() => {
			if (!config) {
				normalizationCacheRef.current = {
					serialized: null,
					config: null
				};
				return {
					normalizedConfig: null,
					serializedConfig: null
				};
			}
			if (config.available === "disabled") {
				normalizationCacheRef.current = {
					serialized: null,
					config: null
				};
				return {
					normalizedConfig: null,
					serializedConfig: null
				};
			}
			let built;
			if (isDynamicConfig(config)) built = { ...config };
			else {
				const normalizedSuggestions = normalizeStaticSuggestions(config.suggestions);
				built = {
					...config,
					suggestions: normalizedSuggestions
				};
			}
			const serialized = JSON.stringify(built);
			const cache = normalizationCacheRef.current;
			if (cache.serialized === serialized && cache.config) return {
				normalizedConfig: cache.config,
				serializedConfig: serialized
			};
			normalizationCacheRef.current = {
				serialized,
				config: built
			};
			return {
				normalizedConfig: built,
				serializedConfig: serialized
			};
		}, [
			config,
			resolvedConsumerAgentId,
			...extraDeps
		]);
		const latestConfigRef = (0, react.useRef)(null);
		latestConfigRef.current = normalizedConfig;
		const previousSerializedConfigRef = (0, react.useRef)(null);
		const targetAgentId = (0, react.useMemo)(() => {
			if (!normalizedConfig) return resolvedConsumerAgentId;
			const consumer = normalizedConfig.consumerAgentId;
			if (!consumer || consumer === "*") return resolvedConsumerAgentId;
			return consumer;
		}, [normalizedConfig, resolvedConsumerAgentId]);
		const isGlobalConfig = rawConsumerAgentId === void 0 || rawConsumerAgentId === "*";
		const isDynamicConfigType = (0, react.useMemo)(() => !!normalizedConfig && "instructions" in normalizedConfig, [normalizedConfig]);
		const requestReload = (0, react.useCallback)(() => {
			if (!normalizedConfig) return;
			if (isGlobalConfig) {
				const seen = /* @__PURE__ */ new Set();
				const agents = Object.values(copilotkit.agents ?? {});
				for (const entry of agents) {
					const agentId = entry.agentId;
					if (!agentId) continue;
					seen.add(agentId);
					if (!entry.isRunning) copilotkit.reloadSuggestions(agentId);
				}
				if (targetAgentId && !seen.has(targetAgentId)) copilotkit.reloadSuggestions(targetAgentId);
				return;
			}
			if (!targetAgentId) return;
			copilotkit.reloadSuggestions(targetAgentId);
		}, [
			copilotkit,
			isGlobalConfig,
			normalizedConfig,
			targetAgentId
		]);
		(0, react.useEffect)(() => {
			if (!serializedConfig || !latestConfigRef.current) return;
			const id = copilotkit.addSuggestionsConfig(latestConfigRef.current);
			requestReload();
			return () => {
				copilotkit.removeSuggestionsConfig(id);
			};
		}, [
			copilotkit,
			serializedConfig,
			requestReload
		]);
		(0, react.useEffect)(() => {
			if (!normalizedConfig) {
				previousSerializedConfigRef.current = null;
				return;
			}
			if (serializedConfig && previousSerializedConfigRef.current === serializedConfig) return;
			if (serializedConfig) previousSerializedConfigRef.current = serializedConfig;
			requestReload();
		}, [
			normalizedConfig,
			requestReload,
			serializedConfig
		]);
		(0, react.useEffect)(() => {
			if (!normalizedConfig || extraDeps.length === 0) return;
			requestReload();
		}, [
			extraDeps.length,
			normalizedConfig,
			requestReload,
			...extraDeps
		]);
		(0, react.useEffect)(() => {
			if (!normalizedConfig || !isDynamicConfigType) return;
			if (!targetAgentId) return;
			if (!!copilotkit.getAgent(targetAgentId)) return;
			const subscription = copilotkit.subscribe({ onAgentsChanged: () => {
				if (copilotkit.getAgent(targetAgentId)) {
					requestReload();
					subscription.unsubscribe();
				}
			} });
			return () => {
				subscription.unsubscribe();
			};
		}, [
			copilotkit,
			normalizedConfig,
			isDynamicConfigType,
			targetAgentId,
			requestReload
		]);
	}
	function isDynamicConfig(config) {
		return "instructions" in config;
	}
	function normalizeStaticSuggestions(suggestions) {
		return suggestions.map((suggestion) => ({
			...suggestion,
			isLoading: suggestion.isLoading ?? false
		}));
	}

//#endregion
//#region src/v2/hooks/use-interrupt.tsx
	const INTERRUPT_EVENT_NAME = "on_interrupt";
	function isPromiseLike(value) {
		return (typeof value === "object" || typeof value === "function") && value !== null && typeof Reflect.get(value, "then") === "function";
	}
	/** Derive the legacy-compatible `event` for any pending interrupt. */
	function toLegacyEvent(pending) {
		if (pending.kind === "legacy") return pending.event;
		return {
			name: INTERRUPT_EVENT_NAME,
			value: pending.interrupts[0]
		};
	}
	/**
	* Handles agent interrupts with optional filtering, preprocessing, and resume behavior.
	*
	* Supports both the AG-UI standard interrupt flow (`RUN_FINISHED` with
	* `outcome.type === "interrupt"`) and the legacy custom-event flow
	* (`on_interrupt`). For standard interrupts, `render` receives `interrupt`
	* (the primary one) and `interrupts` (the full open set); call `resolve(payload)`
	* to resume or `cancel()` to cancel. Resuming addresses the targeted interrupt
	* and, once every open interrupt is addressed, submits a single spec `resume`
	* array via `copilotkit.runAgent`.
	*
	* - `renderInChat: true` (default): the element is published into `<CopilotChat>`; returns `void`.
	* - `renderInChat: false`: the hook returns the interrupt element for manual placement.
	*
	* @example
	* ```tsx
	* useInterrupt({
	*   render: ({ interrupt, resolve, cancel }) => (
	*     <div>
	*       <p>{interrupt?.message}</p>
	*       <button onClick={() => resolve({ approved: true })}>Approve</button>
	*       <button onClick={() => cancel()}>Cancel</button>
	*     </div>
	*   ),
	* });
	* ```
	*/
	function useInterrupt(config) {
		const { copilotkit } = useCopilotKit();
		const { agent } = useAgent({ agentId: config.agentId });
		const [pending, setPending] = (0, react.useState)(null);
		const pendingRef = (0, react.useRef)(pending);
		pendingRef.current = pending;
		const [handlerResult, setHandlerResult] = (0, react.useState)(null);
		const interruptStateRef = (0, react.useRef)(new _copilotkit_core.ɵInterruptState());
		const interruptRunIdsRef = (0, react.useRef)(/* @__PURE__ */ new Map());
		const legacyRunIdRef = (0, react.useRef)(void 0);
		(0, react.useEffect)(() => {
			const interruptState = interruptStateRef.current;
			let localLegacy = null;
			let localStandard = null;
			const subscription = agent.subscribe({
				onCustomEvent: ({ event }) => {
					if (event.name === INTERRUPT_EVENT_NAME) localLegacy = {
						name: event.name,
						value: event.value
					};
				},
				onRunFinishedEvent: (params) => {
					if (params.outcome === "interrupt") {
						const runId = params.input.runId;
						for (const interrupt of params.interrupts) interruptRunIdsRef.current.set(interrupt.id, runId);
						localStandard = params.interrupts;
					}
				},
				onRunStartedEvent: () => {
					localLegacy = null;
					localStandard = null;
					interruptRunIdsRef.current.clear();
					legacyRunIdRef.current = void 0;
					interruptState.clear();
					setPending(null);
				},
				onRunFinalized: (params) => {
					if (localStandard && localStandard.length > 0) {
						interruptState.setStandard(localStandard);
						setPending(interruptState.pending);
					} else if (localLegacy) {
						legacyRunIdRef.current = params.input.runId;
						interruptState.setLegacy(localLegacy);
						setPending(interruptState.pending);
					}
					localLegacy = null;
					localStandard = null;
				},
				onRunFailed: () => {
					localLegacy = null;
					localStandard = null;
					interruptRunIdsRef.current.clear();
					legacyRunIdRef.current = void 0;
					interruptState.clear();
					setPending(null);
				}
			});
			return () => {
				subscription.unsubscribe();
				interruptState.clear();
			};
		}, [agent]);
		const resolve = (0, react.useCallback)(async (payload, interruptId) => {
			const current = pendingRef.current;
			if (!current) return;
			if (current.kind === "standard" && current.interrupts.length > 1 && interruptId === void 0) console.warn(`[CopilotKit] useInterrupt: resolve()/cancel() called without an interruptId while ${current.interrupts.length} interrupts are open; defaulting to the first. Pass an interruptId to address a specific interrupt.`);
			const decision = interruptStateRef.current.resolve(payload, interruptId);
			if (decision.kind === "legacy-resume") {
				const runId = legacyRunIdRef.current;
				try {
					return await copilotkit.runAgent({
						agent,
						...runId !== void 0 ? { runId } : {},
						forwardedProps: { command: {
							resume: decision.payload,
							interruptEvent: decision.interruptValue
						} }
					});
				} catch (err) {
					console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
					setPending(null);
					throw err;
				}
			}
			if (decision.kind === "expired") {
				console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
				interruptStateRef.current.clear();
				setPending(null);
				return;
			}
			if (decision.kind !== "resume") return;
			const runId = decision.resume.map((entry) => interruptRunIdsRef.current.get(entry.interruptId)).find((candidate) => candidate !== void 0);
			for (const toolResult of decision.toolResults) agent.addMessage({
				id: (0, _ag_ui_client.randomUUID)(),
				role: "tool",
				toolCallId: toolResult.toolCallId,
				content: toolResult.content
			});
			try {
				return await copilotkit.runAgent({
					agent,
					resume: decision.resume,
					...runId !== void 0 ? { runId } : {}
				});
			} catch (err) {
				console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
				interruptStateRef.current.clear();
				setPending(null);
				throw err;
			}
		}, [agent, copilotkit]);
		const cancel = (0, react.useCallback)(async (interruptId) => {
			const current = pendingRef.current;
			if (!current) return;
			if (current.kind === "standard" && current.interrupts.length > 1 && interruptId === void 0) console.warn(`[CopilotKit] useInterrupt: resolve()/cancel() called without an interruptId while ${current.interrupts.length} interrupts are open; defaulting to the first. Pass an interruptId to address a specific interrupt.`);
			const decision = interruptStateRef.current.cancel(interruptId);
			if (decision.kind === "dismiss") {
				console.warn("[CopilotKit] useInterrupt: cancel() is not supported for legacy on_interrupt interrupts; dismissing.");
				interruptStateRef.current.clear();
				setPending(null);
				return;
			}
			if (decision.kind === "expired") {
				console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
				interruptStateRef.current.clear();
				setPending(null);
				return;
			}
			if (decision.kind !== "resume") return;
			const runId = decision.resume.map((entry) => interruptRunIdsRef.current.get(entry.interruptId)).find((candidate) => candidate !== void 0);
			for (const toolResult of decision.toolResults) agent.addMessage({
				id: (0, _ag_ui_client.randomUUID)(),
				role: "tool",
				toolCallId: toolResult.toolCallId,
				content: toolResult.content
			});
			try {
				return await copilotkit.runAgent({
					agent,
					resume: decision.resume,
					...runId !== void 0 ? { runId } : {}
				});
			} catch (err) {
				console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
				interruptStateRef.current.clear();
				setPending(null);
				throw err;
			}
		}, [agent, copilotkit]);
		const renderRef = (0, react.useRef)(config.render);
		renderRef.current = config.render;
		const enabledRef = (0, react.useRef)(config.enabled);
		enabledRef.current = config.enabled;
		const handlerRef = (0, react.useRef)(config.handler);
		handlerRef.current = config.handler;
		const resolveRef = (0, react.useRef)(resolve);
		resolveRef.current = resolve;
		const cancelRef = (0, react.useRef)(cancel);
		cancelRef.current = cancel;
		const isEnabled = (event) => {
			const predicate = enabledRef.current;
			if (!predicate) return true;
			try {
				return predicate(event);
			} catch (err) {
				console.error("[CopilotKit] useInterrupt enabled predicate threw; treating interrupt as disabled:", err);
				return false;
			}
		};
		(0, react.useEffect)(() => {
			if (!pending) {
				setHandlerResult(null);
				return;
			}
			const legacyEvent = toLegacyEvent(pending);
			if (!isEnabled(legacyEvent)) {
				setHandlerResult(null);
				return;
			}
			const handler = handlerRef.current;
			if (!handler) {
				setHandlerResult(null);
				return;
			}
			let cancelled = false;
			let maybePromise;
			try {
				maybePromise = handler({
					event: legacyEvent,
					interrupt: pending.kind === "standard" ? pending.interrupts[0] : null,
					interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
					resolve: resolveRef.current,
					cancel: cancelRef.current
				});
			} catch (err) {
				console.error("[CopilotKit] useInterrupt handler threw; result will be null:", err);
				if (!cancelled) setHandlerResult(null);
				return () => {
					cancelled = true;
				};
			}
			if (isPromiseLike(maybePromise)) Promise.resolve(maybePromise).then((resolved) => {
				if (!cancelled) setHandlerResult(resolved);
			}).catch((err) => {
				console.error("[CopilotKit] useInterrupt handler rejected; result will be null:", err);
				if (!cancelled) setHandlerResult(null);
			});
			else setHandlerResult(maybePromise);
			return () => {
				cancelled = true;
			};
		}, [pending]);
		const element = (0, react.useMemo)(() => {
			if (!pending) return null;
			const legacyEvent = toLegacyEvent(pending);
			if (!isEnabled(legacyEvent)) return null;
			return renderRef.current({
				event: legacyEvent,
				interrupt: pending.kind === "standard" ? pending.interrupts[0] : null,
				interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
				result: handlerResult,
				resolve,
				cancel
			});
		}, [
			pending,
			handlerResult,
			resolve,
			cancel
		]);
		(0, react.useEffect)(() => {
			if (config.renderInChat === false) return;
			copilotkit.setInterruptElement(element);
		}, [
			element,
			config.renderInChat,
			copilotkit
		]);
		(0, react.useEffect)(() => {
			if (config.renderInChat === false) return;
			return () => {
				copilotkit.setInterruptElement(null);
			};
		}, []);
		if (config.renderInChat === false) return element;
	}

//#endregion
//#region src/context/copilot-context.tsx
	const emptyCopilotContext$1 = {
		actions: {},
		setAction: () => {},
		removeAction: () => {},
		setRegisteredActions: () => "",
		removeRegisteredAction: () => {},
		chatComponentsCache: { current: {
			actions: {},
			coAgentStateRenders: {}
		} },
		getContextString: (documents, categories) => returnAndThrowInDebug(""),
		addContext: () => "",
		removeContext: () => {},
		getAllContext: () => [],
		getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),
		isLoading: false,
		setIsLoading: () => returnAndThrowInDebug(false),
		chatInstructions: "",
		setChatInstructions: () => returnAndThrowInDebug(""),
		additionalInstructions: [],
		setAdditionalInstructions: () => returnAndThrowInDebug([]),
		getDocumentsContext: (categories) => returnAndThrowInDebug([]),
		addDocumentContext: () => returnAndThrowInDebug(""),
		removeDocumentContext: () => {},
		copilotApiConfig: new class {
			get chatApiEndpoint() {
				throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
			}
			get headers() {
				return {};
			}
			get body() {
				return {};
			}
		}(),
		chatSuggestionConfiguration: {},
		addChatSuggestionConfiguration: () => {},
		removeChatSuggestionConfiguration: () => {},
		showDevConsole: false,
		coagentStates: {},
		setCoagentStates: () => {},
		coagentStatesRef: { current: {} },
		setCoagentStatesWithRef: () => {},
		agentSession: null,
		setAgentSession: () => {},
		forwardedParameters: {},
		agentLock: null,
		threadId: "",
		setThreadId: () => {},
		runId: null,
		setRunId: () => {},
		chatAbortControllerRef: { current: null },
		availableAgents: [],
		extensions: {},
		setExtensions: () => {},
		interruptActions: {},
		setInterruptAction: () => {},
		removeInterruptAction: () => {},
		interruptEventQueue: {},
		addInterruptEvent: () => {},
		resolveInterruptEvent: () => {},
		onError: () => {},
		bannerError: null,
		setBannerError: () => {},
		internalErrorHandlers: {},
		setInternalErrorHandler: () => {},
		removeInternalErrorHandler: () => {}
	};
	const CopilotContext = react.default.createContext(emptyCopilotContext$1);
	function useCopilotContext() {
		const context = react.default.useContext(CopilotContext);
		if (context === emptyCopilotContext$1) throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
		return context;
	}
	function returnAndThrowInDebug(_value) {
		throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
	}

//#endregion
//#region src/hooks/use-tree.ts
	const removeNode = (nodes, id) => {
		return nodes.reduce((result, node) => {
			if (node.id !== id) {
				const newNode = {
					...node,
					children: removeNode(node.children, id)
				};
				result.push(newNode);
			}
			return result;
		}, []);
	};
	const addNode = (nodes, newNode, parentId) => {
		if (!parentId) return [...nodes, newNode];
		return nodes.map((node) => {
			if (node.id === parentId) return {
				...node,
				children: [...node.children, newNode]
			};
			else if (node.children.length) return {
				...node,
				children: addNode(node.children, newNode, parentId)
			};
			return node;
		});
	};
	const treeIndentationRepresentation = (index, indentLevel) => {
		if (indentLevel === 0) return (index + 1).toString();
		else if (indentLevel === 1) return String.fromCharCode(65 + index);
		else if (indentLevel === 2) return String.fromCharCode(97 + index);
		else return "-";
	};
	const printNode = (node, prefix = "", indentLevel = 0) => {
		const indent = " ".repeat(3).repeat(indentLevel);
		const prefixPlusIndentLength = prefix.length + indent.length;
		const subsequentLinesPrefix = " ".repeat(prefixPlusIndentLength);
		const valueLines = node.value.split("\n");
		const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;
		const outputSubsequentLines = valueLines.slice(1).map((line) => `${subsequentLinesPrefix}${line}`).join("\n");
		let output = `${outputFirstLine}\n`;
		if (outputSubsequentLines) output += `${outputSubsequentLines}\n`;
		const childPrePrefix = " ".repeat(prefix.length);
		node.children.forEach((child, index) => output += printNode(child, `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `, indentLevel + 1));
		return output;
	};
	function treeReducer(state, action) {
		switch (action.type) {
			case "ADD_NODE": {
				const { value, parentId, id: newNodeId } = action;
				const newNode = {
					id: newNodeId,
					value,
					children: [],
					categories: new Set(action.categories)
				};
				try {
					return addNode(state, newNode, parentId);
				} catch (error) {
					console.error(`Error while adding node with id ${newNodeId}: ${error}`);
					return state;
				}
			}
			case "REMOVE_NODE": return removeNode(state, action.id);
			default: return state;
		}
	}
	const useTree = () => {
		const [tree, dispatch] = (0, react.useReducer)(treeReducer, []);
		const addElement = (0, react.useCallback)((value, categories, parentId) => {
			const newNodeId = (0, _copilotkit_shared.randomId)();
			dispatch({
				type: "ADD_NODE",
				value,
				parentId,
				id: newNodeId,
				categories
			});
			return newNodeId;
		}, []);
		const removeElement = (0, react.useCallback)((id) => {
			dispatch({
				type: "REMOVE_NODE",
				id
			});
		}, []);
		const getAllElements = (0, react.useCallback)(() => {
			return tree;
		}, [tree]);
		return {
			tree,
			addElement,
			printTree: (0, react.useCallback)((categories) => {
				const categoriesSet = new Set(categories);
				let output = "";
				tree.forEach((node, index) => {
					if (!setsHaveIntersection$1(categoriesSet, node.categories)) return;
					if (index !== 0) output += "\n";
					output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);
				});
				return output;
			}, [tree]),
			removeElement,
			getAllElements
		};
	};
	function setsHaveIntersection$1(setA, setB) {
		const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
		for (let item of smallerSet) if (largerSet.has(item)) return true;
		return false;
	}

//#endregion
//#region src/hooks/use-flat-category-store.ts
	const useFlatCategoryStore = () => {
		const [elements, dispatch] = (0, react.useReducer)(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
		return {
			addElement: (0, react.useCallback)((value, categories) => {
				const newId = (0, _copilotkit_shared.randomId)();
				dispatch({
					type: "ADD_ELEMENT",
					value,
					id: newId,
					categories
				});
				return newId;
			}, []),
			removeElement: (0, react.useCallback)((id) => {
				dispatch({
					type: "REMOVE_ELEMENT",
					id
				});
			}, []),
			allElements: (0, react.useCallback)((categories) => {
				const categoriesSet = new Set(categories);
				const result = [];
				elements.forEach((element) => {
					if (setsHaveIntersection(categoriesSet, element.categories)) result.push(element.value);
				});
				return result;
			}, [elements])
		};
	};
	function flatCategoryStoreReducer(state, action) {
		switch (action.type) {
			case "ADD_ELEMENT": {
				const { value, id, categories } = action;
				const newElement = {
					id,
					value,
					categories: new Set(categories)
				};
				const newState = new Map(state);
				newState.set(id, newElement);
				return newState;
			}
			case "REMOVE_ELEMENT": {
				const newState = new Map(state);
				newState.delete(action.id);
				return newState;
			}
			default: return state;
		}
	}
	function setsHaveIntersection(setA, setB) {
		const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
		for (let item of smallerSet) if (largerSet.has(item)) return true;
		return false;
	}

//#endregion
//#region src/context/copilot-messages-context.tsx
	const emptyCopilotContext = {
		messages: [],
		setMessages: () => [],
		suggestions: [],
		setSuggestions: () => []
	};
	const CopilotMessagesContext = react.default.createContext(emptyCopilotContext);
	function useCopilotMessagesContext() {
		const context = react.default.useContext(CopilotMessagesContext);
		if (context === emptyCopilotContext) throw new Error("A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`");
		return context;
	}

//#endregion
//#region src/components/toast/toast-provider.tsx
	const ToastContext = (0, react.createContext)(void 0);
	function getErrorSeverity(error) {
		if (error.severity) switch (error.severity) {
			case _copilotkit_shared.Severity.CRITICAL: return "critical";
			case _copilotkit_shared.Severity.WARNING: return "warning";
			case _copilotkit_shared.Severity.INFO: return "info";
			default: return "info";
		}
		const message = error.message.toLowerCase();
		if (message.includes("api key") || message.includes("401") || message.includes("unauthorized") || message.includes("authentication") || message.includes("incorrect api key")) return "critical";
		return "info";
	}
	function getErrorColors(severity) {
		switch (severity) {
			case "critical": return {
				background: "#fee2e2",
				border: "#dc2626",
				text: "#7f1d1d",
				icon: "#dc2626"
			};
			case "warning": return {
				background: "#fef3c7",
				border: "#d97706",
				text: "#78350f",
				icon: "#d97706"
			};
			case "info": return {
				background: "#dbeafe",
				border: "#2563eb",
				text: "#1e3a8a",
				icon: "#2563eb"
			};
		}
	}
	function useToast() {
		const context = (0, react.useContext)(ToastContext);
		if (!context) throw new Error("useToast must be used within a ToastProvider");
		return context;
	}
	function formatBannerMessage(message) {
		const jsonMatch = message.match(/'message':\s*'([^']+)'/);
		if (jsonMatch) return jsonMatch[1];
		let cleaned = message.split(" - ")[0];
		cleaned = cleaned.split(": Error code")[0];
		cleaned = cleaned.replace(/:\s*\d{3}$/, "");
		cleaned = cleaned.replace(/See more:.*$/g, "");
		cleaned = cleaned.trim();
		return cleaned || "An error occurred.";
	}
	function extractUrl(message) {
		const markdownMatch = /\[([^\]]+)\]\(([^)]+)\)/.exec(message);
		if (markdownMatch) return {
			url: markdownMatch[2],
			text: "See More"
		};
		const plainMatch = /(https?:\/\/[^\s)]+)/.exec(message);
		if (plainMatch) return {
			url: plainMatch[0].replace(/[.,;:'"]*$/, ""),
			text: "See More"
		};
		return null;
	}
	function BannerErrorDisplay({ bannerError, onDismiss }) {
		const [detailsExpanded, setDetailsExpanded] = (0, react.useState)(false);
		const colors = getErrorColors(getErrorSeverity(bannerError));
		const details = bannerError.details;
		const link = extractUrl(bannerError.message);
		return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
			"data-testid": "copilot-error-banner",
			style: {
				position: "fixed",
				bottom: "20px",
				left: "50%",
				transform: "translateX(-50%)",
				zIndex: 9999,
				backgroundColor: colors.background,
				border: `1px solid ${colors.border}`,
				borderLeft: `4px solid ${colors.border}`,
				borderRadius: "8px",
				padding: "12px 16px",
				fontSize: "13px",
				boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
				backdropFilter: "blur(8px)",
				maxWidth: "min(90vw, 700px)",
				width: "100%",
				boxSizing: "border-box",
				overflow: "hidden"
			},
			children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				style: {
					display: "flex",
					justifyContent: "space-between",
					alignItems: "center",
					gap: "10px"
				},
				children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
					style: {
						display: "flex",
						alignItems: "center",
						gap: "8px",
						flex: 1,
						minWidth: 0
					},
					children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
						width: "12px",
						height: "12px",
						borderRadius: "50%",
						backgroundColor: colors.border,
						flexShrink: 0
					} }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
						style: {
							display: "flex",
							alignItems: "center",
							gap: "10px",
							flex: 1,
							minWidth: 0
						},
						children: [
							/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
								style: {
									color: colors.text,
									lineHeight: "1.4",
									fontWeight: "400",
									fontSize: "13px",
									flex: 1,
									wordBreak: "break-all",
									overflowWrap: "break-word",
									maxWidth: "550px",
									overflow: "hidden",
									display: "-webkit-box",
									WebkitLineClamp: 10,
									WebkitBoxOrient: "vertical"
								},
								children: formatBannerMessage(bannerError.message)
							}),
							link && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
								onClick: () => window.open(link.url, "_blank", "noopener,noreferrer"),
								style: {
									background: colors.border,
									color: "white",
									border: "none",
									borderRadius: "5px",
									padding: "4px 10px",
									fontSize: "11px",
									fontWeight: "500",
									cursor: "pointer",
									transition: "all 0.2s ease",
									flexShrink: 0
								},
								onMouseEnter: (e) => {
									e.currentTarget.style.opacity = "0.9";
									e.currentTarget.style.transform = "translateY(-1px)";
								},
								onMouseLeave: (e) => {
									e.currentTarget.style.opacity = "1";
									e.currentTarget.style.transform = "translateY(0)";
								},
								children: link.text
							}),
							details && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
								onClick: () => setDetailsExpanded(!detailsExpanded),
								style: {
									background: "transparent",
									border: `1px solid ${colors.border}`,
									borderRadius: "5px",
									padding: "4px 10px",
									fontSize: "11px",
									fontWeight: "500",
									cursor: "pointer",
									color: colors.text,
									flexShrink: 0,
									transition: "all 0.2s ease"
								},
								onMouseEnter: (e) => {
									e.currentTarget.style.background = "rgba(0, 0, 0, 0.05)";
								},
								onMouseLeave: (e) => {
									e.currentTarget.style.background = "transparent";
								},
								children: detailsExpanded ? "Hide Details" : "Show Details"
							})
						]
					})]
				}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
					onClick: onDismiss,
					style: {
						background: "transparent",
						border: "none",
						color: colors.text,
						cursor: "pointer",
						padding: "2px",
						borderRadius: "3px",
						fontSize: "14px",
						lineHeight: "1",
						opacity: .6,
						transition: "all 0.2s ease",
						flexShrink: 0
					},
					title: "Dismiss",
					onMouseEnter: (e) => {
						e.currentTarget.style.opacity = "1";
						e.currentTarget.style.background = "rgba(0, 0, 0, 0.05)";
					},
					onMouseLeave: (e) => {
						e.currentTarget.style.opacity = "0.6";
						e.currentTarget.style.background = "transparent";
					},
					children: "x"
				})]
			}), detailsExpanded && details && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				style: {
					marginTop: "10px",
					padding: "10px",
					background: "rgba(0, 0, 0, 0.04)",
					borderRadius: "6px",
					fontSize: "11px",
					fontFamily: "monospace",
					color: colors.text,
					lineHeight: "1.5",
					maxHeight: "200px",
					overflowY: "auto",
					whiteSpace: "pre-wrap",
					wordBreak: "break-all"
				},
				children: [
					details.code && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [
						/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "Code:" }),
						" ",
						details.code
					] }),
					details.originalMessage && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
						style: { marginTop: "4px" },
						children: [
							/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "Message:" }),
							" ",
							details.originalMessage
						]
					}),
					details.context && Object.keys(details.context).length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
						style: { marginTop: "4px" },
						children: [
							/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "Context:" }),
							" ",
							JSON.stringify(details.context, null, 2)
						]
					}),
					details.stack && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
						style: {
							marginTop: "4px",
							opacity: .7
						},
						children: [
							/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "Stack:" }),
							"\n",
							details.stack
						]
					})
				]
			})]
		});
	}
	function ToastProvider({ enabled, children }) {
		const [toasts, setToasts] = (0, react.useState)([]);
		const [bannerError, setBannerErrorState] = (0, react.useState)(null);
		const removeToast = (0, react.useCallback)((id) => {
			setToasts((prev) => prev.filter((toast) => toast.id !== id));
		}, []);
		const addToast = (0, react.useCallback)((toast) => {
			if (!enabled) return;
			const id = toast.id ?? Math.random().toString(36).slice(2, 9);
			setToasts((currentToasts) => {
				if (currentToasts.find((toast) => toast.id === id)) return currentToasts;
				return [...currentToasts, {
					...toast,
					id
				}];
			});
			if (toast.duration) setTimeout(() => {
				removeToast(id);
			}, toast.duration);
		}, [enabled, removeToast]);
		const setBannerError = (0, react.useCallback)((error) => {
			if (!enabled && error !== null) return;
			setBannerErrorState(error);
		}, [enabled]);
		const value = {
			toasts,
			addToast,
			addGraphQLErrorsToast: (0, react.useCallback)((errors) => {
				console.warn("addGraphQLErrorsToast is deprecated. All errors now show as banners.");
			}, []),
			removeToast,
			enabled,
			bannerError,
			setBannerError
		};
		return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(ToastContext.Provider, {
			value,
			children: [bannerError && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BannerErrorDisplay, {
				bannerError,
				onDismiss: () => setBannerError(null)
			}), children]
		});
	}

//#endregion
//#region src/utils/dev-console.ts
	function isLocalhost() {
		if (typeof window === "undefined") return false;
		return window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "0.0.0.0";
	}
	function shouldShowDevConsole(showDevConsole) {
		if (showDevConsole !== void 0) return showDevConsole;
		return isLocalhost();
	}

//#endregion
//#region src/components/copilot-provider/copilot-messages.tsx
/**
	* An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context
	*/
	/**
	* Determine whether a GraphQL error should be suppressed based on its visibility
	* and whether the dev console is active.
	*
	* Returns `null` when the error should be surfaced to the UI, or a log prefix
	* string when the error should be suppressed (logged to console only).
	*
	* Exported for unit testing.
	*/
	function getErrorSuppression(visibility, isDev) {
		if (visibility === _copilotkit_shared.ErrorVisibility.SILENT) return "CopilotKit Silent Error:";
		if (!isDev && visibility === _copilotkit_shared.ErrorVisibility.DEV_ONLY) return "CopilotKit Error (hidden in production):";
		return null;
	}
	const MessagesTapContext = (0, react.createContext)(null);
	function useMessagesTap() {
		const tap = (0, react.useContext)(MessagesTapContext);
		if (!tap) throw new Error("useMessagesTap must be used inside <MessagesTapProvider>");
		return tap;
	}
	function MessagesTapProvider({ children }) {
		const messagesRef = (0, react.useRef)([]);
		const tapRef = (0, react.useRef)({
			getMessagesFromTap: () => messagesRef.current,
			updateTapMessages: (messages) => {
				messagesRef.current = messages;
			}
		});
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessagesTapContext.Provider, {
			value: tapRef.current,
			children
		});
	}
	/**
	* CopilotKit messages context.
	*/
	function CopilotMessages({ children }) {
		const [messages, setMessages] = (0, react.useState)([]);
		(0, react.useRef)(void 0);
		(0, react.useRef)(void 0);
		(0, react.useRef)(void 0);
		const { updateTapMessages } = useMessagesTap();
		const { threadId, agentSession, showDevConsole, onError, copilotApiConfig } = useCopilotContext();
		const { setBannerError } = useToast();
		const traceUIError = (0, react.useCallback)(async (error, originalError) => {
			if (!onError || !copilotApiConfig.publicApiKey) return;
			try {
				await onError({
					type: "error",
					timestamp: Date.now(),
					context: {
						source: "ui",
						request: {
							operation: "loadAgentState",
							url: copilotApiConfig.chatApiEndpoint,
							startTime: Date.now()
						},
						technical: {
							environment: "browser",
							userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
							stackTrace: originalError instanceof Error ? originalError.stack : void 0
						}
					},
					error
				});
			} catch (traceError) {
				console.error("Error in CopilotMessages onError handler:", traceError);
			}
		}, [
			onError,
			copilotApiConfig.publicApiKey,
			copilotApiConfig.chatApiEndpoint
		]);
		const createStructuredError = (gqlError) => {
			const extensions = gqlError.extensions;
			const originalError = extensions?.originalError;
			if (originalError?.stack) {
				if (originalError.stack.includes("CopilotApiDiscoveryError")) return new _copilotkit_shared.CopilotKitApiDiscoveryError({ message: originalError.message });
				if (originalError.stack.includes("CopilotKitRemoteEndpointDiscoveryError")) return new _copilotkit_shared.CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });
				if (originalError.stack.includes("CopilotKitAgentDiscoveryError")) return new _copilotkit_shared.CopilotKitAgentDiscoveryError({
					agentName: "",
					availableAgents: []
				});
			}
			const message = originalError?.message || gqlError.message;
			const code = extensions?.code;
			if (code) return new _copilotkit_shared.CopilotKitError({
				message,
				code
			});
			return null;
		};
		(0, react.useCallback)((error) => {
			if (error.graphQLErrors?.length) {
				const graphQLErrors = error.graphQLErrors;
				const routeError = (gqlError) => {
					const visibility = gqlError.extensions?.visibility;
					const suppression = getErrorSuppression(visibility, shouldShowDevConsole(showDevConsole));
					if (suppression) {
						console.error(suppression, gqlError.message);
						return;
					}
					const ckError = createStructuredError(gqlError);
					if (ckError) {
						setBannerError(ckError);
						traceUIError(ckError, gqlError);
					} else {
						const fallbackError = new _copilotkit_shared.CopilotKitError({
							message: gqlError.message,
							code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
						});
						setBannerError(fallbackError);
						traceUIError(fallbackError, gqlError);
					}
				};
				graphQLErrors.forEach(routeError);
			} else {
				const fallbackError = new _copilotkit_shared.CopilotKitError({
					message: error?.message || String(error),
					code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
				});
				setBannerError(fallbackError);
				traceUIError(fallbackError, error);
			}
		}, [
			setBannerError,
			showDevConsole,
			traceUIError
		]);
		(0, react.useEffect)(() => {
			updateTapMessages(messages);
		}, [messages, updateTapMessages]);
		const memoizedChildren = (0, react.useMemo)(() => children, [children]);
		const [suggestions, setSuggestions] = (0, react.useState)([]);
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotMessagesContext.Provider, {
			value: {
				messages,
				setMessages,
				suggestions,
				setSuggestions
			},
			children: memoizedChildren
		});
	}

//#endregion
//#region src/components/usage-banner.tsx
	function UsageBanner({ severity = _copilotkit_shared.Severity.CRITICAL, message = "", onClose, actions }) {
		if (!message || !severity) return null;
		const theme = {
			[_copilotkit_shared.Severity.INFO]: {
				bg: "#f8fafc",
				border: "#e2e8f0",
				text: "#475569",
				accent: "#3b82f6"
			},
			[_copilotkit_shared.Severity.WARNING]: {
				bg: "#fffbeb",
				border: "#fbbf24",
				text: "#92400e",
				accent: "#f59e0b"
			},
			[_copilotkit_shared.Severity.CRITICAL]: {
				bg: "#fef2f2",
				border: "#fecaca",
				text: "#dc2626",
				accent: "#ef4444"
			}
		}[severity];
		return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { children: `
          @keyframes slideUp {
            from { opacity: 0; transform: translateX(-50%) translateY(8px); }
            to { opacity: 1; transform: translateX(-50%) translateY(0); }
          }
          
          .usage-banner {
            position: fixed;
            bottom: 24px;
            left: 50%;
            transform: translateX(-50%);
            width: min(600px, calc(100vw - 32px));
            z-index: 10000;
            animation: slideUp 0.2s cubic-bezier(0.16, 1, 0.3, 1);
          }
          
          .banner-content {
            background: linear-gradient(135deg, ${theme.bg} 0%, ${theme.bg}f5 100%);
            border: 1px solid ${theme.border};
            border-radius: 12px;
            padding: 18px 20px;
            box-shadow: 
              0 4px 24px rgba(0, 0, 0, 0.08),
              0 2px 8px rgba(0, 0, 0, 0.04),
              inset 0 1px 0 rgba(255, 255, 255, 0.7);
            display: flex;
            align-items: center;
            gap: 16px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
            backdrop-filter: blur(12px);
            position: relative;
            overflow: hidden;
          }
          
          .banner-content::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, ${theme.accent}40, transparent);
          }
          
          .banner-message {
            color: ${theme.text};
            font-size: 14px;
            line-height: 1.5;
            font-weight: 500;
            flex: 1;
            letter-spacing: -0.01em;
          }
          
          .close-btn {
            background: rgba(0, 0, 0, 0.05);
            border: none;
            color: ${theme.text};
            cursor: pointer;
            padding: 0;
            border-radius: 6px;
            opacity: 0.6;
            transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);
            font-size: 14px;
            line-height: 1;
            flex-shrink: 0;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          
          .close-btn:hover {
            opacity: 1;
            background: rgba(0, 0, 0, 0.08);
            transform: scale(1.05);
          }
          
          .btn-primary {
            background: linear-gradient(135deg, ${theme.accent} 0%, ${theme.accent}e6 100%);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 10px 18px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);
            font-family: inherit;
            flex-shrink: 0;
            box-shadow: 
              0 2px 8px ${theme.accent}30,
              inset 0 1px 0 rgba(255, 255, 255, 0.2);
            letter-spacing: -0.01em;
          }
          
          .btn-primary:hover {
            transform: translateY(-1px) scale(1.02);
            box-shadow: 
              0 4px 12px ${theme.accent}40,
              inset 0 1px 0 rgba(255, 255, 255, 0.25);
          }
          
          .btn-primary:active {
            transform: translateY(0) scale(0.98);
            transition: all 0.08s cubic-bezier(0.16, 1, 0.3, 1);
          }
          
          @media (max-width: 640px) {
            .usage-banner {
              width: calc(100vw - 24px);
            }
            
            .banner-content {
              padding: 16px;
              gap: 12px;
            }
            
            .banner-message {
              font-size: 13px;
              line-height: 1.45;
            }
            
            .btn-primary {
              padding: 8px 14px;
              font-size: 12px;
            }
            
            .close-btn {
              width: 22px;
              height: 22px;
              font-size: 12px;
            }
          }
        ` }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
			className: "usage-banner",
			"data-testid": "copilot-error-banner",
			children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				className: "banner-content",
				children: [
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: "banner-message",
						children: message
					}),
					actions?.primary && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
						className: "btn-primary",
						onClick: actions.primary.onClick,
						children: actions.primary.label
					}),
					onClose && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
						className: "close-btn",
						onClick: onClose,
						title: "Close",
						children: "×"
					})
				]
			})
		})] });
	}
	const getErrorActions = (error) => {
		switch (error.code) {
			case _copilotkit_shared.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR: return { primary: {
				label: "Show me how",
				onClick: () => window.open("https://docs.copilotkit.ai/premium/overview#getting-access", "_blank", "noopener,noreferrer")
			} };
			case _copilotkit_shared.CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR: return { primary: {
				label: "Upgrade",
				onClick: () => window.open("https://dashboard.operations.copilotkit.ai", "_blank", "noopener,noreferrer")
			} };
			default: return;
		}
	};

//#endregion
//#region src/utils/suggestions-constants.ts
/**
	* Constants for suggestions retry logic
	*/
	const SUGGESTION_RETRY_CONFIG = {
		MAX_RETRIES: 3,
		COOLDOWN_MS: 5e3
	};

//#endregion
//#region src/lib/status-checker.ts
	const STATUS_CHECK_INTERVAL = 1e3 * 60 * 5;
	var StatusChecker = class {
		constructor() {
			this.activeKey = null;
			this.intervalId = null;
			this.instanceCount = 0;
			this.lastResponse = null;
		}
		async start(publicApiKey, onUpdate) {
			this.instanceCount++;
			if (this.activeKey === publicApiKey) return;
			if (this.intervalId) clearInterval(this.intervalId);
			const checkStatus = async () => {
				try {
					const response = await fetch(`${_copilotkit_shared.COPILOT_CLOUD_API_URL}/ciu`, {
						method: "GET",
						headers: { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey }
					}).then((response) => response.json());
					this.lastResponse = response;
					onUpdate?.(response);
					return response;
				} catch (error) {
					return null;
				}
			};
			const initialResponse = await checkStatus();
			this.intervalId = setInterval(checkStatus, STATUS_CHECK_INTERVAL);
			this.activeKey = publicApiKey;
			return initialResponse;
		}
		getLastResponse() {
			return this.lastResponse;
		}
		stop() {
			this.instanceCount--;
			if (this.instanceCount === 0) {
				if (this.intervalId) {
					clearInterval(this.intervalId);
					this.intervalId = null;
					this.activeKey = null;
					this.lastResponse = null;
				}
			}
		}
	};

//#endregion
//#region src/components/toast/exclamation-mark-icon.tsx
	const ExclamationMarkIcon = ({ className, style }) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
		xmlns: "http://www.w3.org/2000/svg",
		width: "24",
		height: "24",
		viewBox: "0 0 24 24",
		fill: "none",
		stroke: "currentColor",
		strokeWidth: "2",
		strokeLinecap: "round",
		strokeLinejoin: "round",
		className: `lucide lucide-circle-alert ${className ? className : ""}`,
		style,
		children: [
			/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
				cx: "12",
				cy: "12",
				r: "10"
			}),
			/* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
				x1: "12",
				x2: "12",
				y1: "8",
				y2: "12"
			}),
			/* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
				x1: "12",
				x2: "12.01",
				y1: "16",
				y2: "16"
			})
		]
	});

//#endregion
//#region src/components/error-boundary/error-utils.tsx
	function ErrorToast({ errors }) {
		return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
			style: {
				fontSize: "13px",
				maxWidth: "600px"
			},
			children: [errors.map((error, idx) => {
				const message = ("extensions" in error ? error.extensions?.originalError : {})?.message ?? error.message;
				const code = "extensions" in error ? error.extensions?.code : null;
				return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
					style: {
						marginTop: idx === 0 ? 0 : 10,
						marginBottom: 14
					},
					children: [
						/* @__PURE__ */ (0, react_jsx_runtime.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
						code && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
							style: {
								fontWeight: "600",
								marginBottom: 4
							},
							children: [
								"Copilot Runtime Error:",
								" ",
								/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
									style: {
										fontFamily: "monospace",
										fontWeight: "normal"
									},
									children: code
								})
							]
						}),
						/* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_markdown.default, { children: message })
					]
				}, idx);
			}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
				style: {
					fontSize: "11px",
					opacity: .75
				},
				children: "NOTE: This error only displays during local development."
			})]
		});
	}
	function useErrorToast() {
		const { addToast } = useToast();
		return (0, react.useCallback)((errors) => {
			addToast({
				type: "error",
				id: errors.map((err) => {
					const message = "extensions" in err ? (err.extensions?.originalError)?.message || err.message : err.message;
					const stack = err.stack || "";
					return btoa(message + stack).slice(0, 32);
				}).join("|"),
				message: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorToast, { errors })
			});
		}, [addToast]);
	}
	function useAsyncCallback(callback, deps) {
		const addErrorToast = useErrorToast();
		return (0, react.useCallback)(async (...args) => {
			try {
				return await callback(...args);
			} catch (error) {
				console.error("Error in async callback:", error);
				addErrorToast([error]);
				throw error;
			}
		}, deps);
	}

//#endregion
//#region src/components/error-boundary/error-boundary.tsx
	const statusChecker = new StatusChecker();
	var CopilotErrorBoundary = class extends react.default.Component {
		constructor(props) {
			super(props);
			this.state = { hasError: false };
		}
		static getDerivedStateFromError(error) {
			return {
				hasError: true,
				error
			};
		}
		componentDidMount() {
			if (this.props.publicApiKey) statusChecker.start(this.props.publicApiKey, (newStatus) => {
				this.setState((prevState) => {
					if (newStatus?.severity !== prevState.status?.severity) return { status: newStatus ?? void 0 };
					return null;
				});
			});
		}
		componentWillUnmount() {
			statusChecker.stop();
		}
		componentDidCatch(error, errorInfo) {
			console.error("CopilotKit Error:", error, errorInfo);
		}
		render() {
			if (this.state.hasError) {
				if (this.state.error instanceof _copilotkit_shared.CopilotKitError) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [this.props.children, this.props.showUsageBanner && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UsageBanner, {
					severity: this.state.status?.severity ?? this.state.error.severity,
					message: this.state.status?.message ?? this.state.error.message,
					actions: getErrorActions(this.state.error)
				})] });
				throw this.state.error;
			}
			return this.props.children;
		}
	};

//#endregion
//#region src/context/coagent-state-renders-context.tsx
	const CoAgentStateRendersContext = (0, react.createContext)(void 0);
	function CoAgentStateRendersProvider({ children }) {
		const [coAgentStateRenders, setCoAgentStateRenders] = (0, react.useState)({});
		const setCoAgentStateRender = (0, react.useCallback)((id, stateRender) => {
			setCoAgentStateRenders((prevPoints) => ({
				...prevPoints,
				[id]: stateRender
			}));
		}, []);
		const removeCoAgentStateRender = (0, react.useCallback)((id) => {
			setCoAgentStateRenders((prevPoints) => {
				const newPoints = { ...prevPoints };
				delete newPoints[id];
				return newPoints;
			});
		}, []);
		const claimsRef = (0, react.useRef)({});
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CoAgentStateRendersContext.Provider, {
			value: {
				coAgentStateRenders,
				setCoAgentStateRender,
				removeCoAgentStateRender,
				claimsRef
			},
			children
		});
	}
	function useCoAgentStateRenders() {
		const context = (0, react.useContext)(CoAgentStateRendersContext);
		if (!context) throw new Error("useCoAgentStateRenders must be used within CoAgentStateRendersProvider");
		return context;
	}

//#endregion
//#region src/context/threads-context.tsx
	const ThreadsContext = (0, react.createContext)(void 0);
	function ThreadsProvider({ children, threadId: explicitThreadId }) {
		const [internalThreadId, setInternalThreadId] = (0, react.useState)(() => (0, _copilotkit_shared.randomUUID)());
		const [internalIsExplicit, setInternalIsExplicit] = (0, react.useState)(false);
		const threadId = explicitThreadId ?? internalThreadId;
		const isThreadIdExplicit = explicitThreadId != null || internalIsExplicit;
		const setThreadId = (0, react.useCallback)((value) => {
			setInternalThreadId(value);
			setInternalIsExplicit(true);
		}, []);
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ThreadsContext.Provider, {
			value: {
				threadId,
				setThreadId,
				isThreadIdExplicit
			},
			children
		});
	}
	function useThreads() {
		const context = (0, react.useContext)(ThreadsContext);
		if (!context) throw new Error("useThreads must be used within ThreadsProvider");
		return context;
	}

//#endregion
//#region src/hooks/use-coagent-state-render-bridge.helpers.ts
	let RenderStatus = /* @__PURE__ */ function(RenderStatus) {
		RenderStatus["InProgress"] = "inProgress";
		RenderStatus["Complete"] = "complete";
		return RenderStatus;
	}({});
	let ClaimAction = /* @__PURE__ */ function(ClaimAction) {
		ClaimAction["Create"] = "create";
		ClaimAction["Override"] = "override";
		ClaimAction["Existing"] = "existing";
		ClaimAction["Block"] = "block";
		return ClaimAction;
	}({});
	function getStateWithoutConstantKeys(state) {
		if (!state) return {};
		const { messages, tools, copilotkit, ...stateWithoutConstantKeys } = state;
		return stateWithoutConstantKeys;
	}
	function areStatesEquals(a, b) {
		if (a && !b || !a && b) return false;
		const { messages, tools, copilotkit, ...aWithoutConstantKeys } = a;
		const { messages: bMessages, tools: bTools, copilotkit: bCopilotkit, ...bWithoutConstantKeys } = b;
		return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);
	}
	function isPlaceholderMessageId(messageId) {
		return !!messageId && messageId.startsWith("coagent-state-render-");
	}
	function isPlaceholderMessageName(messageName) {
		return messageName === "coagent-state-render";
	}
	function readCachedMessageEntry(entry) {
		if (!entry || typeof entry !== "object") return {
			snapshot: entry,
			runId: void 0
		};
		return {
			snapshot: "snapshot" in entry ? entry.snapshot : entry,
			runId: "runId" in entry ? entry.runId : void 0
		};
	}
	function getEffectiveRunId({ existingClaimRunId, cachedMessageRunId, runId }) {
		return existingClaimRunId || cachedMessageRunId || runId || "pending";
	}
	/**
	* Resolve whether a message can claim a render slot.
	* This is a pure decision function; the caller applies claim mutations.
	*/
	function resolveClaim({ claims, context, stateSnapshot }) {
		const { messageId, stateRenderId, runId, messageIndex } = context;
		const existing = claims[messageId];
		if (existing) {
			const canRender = existing.stateRenderId === stateRenderId;
			const shouldUpdateRunId = canRender && runId && (!existing.runId || existing.runId === "pending");
			return {
				canRender,
				action: canRender ? ClaimAction.Existing : ClaimAction.Block,
				updateRunId: shouldUpdateRunId ? runId : void 0
			};
		}
		const normalizedRunId = runId ?? "pending";
		const renderClaimedByOtherMessageEntry = Object.entries(claims).find(([, claim]) => claim.stateRenderId === stateRenderId && (claim.runId ?? "pending") === normalizedRunId && (0, _copilotkit_shared.dataToUUID)(getStateWithoutConstantKeys(claim.stateSnapshot)) === (0, _copilotkit_shared.dataToUUID)(getStateWithoutConstantKeys(stateSnapshot)));
		const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry?.[1];
		const claimedMessageId = renderClaimedByOtherMessageEntry?.[0];
		if (renderClaimedByOtherMessage) {
			if (messageIndex !== void 0 && renderClaimedByOtherMessage.messageIndex !== void 0 && messageIndex > renderClaimedByOtherMessage.messageIndex) return {
				canRender: true,
				action: ClaimAction.Override,
				nextClaim: {
					stateRenderId,
					runId,
					messageIndex
				},
				lockOthers: runId === renderClaimedByOtherMessage.runId || isPlaceholderMessageId(claimedMessageId)
			};
			if (runId && renderClaimedByOtherMessage.runId && runId !== renderClaimedByOtherMessage.runId) return {
				canRender: true,
				action: ClaimAction.Override,
				nextClaim: {
					stateRenderId,
					runId,
					messageIndex
				},
				lockOthers: isPlaceholderMessageId(claimedMessageId)
			};
			if (isPlaceholderMessageId(claimedMessageId)) return {
				canRender: true,
				action: ClaimAction.Override,
				nextClaim: {
					stateRenderId,
					runId,
					messageIndex
				},
				lockOthers: true
			};
			if (stateSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, stateSnapshot)) return {
				canRender: true,
				action: ClaimAction.Override,
				nextClaim: {
					stateRenderId,
					runId
				}
			};
			return {
				canRender: false,
				action: ClaimAction.Block
			};
		}
		if (!runId) return {
			canRender: false,
			action: ClaimAction.Block
		};
		return {
			canRender: true,
			action: ClaimAction.Create,
			nextClaim: {
				stateRenderId,
				runId,
				messageIndex
			}
		};
	}
	/**
	* Select the best snapshot to render for this message.
	* Priority order is:
	* 1) explicit message snapshot
	* 2) live agent state (latest assistant only)
	* 3) cached snapshot for message
	* 4) cached snapshot for stateRenderId+runId
	* 5) last cached snapshot for stateRenderId
	*/
	function selectSnapshot({ messageId, messageName, allowLiveState, skipLatestCache, stateRenderId, effectiveRunId, stateSnapshotProp, agentState, agentMessages, existingClaim, caches }) {
		const lastAssistantId = agentMessages ? [...agentMessages].toReversed().find((msg) => msg.role === "assistant")?.id : void 0;
		const latestSnapshot = stateRenderId !== void 0 ? caches.byStateRenderAndRun[`${stateRenderId}::latest`] : void 0;
		const messageIndex = agentMessages ? agentMessages.findIndex((msg) => msg.id === messageId) : -1;
		const messageRole = messageIndex >= 0 && agentMessages ? agentMessages[messageIndex]?.role : void 0;
		let previousUserMessageId;
		if (messageIndex > 0 && agentMessages) {
			for (let i = messageIndex - 1; i >= 0; i -= 1) if (agentMessages[i]?.role === "user") {
				previousUserMessageId = agentMessages[i]?.id;
				break;
			}
		}
		const liveStateIsStale = stateSnapshotProp === void 0 && latestSnapshot !== void 0 && agentState !== void 0 && areStatesEquals(latestSnapshot, agentState);
		const shouldUseLiveState = (Boolean(allowLiveState) || !lastAssistantId || messageId === lastAssistantId) && !liveStateIsStale;
		const snapshot = stateSnapshotProp ? (0, _copilotkit_shared.parseJson)(stateSnapshotProp, stateSnapshotProp) : shouldUseLiveState ? agentState : void 0;
		const hasSnapshotKeys = !!(snapshot && Object.keys(snapshot).length > 0);
		const allowEmptySnapshot = snapshot !== void 0 && !hasSnapshotKeys && (stateSnapshotProp !== void 0 || shouldUseLiveState);
		const messageCacheEntry = caches.byMessageId[messageId];
		const cachedMessageSnapshot = readCachedMessageEntry(messageCacheEntry).snapshot;
		const cacheKey = stateRenderId !== void 0 ? `${stateRenderId}::${effectiveRunId}` : void 0;
		let cachedSnapshot = cachedMessageSnapshot ?? caches.byMessageId[messageId];
		if (cachedSnapshot === void 0 && cacheKey && caches.byStateRenderAndRun[cacheKey] !== void 0) cachedSnapshot = caches.byStateRenderAndRun[cacheKey];
		if (cachedSnapshot === void 0 && stateRenderId && previousUserMessageId && caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`] !== void 0) cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`];
		if (cachedSnapshot === void 0 && !skipLatestCache && stateRenderId && messageRole !== "assistant" && (stateSnapshotProp !== void 0 || agentState && Object.keys(agentState).length > 0)) cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`];
		const snapshotForClaim = existingClaim?.locked ? existingClaim.stateSnapshot ?? cachedSnapshot : hasSnapshotKeys ? snapshot : existingClaim?.stateSnapshot ?? cachedSnapshot;
		return {
			snapshot,
			hasSnapshotKeys,
			cachedSnapshot,
			allowEmptySnapshot,
			snapshotForClaim
		};
	}

//#endregion
//#region src/hooks/use-coagent-state-render-registry.ts
	const LAST_SNAPSHOTS_BY_RENDER_AND_RUN = "__lastSnapshotsByStateRenderIdAndRun";
	const LAST_SNAPSHOTS_BY_MESSAGE = "__lastSnapshotsByMessageId";
	function getClaimsStore(claimsRef) {
		return claimsRef.current;
	}
	function getSnapshotCaches(claimsRef) {
		const store = getClaimsStore(claimsRef);
		return {
			byStateRenderAndRun: store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {},
			byMessageId: store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}
		};
	}
	function useStateRenderRegistry({ agentId, stateRenderId, message, messageIndex, stateSnapshot, agentState, agentMessages, claimsRef }) {
		const store = getClaimsStore(claimsRef);
		const runId = message.runId;
		const cachedMessageEntry = store[LAST_SNAPSHOTS_BY_MESSAGE]?.[message.id];
		const { runId: cachedMessageRunId } = readCachedMessageEntry(cachedMessageEntry);
		const existingClaimRunId = claimsRef.current[message.id]?.runId;
		const effectiveRunId = getEffectiveRunId({
			existingClaimRunId,
			cachedMessageRunId,
			runId
		});
		(0, react.useEffect)(() => {
			return () => {
				const existingClaim = claimsRef.current[message.id];
				if (existingClaim?.stateSnapshot && Object.keys(existingClaim.stateSnapshot).length > 0) {
					const snapshotCache = { ...store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] };
					const cacheKey = `${existingClaim.stateRenderId}::${existingClaim.runId ?? "pending"}`;
					snapshotCache[cacheKey] = existingClaim.stateSnapshot;
					snapshotCache[`${existingClaim.stateRenderId}::latest`] = existingClaim.stateSnapshot;
					store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
					const messageCache = { ...store[LAST_SNAPSHOTS_BY_MESSAGE] };
					messageCache[message.id] = {
						snapshot: existingClaim.stateSnapshot,
						runId: existingClaim.runId ?? effectiveRunId
					};
					store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
				}
				delete claimsRef.current[message.id];
			};
		}, [
			claimsRef,
			effectiveRunId,
			message.id
		]);
		if (!stateRenderId) return { canRender: false };
		const caches = getSnapshotCaches(claimsRef);
		const existingClaim = claimsRef.current[message.id];
		const { snapshot, hasSnapshotKeys, allowEmptySnapshot, snapshotForClaim } = selectSnapshot({
			messageId: message.id,
			messageName: message.name,
			allowLiveState: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),
			skipLatestCache: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),
			stateRenderId,
			effectiveRunId,
			stateSnapshotProp: stateSnapshot,
			agentState,
			agentMessages,
			existingClaim,
			caches
		});
		const resolution = resolveClaim({
			claims: claimsRef.current,
			context: {
				agentId,
				messageId: message.id,
				stateRenderId,
				runId: effectiveRunId,
				messageIndex
			},
			stateSnapshot: snapshotForClaim
		});
		if (resolution.action === ClaimAction.Block) return { canRender: false };
		if (resolution.updateRunId && claimsRef.current[message.id]) claimsRef.current[message.id].runId = resolution.updateRunId;
		if (resolution.nextClaim) claimsRef.current[message.id] = resolution.nextClaim;
		if (resolution.lockOthers) Object.entries(claimsRef.current).forEach(([id, claim]) => {
			if (id !== message.id && claim.stateRenderId === stateRenderId) claim.locked = true;
		});
		if (existingClaim && !existingClaim.locked && agentMessages?.length) {
			const indexInAgentMessages = agentMessages.findIndex((msg) => msg.id === message.id);
			if (indexInAgentMessages >= 0 && indexInAgentMessages < agentMessages.length - 1) existingClaim.locked = true;
		}
		const existingSnapshot = claimsRef.current[message.id].stateSnapshot;
		const snapshotChanged = stateSnapshot && existingSnapshot !== void 0 && !areStatesEquals(existingSnapshot, snapshot);
		if (snapshot && (stateSnapshot || hasSnapshotKeys || allowEmptySnapshot) && (!claimsRef.current[message.id].locked || snapshotChanged)) {
			if (!claimsRef.current[message.id].locked || snapshotChanged) {
				claimsRef.current[message.id].stateSnapshot = snapshot;
				const snapshotCache = { ...store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] };
				const cacheKey = `${stateRenderId}::${effectiveRunId}`;
				snapshotCache[cacheKey] = snapshot;
				snapshotCache[`${stateRenderId}::latest`] = snapshot;
				store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
				const messageCache = { ...store[LAST_SNAPSHOTS_BY_MESSAGE] };
				messageCache[message.id] = {
					snapshot,
					runId: effectiveRunId
				};
				store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
				if (stateSnapshot) claimsRef.current[message.id].locked = true;
			}
		} else if (snapshotForClaim) {
			if (!claimsRef.current[message.id].stateSnapshot) {
				claimsRef.current[message.id].stateSnapshot = snapshotForClaim;
				const snapshotCache = { ...store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] };
				const cacheKey = `${stateRenderId}::${effectiveRunId}`;
				snapshotCache[cacheKey] = snapshotForClaim;
				snapshotCache[`${stateRenderId}::latest`] = snapshotForClaim;
				store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
				const messageCache = { ...store[LAST_SNAPSHOTS_BY_MESSAGE] };
				messageCache[message.id] = {
					snapshot: snapshotForClaim,
					runId: effectiveRunId
				};
				store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
			}
		}
		return { canRender: true };
	}

//#endregion
//#region src/hooks/use-coagent-state-render-bridge.tsx
	function useCoagentStateRenderBridge(agentId, props) {
		const { stateSnapshot, message } = props;
		const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();
		const { agent } = useAgent({ agentId });
		const [nodeName, setNodeName] = (0, react.useState)(void 0);
		const [, forceUpdate] = (0, react.useState)(0);
		(0, react.useEffect)(() => {
			if (!agent) return;
			const { unsubscribe } = agent.subscribe({
				onStateChanged: () => {
					forceUpdate((value) => value + 1);
				},
				onStepStartedEvent: ({ event }) => {
					if (event.stepName !== nodeName) setNodeName(event.stepName);
				},
				onStepFinishedEvent: ({ event }) => {
					if (event.stepName === nodeName) setNodeName(void 0);
				}
			});
			return () => {
				unsubscribe();
			};
		}, [agentId, nodeName]);
		const getStateRender = (0, react.useCallback)((messageId) => {
			return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {
				if (claimsRef.current[messageId]) return stateRenderId === claimsRef.current[messageId].stateRenderId;
				const matchingAgentName = stateRender.name === agentId;
				const matchesNodeContext = stateRender.nodeName ? stateRender.nodeName === nodeName : true;
				return matchingAgentName && matchesNodeContext;
			});
		}, [
			coAgentStateRenders,
			nodeName,
			agentId
		]);
		const stateRenderEntry = (0, react.useMemo)(() => getStateRender(message.id), [getStateRender, message.id]);
		const stateRenderId = stateRenderEntry?.[0];
		const stateRender = stateRenderEntry?.[1];
		const { canRender } = useStateRenderRegistry({
			agentId,
			stateRenderId,
			message: {
				...message,
				runId: props.runId ?? message.runId
			},
			messageIndex: props.messageIndex,
			stateSnapshot,
			agentState: agent?.state,
			agentMessages: agent?.messages,
			claimsRef
		});
		return (0, react.useMemo)(() => {
			if (!stateRender || !stateRenderId) return null;
			if (!canRender) return null;
			if (stateRender.handler) stateRender.handler({
				state: stateSnapshot ? (0, _copilotkit_shared.parseJson)(stateSnapshot, stateSnapshot) : agent?.state ?? {},
				nodeName: nodeName ?? ""
			});
			if (stateRender.render) {
				const status = agent?.isRunning ? RenderStatus.InProgress : RenderStatus.Complete;
				if (typeof stateRender.render === "string") return stateRender.render;
				return stateRender.render({
					status,
					state: claimsRef.current[message.id].stateSnapshot ?? {},
					nodeName: nodeName ?? ""
				});
			}
		}, [
			stateRender,
			stateRenderId,
			agent?.state,
			agent?.isRunning,
			nodeName,
			message.id,
			stateSnapshot,
			canRender
		]);
	}
	function CoAgentStateRenderBridge(props) {
		return useCoagentStateRenderBridge(props.agentId, props);
	}

//#endregion
//#region src/components/CopilotListeners.tsx
	const usePredictStateSubscription = (agent) => {
		const predictStateToolsRef = (0, react.useRef)([]);
		const getSubscriber = (0, react.useCallback)((agent) => ({
			onCustomEvent: ({ event }) => {
				if (event.name === "PredictState") predictStateToolsRef.current = event.value;
			},
			onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {
				predictStateToolsRef.current.forEach((t) => {
					if (t?.tool !== toolCallName) return;
					const emittedState = typeof partialToolCallArgs === "string" ? (0, _copilotkit_shared.parseJson)(partialToolCallArgs, partialToolCallArgs) : partialToolCallArgs;
					agent.setState({ [t.state_key]: emittedState[t.state_key] });
				});
			}
		}), []);
		(0, react.useEffect)(() => {
			if (!agent) return;
			const subscriber = getSubscriber(agent);
			const { unsubscribe } = agent.subscribe(subscriber);
			return () => {
				unsubscribe();
			};
		}, [agent, getSubscriber]);
	};
	function CopilotListenersAgentSubscription() {
		const { copilotkit } = useCopilotKit();
		const configAgentId = useCopilotChatConfiguration()?.agentId;
		const { agent } = useAgent({ agentId: (0, react.useMemo)(() => {
			const requested = configAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
			const registered = copilotkit.agents ?? {};
			if (registered[requested]) return requested;
			if (requested === _copilotkit_shared.DEFAULT_AGENT_ID) {
				const firstRegistered = Object.keys(registered)[0];
				if (firstRegistered) return firstRegistered;
			}
			return requested;
		}, [configAgentId, copilotkit.agents]) });
		usePredictStateSubscription(agent);
		return null;
	}
	function CopilotListeners() {
		const { copilotkit } = useCopilotKit();
		const { setBannerError } = useToast();
		const hasAgents = Object.keys(copilotkit.agents ?? {}).length > 0;
		const hasRuntime = copilotkit.runtimeUrl !== void 0;
		(0, react.useEffect)(() => {
			const subscription = copilotkit.subscribe({ onError: ({ error, code, context }) => {
				if (error.name === "AbortError" || error.message === "Fetch is aborted" || error.message === "signal is aborted without reason" || error.message === "component unmounted" || !error.message) return;
				if (process.env.NODE_ENV === "development") console.error("[CopilotKit] Agent error:", error.message, "\n  Code:", code, "\n  Context:", context, "\n  Stack:", error.stack);
				const ckError = new _copilotkit_shared.CopilotKitLowLevelError({
					error,
					message: error.message,
					url: typeof window !== "undefined" ? window.location.href : ""
				});
				ckError.details = {
					code,
					context,
					stack: error.stack,
					originalMessage: error.message
				};
				setBannerError(ckError);
			} });
			return () => {
				subscription.unsubscribe();
			};
		}, [copilotkit?.subscribe]);
		return hasAgents || hasRuntime ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotListenersAgentSubscription, {}) : null;
	}

//#endregion
//#region src/components/copilot-provider/copilotkit.tsx
	function CopilotKit({ children, ...props }) {
		const enabled = shouldShowDevConsole(props.showDevConsole);
		const showInspector = shouldShowDevConsole(props.enableInspector);
		const publicApiKey = props.publicApiKey || props.publicLicenseKey;
		const renderArr = (0, react.useMemo)(() => [{ render: CoAgentStateRenderBridge }], []);
		const { onError: _onError, ...v2Props } = props;
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToastProvider, {
			enabled,
			children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotErrorBoundary, {
				publicApiKey,
				showUsageBanner: enabled,
				children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ThreadsProvider, {
					threadId: props.threadId,
					children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitProvider, {
						...v2Props,
						showDevConsole: showInspector,
						renderCustomMessages: renderArr,
						useSingleEndpoint: props.useSingleEndpoint ?? true,
						children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitInternal, {
							...props,
							children
						})
					})
				})
			})
		});
	}
	/**
	* Bridge component that subscribes to v2.x copilotkit core error events
	* and forwards them to v1.x error handling system.
	* This ensures only ONE subscription exists regardless of how many times
	* Chat components are rendered.
	*/
	function CopilotKitErrorBridge() {
		const { copilotkit } = useCopilotKit();
		const { onError, copilotApiConfig } = useCopilotContext();
		(0, react.useEffect)(() => {
			if (!copilotkit) return;
			const subscription = copilotkit.subscribe({ onError: async (event) => {
				const errorEvent = {
					type: "error",
					timestamp: Date.now(),
					context: {
						source: "agent",
						request: {
							operation: event.code || "unknown",
							url: copilotApiConfig?.chatApiEndpoint,
							startTime: Date.now()
						},
						technical: {
							environment: "browser",
							userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
							stackTrace: event.error.stack
						},
						...event.context
					},
					error: event.error
				};
				try {
					await onError(errorEvent);
				} catch (handlerError) {
					console.error("Error in onError handler:", handlerError);
				}
			} });
			return () => {
				subscription.unsubscribe();
			};
		}, [
			copilotkit,
			onError,
			copilotApiConfig
		]);
		return null;
	}
	function CopilotKitInternal(cpkProps) {
		const { children, ...props } = cpkProps;
		/**
		* This will throw an error if the props are invalid.
		*/
		validateProps(cpkProps);
		const publicApiKey = props.publicLicenseKey || props.publicApiKey;
		const chatApiEndpoint = props.runtimeUrl || _copilotkit_shared.COPILOT_CLOUD_CHAT_URL;
		const [actions, setActions] = (0, react.useState)({});
		const [registeredActionConfigs, setRegisteredActionConfigs] = (0, react.useState)(/* @__PURE__ */ new Map());
		const chatComponentsCache = (0, react.useRef)({
			actions: {},
			coAgentStateRenders: {}
		});
		const { addElement, removeElement, printTree, getAllElements } = useTree();
		const [isLoading, setIsLoading] = (0, react.useState)(false);
		const [chatInstructions, setChatInstructions] = (0, react.useState)("");
		const [authStates, setAuthStates] = (0, react.useState)({});
		const [extensions, setExtensions] = (0, react.useState)({});
		const [additionalInstructions, setAdditionalInstructions] = (0, react.useState)([]);
		const { addElement: addDocument, removeElement: removeDocument, allElements: allDocuments } = useFlatCategoryStore();
		const setAction = (0, react.useCallback)((id, action) => {
			setActions((prevPoints) => {
				return {
					...prevPoints,
					[id]: action
				};
			});
		}, []);
		const removeAction = (0, react.useCallback)((id) => {
			setActions((prevPoints) => {
				const newPoints = { ...prevPoints };
				delete newPoints[id];
				return newPoints;
			});
		}, []);
		const getContextString = (0, react.useCallback)((documents, categories) => {
			return `${documents.map((document) => {
				return `${document.name} (${document.sourceApplication}):\n${document.getContents()}`;
			}).join("\n\n")}\n\n${printTree(categories)}`;
		}, [printTree]);
		const addContext = (0, react.useCallback)((context, parentId, categories = defaultCopilotContextCategories) => {
			return addElement(context, categories, parentId);
		}, [addElement]);
		const removeContext = (0, react.useCallback)((id) => {
			removeElement(id);
		}, [removeElement]);
		const getAllContext = (0, react.useCallback)(() => {
			return getAllElements();
		}, [getAllElements]);
		const getFunctionCallHandler = (0, react.useCallback)((customEntryPoints) => {
			return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
		}, [actions]);
		const getDocumentsContext = (0, react.useCallback)((categories) => {
			return allDocuments(categories);
		}, [allDocuments]);
		const addDocumentContext = (0, react.useCallback)((documentPointer, categories = defaultCopilotContextCategories) => {
			return addDocument(documentPointer, categories);
		}, [addDocument]);
		const removeDocumentContext = (0, react.useCallback)((documentId) => {
			removeDocument(documentId);
		}, [removeDocument]);
		const copilotApiConfig = (0, react.useMemo)(() => {
			let cloud = void 0;
			if (publicApiKey) cloud = { guardrails: { input: { restrictToTopic: {
				enabled: Boolean(props.guardrails_c),
				validTopics: props.guardrails_c?.validTopics || [],
				invalidTopics: props.guardrails_c?.invalidTopics || []
			} } } };
			return {
				publicApiKey,
				...cloud ? { cloud } : {},
				chatApiEndpoint,
				headers: typeof props.headers === "function" ? props.headers() : props.headers || {},
				properties: props.properties || {},
				transcribeAudioUrl: props.transcribeAudioUrl,
				textToSpeechUrl: props.textToSpeechUrl,
				credentials: props.credentials
			};
		}, [
			publicApiKey,
			props.headers,
			props.properties,
			props.transcribeAudioUrl,
			props.textToSpeechUrl,
			props.credentials,
			props.cloudRestrictToTopic,
			props.guardrails_c
		]);
		(0, react.useMemo)(() => {
			const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {
				if (state.status === "authenticated" && state.authHeaders) return {
					...acc,
					...Object.entries(state.authHeaders).reduce((headers, [key, value]) => ({
						...headers,
						[key.startsWith("X-Custom-") ? key : `X-Custom-${key}`]: value
					}), {})
				};
				return acc;
			}, {});
			return {
				...copilotApiConfig.headers,
				...copilotApiConfig.publicApiKey ? { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {},
				...authHeaders
			};
		}, [
			copilotApiConfig.headers,
			copilotApiConfig.publicApiKey,
			authStates
		]);
		const [internalErrorHandlers, _setInternalErrorHandler] = (0, react.useState)({});
		const setInternalErrorHandler = (0, react.useCallback)((handler) => {
			_setInternalErrorHandler((prev) => ({
				...prev,
				...handler
			}));
		}, []);
		const removeInternalErrorHandler = (0, react.useCallback)((key) => {
			_setInternalErrorHandler((prev) => {
				const { [key]: _removed, ...rest } = prev;
				return rest;
			});
		}, []);
		const onErrorRef = (0, react.useRef)(props.onError);
		(0, react.useEffect)(() => {
			onErrorRef.current = props.onError;
		}, [props.onError]);
		const internalHandlersRef = (0, react.useRef)({});
		(0, react.useEffect)(() => {
			internalHandlersRef.current = internalErrorHandlers;
		}, [internalErrorHandlers]);
		const handleErrors = (0, react.useCallback)(async (error) => {
			if (copilotApiConfig.publicApiKey && onErrorRef.current) try {
				await onErrorRef.current(error);
			} catch (e) {
				console.error("Error in public onError handler:", e);
			}
			const handlers = Object.values(internalHandlersRef.current);
			await Promise.all(handlers.map((h) => Promise.resolve(h(error)).catch((e) => console.error("Error in internal error handler:", e))));
		}, [copilotApiConfig.publicApiKey]);
		const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, react.useState)({});
		const addChatSuggestionConfiguration = (0, react.useCallback)((id, suggestion) => {
			setChatSuggestionConfiguration((prev) => ({
				...prev,
				[id]: suggestion
			}));
		}, [setChatSuggestionConfiguration]);
		const removeChatSuggestionConfiguration = (0, react.useCallback)((id) => {
			setChatSuggestionConfiguration((prev) => {
				const { [id]: _, ...rest } = prev;
				return rest;
			});
		}, [setChatSuggestionConfiguration]);
		const [availableAgents, setAvailableAgents] = (0, react.useState)([]);
		const [coagentStates, setCoagentStates] = (0, react.useState)({});
		const coagentStatesRef = (0, react.useRef)({});
		const setCoagentStatesWithRef = (0, react.useCallback)((value) => {
			const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value;
			coagentStatesRef.current = newValue;
			setCoagentStates((prev) => {
				return newValue;
			});
		}, []);
		let initialAgentSession = null;
		if (props.agent) initialAgentSession = { agentName: props.agent };
		const [agentSession, setAgentSession] = (0, react.useState)(initialAgentSession);
		(0, react.useEffect)(() => {
			if (props.agent) setAgentSession({ agentName: props.agent });
			else setAgentSession(null);
		}, [props.agent]);
		const { threadId, setThreadId: setInternalThreadId, isThreadIdExplicit } = useThreads();
		const setThreadId = (0, react.useCallback)((value) => {
			if (props.threadId) throw new Error("Cannot call setThreadId() when threadId is provided via props.");
			setInternalThreadId(value);
		}, [props.threadId]);
		const [runId, setRunId] = (0, react.useState)(null);
		const chatAbortControllerRef = (0, react.useRef)(null);
		const showDevConsole = shouldShowDevConsole(props.showDevConsole);
		const [interruptActions, _setInterruptActions] = (0, react.useState)({});
		const setInterruptAction = (0, react.useCallback)((action) => {
			_setInterruptActions((prev) => {
				if (action == null || !action.id) return prev;
				return {
					...prev,
					[action.id]: {
						...prev[action.id],
						...action
					}
				};
			});
		}, []);
		const removeInterruptAction = (0, react.useCallback)((actionId) => {
			_setInterruptActions((prev) => {
				const { [actionId]: _, ...rest } = prev;
				return rest;
			});
		}, []);
		const [interruptEventQueue, setInterruptEventQueue] = (0, react.useState)({});
		const addInterruptEvent = (0, react.useCallback)((queuedEvent) => {
			setInterruptEventQueue((prev) => {
				const threadQueue = prev[queuedEvent.threadId] || [];
				return {
					...prev,
					[queuedEvent.threadId]: [...threadQueue, queuedEvent]
				};
			});
		}, []);
		const resolveInterruptEvent = (0, react.useCallback)((threadId, eventId, response) => {
			setInterruptEventQueue((prev) => {
				const threadQueue = prev[threadId] || [];
				return {
					...prev,
					[threadId]: threadQueue.map((queuedEvent) => queuedEvent.eventId === eventId ? {
						...queuedEvent,
						event: {
							...queuedEvent.event,
							response
						}
					} : queuedEvent)
				};
			});
		}, []);
		const memoizedChildren = (0, react.useMemo)(() => children, [children]);
		const [bannerError, setBannerError] = (0, react.useState)(null);
		const agentLock = (0, react.useMemo)(() => props.agent ?? null, [props.agent]);
		const forwardedParameters = (0, react.useMemo)(() => props.forwardedParameters ?? {}, [props.forwardedParameters]);
		const updateExtensions = (0, react.useCallback)((newExtensions) => {
			setExtensions((prev) => {
				const resolved = typeof newExtensions === "function" ? newExtensions(prev) : newExtensions;
				return Object.keys(resolved).length === Object.keys(prev).length && Object.entries(resolved).every(([key, value]) => prev[key] === value) ? prev : resolved;
			});
		}, [setExtensions]);
		const updateAuthStates = (0, react.useCallback)((newAuthStates) => {
			setAuthStates((prev) => {
				const resolved = typeof newAuthStates === "function" ? newAuthStates(prev) : newAuthStates;
				return Object.keys(resolved).length === Object.keys(prev).length && Object.entries(resolved).every(([key, value]) => prev[key] === value) ? prev : resolved;
			});
		}, [setAuthStates]);
		const handleSetRegisteredActions = (0, react.useCallback)((actionConfig) => {
			const key = actionConfig.action.name || (0, _copilotkit_shared.randomUUID)();
			setRegisteredActionConfigs((prev) => {
				const newMap = new Map(prev);
				newMap.set(key, actionConfig);
				return newMap;
			});
			return key;
		}, []);
		const handleRemoveRegisteredAction = (0, react.useCallback)((actionKey) => {
			setRegisteredActionConfigs((prev) => {
				const newMap = new Map(prev);
				newMap.delete(actionKey);
				return newMap;
			});
		}, []);
		const RegisteredActionsRenderer = (0, react.useMemo)(() => {
			return () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: Array.from(registeredActionConfigs.entries()).map(([key, config]) => {
				const Component = config.component;
				return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Component, { action: config.action }, key);
			}) });
		}, [registeredActionConfigs]);
		const copilotContextValue = (0, react.useMemo)(() => ({
			actions,
			chatComponentsCache,
			getFunctionCallHandler,
			setAction,
			removeAction,
			setRegisteredActions: handleSetRegisteredActions,
			removeRegisteredAction: handleRemoveRegisteredAction,
			getContextString,
			addContext,
			removeContext,
			getAllContext,
			getDocumentsContext,
			addDocumentContext,
			removeDocumentContext,
			copilotApiConfig,
			isLoading,
			setIsLoading,
			chatSuggestionConfiguration,
			addChatSuggestionConfiguration,
			removeChatSuggestionConfiguration,
			chatInstructions,
			setChatInstructions,
			additionalInstructions,
			setAdditionalInstructions,
			showDevConsole,
			coagentStates,
			setCoagentStates,
			coagentStatesRef,
			setCoagentStatesWithRef,
			agentSession,
			setAgentSession,
			forwardedParameters,
			agentLock,
			threadId,
			setThreadId,
			runId,
			setRunId,
			chatAbortControllerRef,
			availableAgents,
			authConfig_c: props.authConfig_c,
			authStates_c: authStates,
			setAuthStates_c: updateAuthStates,
			extensions,
			setExtensions: updateExtensions,
			interruptActions,
			setInterruptAction,
			removeInterruptAction,
			interruptEventQueue,
			addInterruptEvent,
			resolveInterruptEvent,
			bannerError,
			setBannerError,
			onError: handleErrors,
			internalErrorHandlers,
			setInternalErrorHandler,
			removeInternalErrorHandler
		}), [
			actions,
			chatComponentsCache,
			getFunctionCallHandler,
			setAction,
			removeAction,
			handleSetRegisteredActions,
			handleRemoveRegisteredAction,
			getContextString,
			addContext,
			removeContext,
			getAllContext,
			getDocumentsContext,
			addDocumentContext,
			removeDocumentContext,
			copilotApiConfig,
			isLoading,
			chatSuggestionConfiguration,
			addChatSuggestionConfiguration,
			removeChatSuggestionConfiguration,
			chatInstructions,
			additionalInstructions,
			showDevConsole,
			coagentStates,
			setCoagentStatesWithRef,
			agentSession,
			setAgentSession,
			forwardedParameters,
			agentLock,
			threadId,
			setThreadId,
			runId,
			availableAgents,
			props.authConfig_c,
			authStates,
			updateAuthStates,
			extensions,
			updateExtensions,
			interruptActions,
			setInterruptAction,
			removeInterruptAction,
			interruptEventQueue,
			addInterruptEvent,
			resolveInterruptEvent,
			bannerError,
			handleErrors,
			internalErrorHandlers,
			setInternalErrorHandler,
			removeInternalErrorHandler
		]);
		return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfigurationProvider, {
			agentId: props.agent ?? "default",
			threadId,
			hasExplicitThreadId: isThreadIdExplicit,
			children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotContext.Provider, {
				value: copilotContextValue,
				children: [
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotListeners, {}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitErrorBridge, {}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CoAgentStateRendersProvider, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessagesTapProvider, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotMessages, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.default.Fragment, { children: memoizedChildren }, "children"), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RegisteredActionsRenderer, {}, "actions")] }) }), bannerError && showDevConsole && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UsageBanner, {
						severity: bannerError.severity,
						message: bannerError.message,
						onClose: () => setBannerError(null),
						actions: getErrorActions(bannerError)
					})] })
				]
			})
		});
	}
	const defaultCopilotContextCategories = ["global"];
	function entryPointsToFunctionCallHandler(actions) {
		return async ({ name, args }) => {
			let actionsByFunctionName = {};
			for (let action of actions) actionsByFunctionName[action.name] = action;
			const action = actionsByFunctionName[name];
			let result = void 0;
			if (action) {
				await new Promise((resolve, reject) => {
					(0, react_dom.flushSync)(async () => {
						try {
							result = await action.handler?.(args);
							resolve();
						} catch (error) {
							reject(error);
						}
					});
				});
				await new Promise((resolve) => setTimeout(resolve, 20));
			}
			return result;
		};
	}
	function formatFeatureName(featureName) {
		return featureName.replace(/_c$/, "").split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
	}
	function validateProps(props) {
		const cloudFeatures = Object.keys(props).filter((key) => key.endsWith("_c"));
		const hasApiKey = props.publicApiKey || props.publicLicenseKey;
		const hasLocalAgents = Object.keys({
			...props.agents__unsafe_dev_only,
			...props.selfManagedAgents
		}).length > 0;
		if (!props.runtimeUrl && !hasApiKey && !hasLocalAgents) throw new _copilotkit_shared.ConfigurationError("Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'");
		if (cloudFeatures.length > 0 && !hasApiKey) throw new _copilotkit_shared.MissingPublicApiKeyError(`Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures.map(formatFeatureName).join(", ")}`);
	}

//#endregion
//#region src/hooks/use-lazy-tool-renderer.tsx
	function useLazyToolRenderer() {
		const renderToolCall = useRenderToolCall$1();
		return (0, react.useCallback)((message, messages) => {
			if (!message?.toolCalls?.length) return null;
			const toolCall = message.toolCalls[0];
			if (!toolCall) return null;
			const toolMessage = messages?.find((m) => m.role === "tool" && m.toolCallId === toolCall.id);
			return () => renderToolCall({
				toolCall,
				toolMessage
			});
		}, [renderToolCall]);
	}

//#endregion
//#region src/hooks/use-copilot-chat_internal.ts
	function useCopilotChatInternal({ suggestions, onInProgress, onSubmitMessage, onStopGeneration, onReloadMessages } = {}) {
		const { copilotkit } = useCopilotKit();
		const { threadId, agentSession } = useCopilotContext();
		const existingConfig = useCopilotChatConfiguration();
		const [agentAvailable, setAgentAvailable] = (0, react.useState)(false);
		const resolvedAgentId = existingConfig?.agentId ?? "default";
		const { agent } = useAgent({ agentId: resolvedAgentId });
		const lastConnectedAgentRef = (0, react.useRef)(null);
		(0, react.useEffect)(() => {
			let detached = false;
			const connectAbortController = new AbortController();
			if (agent instanceof _ag_ui_client.HttpAgent) agent.abortController = connectAbortController;
			const connect = async (agent) => {
				setAgentAvailable(false);
				try {
					await copilotkit.connectAgent({ agent });
					if (!detached) setAgentAvailable(true);
				} catch (error) {
					if (detached) return;
					if (error instanceof _ag_ui_client.AGUIConnectNotImplementedError) {} else console.error("CopilotChat: connectAgent failed", error);
				}
			};
			if (agent && agent !== lastConnectedAgentRef.current && copilotkit.runtimeConnectionStatus === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connected) {
				lastConnectedAgentRef.current = agent;
				connect(agent);
			}
			return () => {
				lastConnectedAgentRef.current = null;
				detached = true;
				connectAbortController.abort();
				agent?.detachActiveRun();
			};
		}, [
			existingConfig?.threadId,
			agent,
			copilotkit,
			copilotkit.runtimeConnectionStatus,
			resolvedAgentId
		]);
		(0, react.useEffect)(() => {
			onInProgress?.(Boolean(agent?.isRunning));
		}, [agent?.isRunning, onInProgress]);
		const [interrupt, setInterrupt] = (0, react.useState)(null);
		(0, react.useEffect)(() => {
			setInterrupt(copilotkit.interruptElement);
			const subscription = copilotkit.subscribe({ onInterruptElementChanged: ({ interruptElement }) => {
				setInterrupt(interruptElement);
			} });
			return () => subscription.unsubscribe();
		}, [copilotkit]);
		const reset = () => {
			agent?.setMessages([]);
			agent?.setState(null);
		};
		const latestDelete = useUpdatedRef((0, react.useCallback)((messageId) => {
			const filteredMessages = (agent?.messages ?? []).filter((message) => message.id !== messageId);
			agent?.setMessages(filteredMessages);
		}, [agent?.setMessages, agent?.messages]));
		const latestDeleteFunc = (0, react.useCallback)((messageId) => {
			return latestDelete.current(messageId);
		}, [latestDelete]);
		const currentSuggestions = useSuggestions({ agentId: resolvedAgentId });
		const reload = useAsyncCallback(async (reloadMessageId) => {
			if (!agent) return;
			const messages = agent?.messages ?? [];
			if (agent.isRunning || messages.length === 0) return;
			const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
			if (reloadMessageIndex === -1) {
				console.warn(`Message with id ${reloadMessageId} not found`);
				return;
			}
			const reloadMessageRole = messages[reloadMessageIndex].role;
			if (reloadMessageRole !== "assistant") {
				console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
				return;
			}
			let historyCutoff = [messages[0]];
			if (messages.length > 2 && reloadMessageIndex !== 0) {
				const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).toReversed().find((msg) => msg.role === "user");
				if (!lastUserMessageBeforeRegenerate) historyCutoff = [messages[0]];
				else {
					const indexOfLastUserMessageBeforeRegenerate = messages.findIndex((msg) => msg.id === lastUserMessageBeforeRegenerate.id);
					historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
				}
			} else if (messages.length > 2 && reloadMessageIndex === 0) historyCutoff = [messages[0], messages[1]];
			agent?.setMessages(historyCutoff);
			if (agent) try {
				await copilotkit.runAgent({ agent });
			} catch (error) {
				console.error("CopilotChat: runAgent failed during reload", error);
			}
		}, [
			agent?.messages.length,
			agent?.isRunning,
			agent?.setMessages,
			copilotkit?.runAgent
		]);
		const latestSendMessageFunc = useAsyncCallback(async (message, options) => {
			if (!agent) return;
			const followUp = options?.followUp ?? true;
			if (options?.clearSuggestions) copilotkit.clearSuggestions(resolvedAgentId);
			if (onSubmitMessage) {
				const content = typeof message.content === "string" ? message.content : message.content && "text" in message.content ? message.content.text : message.content && "filename" in message.content ? message.content.filename : "";
				try {
					await onSubmitMessage(content);
				} catch (error) {
					console.error("Error in onSubmitMessage:", error);
				}
			}
			agent?.addMessage(message);
			if (followUp) try {
				await copilotkit.runAgent({ agent });
			} catch (error) {
				console.error("CopilotChat: runAgent failed", error);
			}
		}, [
			agent,
			copilotkit,
			resolvedAgentId,
			onSubmitMessage
		]);
		const latestAppendFunc = useAsyncCallback(async (message, options) => {
			return latestSendMessageFunc((0, _copilotkit_runtime_client_gql.gqlToAGUI)([message])[0], options);
		}, [latestSendMessageFunc]);
		const latestSetMessagesFunc = (0, react.useCallback)((messages) => {
			if (messages.every((message) => message instanceof _copilotkit_runtime_client_gql.Message)) return agent?.setMessages?.((0, _copilotkit_runtime_client_gql.gqlToAGUI)(messages));
			return agent?.setMessages?.(messages);
		}, [agent?.setMessages, agent]);
		const latestReload = useUpdatedRef(reload);
		const latestReloadFunc = useAsyncCallback(async (messageId) => {
			onReloadMessages?.({
				messageId,
				currentAgentName: agent?.agentId,
				messages: agent?.messages ?? []
			});
			return await latestReload.current(messageId);
		}, [
			latestReload,
			agent,
			onReloadMessages
		]);
		const latestStopFunc = (0, react.useCallback)(() => {
			onStopGeneration?.({
				currentAgentName: agent?.agentId,
				messages: agent?.messages ?? []
			});
			return agent?.abortRun?.();
		}, [onStopGeneration, agent]);
		const latestReset = useUpdatedRef(reset);
		const latestResetFunc = (0, react.useCallback)(() => {
			return latestReset.current();
		}, [latestReset]);
		const lazyToolRendered = useLazyToolRenderer();
		const renderCustomMessage = useRenderCustomMessages();
		const legacyCustomMessageRenderer = useLegacyCoagentRenderer({
			copilotkit,
			agent,
			agentId: resolvedAgentId,
			threadId: existingConfig?.threadId ?? threadId
		});
		const allMessages = agent?.messages ?? [];
		const resolvedMessages = (0, react.useMemo)(() => {
			let processedMessages = allMessages.map((message) => {
				if (message.role !== "assistant") return message;
				const lazyRendered = lazyToolRendered(message, allMessages);
				if (lazyRendered) {
					const renderedGenUi = lazyRendered();
					if (renderedGenUi) return {
						...message,
						generativeUI: () => renderedGenUi
					};
				}
				const bridgeRenderer = legacyCustomMessageRenderer || renderCustomMessage ? () => {
					if (legacyCustomMessageRenderer) return legacyCustomMessageRenderer({
						message,
						position: "before"
					});
					try {
						return renderCustomMessage?.({
							message,
							position: "before"
						}) ?? null;
					} catch (error) {
						console.warn("[CopilotKit] renderCustomMessages failed, falling back to legacy renderer", error);
						return null;
					}
				} : null;
				if (bridgeRenderer) return {
					...message,
					generativeUI: bridgeRenderer,
					generativeUIPosition: "before"
				};
				return message;
			});
			const hasAssistantMessages = processedMessages.some((msg) => msg.role === "assistant");
			const canUseCustomRenderer = Boolean(renderCustomMessage && copilotkit?.getAgent?.(resolvedAgentId));
			const placeholderRenderer = legacyCustomMessageRenderer ? legacyCustomMessageRenderer : canUseCustomRenderer ? renderCustomMessage : null;
			const shouldRenderPlaceholder = Boolean(agent?.isRunning) || Boolean(agent?.state && Object.keys(agent.state).length);
			const effectiveThreadId = threadId ?? agent?.threadId ?? "default";
			let latestUserIndex = -1;
			for (let i = processedMessages.length - 1; i >= 0; i -= 1) if (processedMessages[i].role === "user") {
				latestUserIndex = i;
				break;
			}
			const latestUserMessageId = latestUserIndex >= 0 ? processedMessages[latestUserIndex].id : void 0;
			const currentRunId = latestUserMessageId ? copilotkit.getRunIdForMessage(resolvedAgentId, effectiveThreadId, latestUserMessageId) || `pending:${latestUserMessageId}` : void 0;
			const hasAssistantForCurrentRun = latestUserIndex >= 0 ? processedMessages.slice(latestUserIndex + 1).some((msg) => msg.role === "assistant") : hasAssistantMessages;
			if (placeholderRenderer && shouldRenderPlaceholder && !hasAssistantForCurrentRun) {
				const placeholderMessage = {
					id: currentRunId ? `coagent-state-render-${resolvedAgentId}-${currentRunId}` : `coagent-state-render-${resolvedAgentId}`,
					role: "assistant",
					content: "",
					name: "coagent-state-render",
					runId: currentRunId
				};
				processedMessages = [...processedMessages, {
					...placeholderMessage,
					generativeUIPosition: "before",
					generativeUI: () => placeholderRenderer({
						message: placeholderMessage,
						position: "before"
					})
				}];
			}
			return processedMessages;
		}, [
			agent?.messages,
			lazyToolRendered,
			allMessages,
			renderCustomMessage,
			legacyCustomMessageRenderer,
			resolvedAgentId,
			copilotkit,
			agent?.isRunning,
			agent?.state
		]);
		const renderedSuggestions = (0, react.useMemo)(() => {
			if (Array.isArray(suggestions)) return {
				suggestions: suggestions.map((s) => ({
					...s,
					isLoading: false
				})),
				isLoading: false
			};
			return currentSuggestions;
		}, [suggestions, currentSuggestions]);
		return {
			messages: resolvedMessages,
			sendMessage: latestSendMessageFunc,
			appendMessage: latestAppendFunc,
			setMessages: latestSetMessagesFunc,
			reloadMessages: latestReloadFunc,
			stopGeneration: latestStopFunc,
			reset: latestResetFunc,
			deleteMessage: latestDeleteFunc,
			isAvailable: agentAvailable,
			isLoading: Boolean(agent?.isRunning),
			suggestions: renderedSuggestions.suggestions,
			setSuggestions: (suggestions) => copilotkit.addSuggestionsConfig({ suggestions }),
			generateSuggestions: async () => copilotkit.reloadSuggestions(resolvedAgentId),
			resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),
			isLoadingSuggestions: renderedSuggestions.isLoading,
			interrupt,
			agent,
			threadId
		};
	}
	function useUpdatedRef(value) {
		const ref = (0, react.useRef)(value);
		(0, react.useEffect)(() => {
			ref.current = value;
		}, [value]);
		return ref;
	}
	function useLegacyCoagentRenderer({ copilotkit, agent, agentId, threadId }) {
		return (0, react.useMemo)(() => {
			if (!copilotkit || !agent) return null;
			return ({ message, position }) => {
				const effectiveThreadId = threadId ?? agent.threadId ?? "default";
				const providedRunId = message.runId;
				return (0, react.createElement)(CoAgentStateRenderBridge, {
					message,
					position,
					runId: (providedRunId ? providedRunId : copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id)) || `pending:${message.id}`,
					messageIndex: Math.max(agent.messages.findIndex((msg) => msg.id === message.id), 0),
					messageIndexInRun: 0,
					numberOfMessagesInRun: 1,
					agentId,
					stateSnapshot: message.state
				});
			};
		}, [
			agent,
			agentId,
			copilotkit,
			threadId
		]);
	}

//#endregion
//#region src/hooks/use-copilot-chat.ts
/**
	* A lightweight React hook for headless chat interactions.
	* Perfect for programmatic messaging, background operations, and custom UI implementations.
	*
	* **Open Source Friendly** - Works without requiring a `publicApiKey`.
	*/
	function useCopilotChat(options = {}) {
		const { visibleMessages, appendMessage, reloadMessages, stopGeneration, reset, isLoading, isAvailable, runChatCompletion, mcpServers, setMcpServers } = useCopilotChatInternal(options);
		return {
			visibleMessages,
			appendMessage,
			reloadMessages,
			stopGeneration,
			reset,
			isLoading,
			isAvailable,
			runChatCompletion,
			mcpServers,
			setMcpServers
		};
	}

//#endregion
//#region src/hooks/use-copilot-chat-headless_c.ts
/**
	* `useCopilotChatHeadless_c` is for building fully custom UI (headless UI) implementations.
	*
	* <Callout title="This is an Enterprise Intelligence Platform feature">
	* Read more about <a href="/premium/overview">the Enterprise Intelligence Platform</a>.
	*
	* Usage is generous and **free** to get started.
	* </Callout>
	*
	* ## Key Features
	*
	* - **Fully headless**: Build your own fully custom UI's for your agentic applications.
	* - **Advanced Suggestions**: Direct access to suggestions array with full control
	* - **Interrupt Handling**: Support for advanced interrupt functionality
	* - **MCP Server Support**: Model Context Protocol server configurations
	* - **Chat Controls**: Complete set of chat management functions
	* - **Loading States**: Comprehensive loading state management
	*
	*
	* ## Usage
	*
	* ### Basic Setup
	*
	* ```tsx
	* import { CopilotKit } from "@copilotkit/react-core";
	* import { useCopilotChatHeadless_c } from "@copilotkit/react-core";
	*
	* export function App() {
	*   return (
	*     <CopilotKit runtimeUrl="/api/copilotkit">
	*       <YourComponent />
	*     </CopilotKit>
	*   );
	* }
	*
	* export function YourComponent() {
	*   const { messages, sendMessage, isLoading } = useCopilotChatHeadless_c();
	*
	*   const handleSendMessage = async () => {
	*     await sendMessage({
	*       id: "123",
	*       role: "user",
	*       content: "Hello World",
	*     });
	*   };
	*
	*   return (
	*     <div>
	*       {messages.map(msg => <div key={msg.id}>{msg.content}</div>)}
	*       <button onClick={handleSendMessage} disabled={isLoading}>
	*         Send Message
	*       </button>
	*     </div>
	*   );
	* }
	* ```
	*
	* ### Working with Suggestions
	*
	* ```tsx
	* import { useCopilotChatHeadless_c, useCopilotChatSuggestions } from "@copilotkit/react-core";
	*
	* export function SuggestionExample() {
	*   const {
	*     suggestions,
	*     setSuggestions,
	*     generateSuggestions,
	*     isLoadingSuggestions
	*   } = useCopilotChatHeadless_c();
	*
	*   // Configure AI suggestion generation
	*   useCopilotChatSuggestions({
	*     instructions: "Suggest helpful actions based on the current context",
	*     maxSuggestions: 3
	*   });
	*
	*   return (
	*     <div>
	*       {suggestions.map(suggestion => (
	*         <button key={suggestion.title}>{suggestion.title}</button>
	*       ))}
	*       <button onClick={generateSuggestions} disabled={isLoadingSuggestions}>
	*         Generate Suggestions
	*       </button>
	*     </div>
	*   );
	* }
	* ```
	*
	* ## Return Values
	* The following properties are returned from the hook:
	*
	* <PropertyReference name="messages" type="Message[]">
	* The messages currently in the chat in AG-UI format
	* </PropertyReference>
	*
	* <PropertyReference name="sendMessage" type="(message: Message, options?) => Promise<void>">
	* Send a new message to the chat and trigger AI response
	* </PropertyReference>
	*
	* <PropertyReference name="setMessages" type="(messages: Message[] | DeprecatedGqlMessage[]) => void">
	* Replace all messages in the chat with new array
	* </PropertyReference>
	*
	* <PropertyReference name="deleteMessage" type="(messageId: string) => void">
	* Remove a specific message by ID from the chat
	* </PropertyReference>
	*
	* <PropertyReference name="reloadMessages" type="(messageId: string) => Promise<void>">
	* Regenerate the response for a specific message by ID
	* </PropertyReference>
	*
	* <PropertyReference name="stopGeneration" type="() => void">
	* Stop the current message generation process
	* </PropertyReference>
	*
	* <PropertyReference name="reset" type="() => void">
	* Clear all messages and reset chat state completely
	* </PropertyReference>
	*
	* <PropertyReference name="isLoading" type="boolean">
	* Whether the chat is currently generating a response
	* </PropertyReference>
	*
	* <PropertyReference name="runChatCompletion" type="() => Promise<Message[]>">
	* Manually trigger chat completion for advanced usage
	* </PropertyReference>
	*
	* <PropertyReference name="mcpServers" type="MCPServerConfig[]">
	* Array of Model Context Protocol server configurations
	* </PropertyReference>
	*
	* <PropertyReference name="setMcpServers" type="(servers: MCPServerConfig[]) => void">
	* Update MCP server configurations for enhanced context
	* </PropertyReference>
	*
	* <PropertyReference name="suggestions" type="SuggestionItem[]">
	* Current suggestions array for reading or manual control
	* </PropertyReference>
	*
	* <PropertyReference name="setSuggestions" type="(suggestions: SuggestionItem[]) => void">
	* Manually set suggestions for custom workflows
	* </PropertyReference>
	*
	* <PropertyReference name="generateSuggestions" type="() => Promise<void>">
	* Trigger AI-powered suggestion generation using configured settings
	* </PropertyReference>
	*
	* <PropertyReference name="resetSuggestions" type="() => void">
	* Clear all current suggestions and reset generation state
	* </PropertyReference>
	*
	* <PropertyReference name="isLoadingSuggestions" type="boolean">
	* Whether suggestions are currently being generated
	* </PropertyReference>
	*
	* <PropertyReference name="interrupt" type="string | React.ReactElement | null">
	* Interrupt content for human-in-the-loop workflows
	* </PropertyReference>
	*/
	const createNonFunctionalReturn = () => ({
		visibleMessages: [],
		messages: [],
		sendMessage: async () => {},
		appendMessage: async () => {},
		setMessages: () => {},
		deleteMessage: () => {},
		reloadMessages: async () => {},
		stopGeneration: () => {},
		reset: () => {},
		isLoading: false,
		isAvailable: false,
		runChatCompletion: async () => [],
		mcpServers: [],
		setMcpServers: () => {},
		suggestions: [],
		setSuggestions: () => {},
		generateSuggestions: async () => {},
		resetSuggestions: () => {},
		isLoadingSuggestions: false,
		interrupt: null
	});
	/**
	* Enterprise Intelligence Platform React hook that provides complete chat functionality for fully custom UI implementations.
	* Includes all advanced features like direct message access, suggestions array, interrupt handling, and MCP support.
	*
	* @param options - Configuration options for the chat
	* @returns Complete chat interface with all Enterprise Intelligence Platform features
	*
	* @example
	* ```tsx
	* const { messages, sendMessage, suggestions, interrupt } = useCopilotChatHeadless_c();
	* ```
	*/
	function useCopilotChatHeadless_c(options = {}) {
		const { copilotApiConfig, setBannerError } = useCopilotContext();
		const hasPublicApiKey = Boolean(copilotApiConfig.publicApiKey);
		const internalResult = useCopilotChatInternal(options);
		(0, react.useEffect)(() => {
			if (!hasPublicApiKey) {
				setBannerError(new _copilotkit_shared.CopilotKitError({
					message: "You're using useCopilotChatHeadless_c, an Enterprise Intelligence Platform feature that offers extensive headless chat capabilities. To continue, you'll need to provide a free public license key.",
					code: _copilotkit_shared.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
					severity: _copilotkit_shared.Severity.WARNING,
					visibility: _copilotkit_shared.ErrorVisibility.BANNER
				}));
				_copilotkit_shared.styledConsole.logCopilotKitPlatformMessage();
			} else setBannerError(null);
		}, [hasPublicApiKey]);
		if (hasPublicApiKey) return internalResult;
		return createNonFunctionalReturn();
	}

//#endregion
//#region src/hooks/use-frontend-tool.ts
	function useFrontendTool(tool, dependencies) {
		const { name, description, parameters, render, followUp, available } = tool;
		const zodParameters = (0, _copilotkit_shared.getZodParameters)(parameters);
		const renderRef = (0, react.useRef)(render);
		(0, react.useEffect)(() => {
			renderRef.current = render;
		}, [render, ...dependencies ?? []]);
		const normalizedRender = (0, react.useMemo)(() => {
			if (typeof render === "undefined") return;
			return ((args) => {
				const currentRender = renderRef.current;
				if (typeof currentRender === "undefined") return null;
				if (typeof currentRender === "string") return react.default.createElement(react.default.Fragment, null, currentRender);
				const rendered = currentRender({
					...args,
					result: typeof args.result === "string" ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result
				});
				if (typeof rendered === "string") return react.default.createElement(react.default.Fragment, null, rendered);
				return rendered ?? null;
			});
		}, []);
		const handlerRef = (0, react.useRef)(tool.handler);
		(0, react.useEffect)(() => {
			handlerRef.current = tool.handler;
		}, [tool.handler, ...dependencies ?? []]);
		useFrontendTool$1({
			name,
			description,
			parameters: zodParameters,
			handler: tool.handler ? (args) => handlerRef.current?.(args) : void 0,
			followUp,
			render: normalizedRender,
			available: available === void 0 ? void 0 : available !== "disabled"
		});
	}

//#endregion
//#region src/hooks/use-render-tool-call.ts
	function useRenderToolCall(tool, dependencies) {
		const { copilotkit } = useCopilotKit();
		const hasAddedRef = (0, react.useRef)(false);
		(0, react.useEffect)(() => {
			const { name, parameters, render } = tool;
			const zodParameters = (0, _copilotkit_shared.getZodParameters)(parameters);
			const renderToolCall = name === "*" ? defineToolCallRenderer({
				name: "*",
				render: ((args) => {
					return render({
						...args,
						result: args.result ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result
					});
				})
			}) : defineToolCallRenderer({
				name,
				args: zodParameters,
				render: ((args) => {
					return render({
						...args,
						result: args.result ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result
					});
				})
			});
			const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);
			if (existingIndex !== -1) copilotkit.renderToolCalls.splice(existingIndex, 1);
			copilotkit.renderToolCalls.push(renderToolCall);
			hasAddedRef.current = true;
			return () => {
				if (hasAddedRef.current) {
					const index = copilotkit.renderToolCalls.findIndex((r) => r.name === name);
					if (index !== -1) copilotkit.renderToolCalls.splice(index, 1);
					hasAddedRef.current = false;
				}
			};
		}, [tool, ...dependencies ?? []]);
	}

//#endregion
//#region src/hooks/use-human-in-the-loop.ts
	function useHumanInTheLoop(tool, dependencies) {
		const { render, ...toolRest } = tool;
		const { name, description, parameters, followUp } = toolRest;
		const zodParameters = (0, _copilotkit_shared.getZodParameters)(parameters);
		const renderRef = (0, react.useRef)(null);
		(0, react.useEffect)(() => {
			renderRef.current = (args) => {
				if (typeof render === "string") return react.default.createElement(react.default.Fragment, null, render);
				if (!render) return null;
				const rendered = render((() => {
					const mappedArgs = args.args;
					switch (args.status) {
						case _copilotkit_core.ToolCallStatus.InProgress: return {
							args: mappedArgs,
							respond: args.respond,
							status: args.status,
							handler: void 0
						};
						case _copilotkit_core.ToolCallStatus.Executing: return {
							args: mappedArgs,
							respond: args.respond,
							status: args.status,
							handler: () => {}
						};
						case _copilotkit_core.ToolCallStatus.Complete: return {
							args: mappedArgs,
							respond: args.respond,
							status: args.status,
							result: args.result ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result,
							handler: void 0
						};
						default: throw new _copilotkit_shared.CopilotKitError({
							code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN,
							message: `Invalid tool call status: ${args.status}`
						});
					}
				})());
				if (typeof rendered === "string") return react.default.createElement(react.default.Fragment, null, rendered);
				return rendered ?? null;
			};
		}, [render, ...dependencies ?? []]);
		useHumanInTheLoop$1({
			name,
			description,
			followUp,
			parameters: zodParameters,
			render: ((args) => renderRef.current?.(args) ?? null)
		});
	}

//#endregion
//#region src/hooks/use-copilot-action.ts
/**
	* Example usage of useCopilotAction with complex parameters:
	*
	* @example
	* useCopilotAction({
	*   name: "myAction",
	*   parameters: [
	*     { name: "arg1", type: "string", enum: ["option1", "option2", "option3"], required: false },
	*     { name: "arg2", type: "number" },
	*     {
	*       name: "arg3",
	*       type: "object",
	*       attributes: [
	*         { name: "nestedArg1", type: "boolean" },
	*         { name: "xyz", required: false },
	*       ],
	*     },
	*     { name: "arg4", type: "number[]" },
	*   ],
	*   handler: ({ arg1, arg2, arg3, arg4 }) => {
	*     const x = arg3.nestedArg1;
	*     const z = arg3.xyz;
	*     console.log(arg1, arg2, arg3);
	*   },
	* });
	*
	* @example
	* // Simple action without parameters
	* useCopilotAction({
	*   name: "myAction",
	*   handler: () => {
	*     console.log("No parameters provided.");
	*   },
	* });
	*
	* @example
	* // Interactive action with UI rendering and response handling
	* useCopilotAction({
	*   name: "handleMeeting",
	*   description: "Handle a meeting by booking or canceling",
	*   parameters: [
	*     {
	*       name: "meeting",
	*       type: "string",
	*       description: "The meeting to handle",
	*       required: true,
	*     },
	*     {
	*       name: "date",
	*       type: "string",
	*       description: "The date of the meeting",
	*       required: true,
	*     },
	*     {
	*       name: "title",
	*       type: "string",
	*       description: "The title of the meeting",
	*       required: true,
	*     },
	*   ],
	*   renderAndWaitForResponse: ({ args, respond, status }) => {
	*     const { meeting, date, title } = args;
	*     return (
	*       <MeetingConfirmationDialog
	*         meeting={meeting}
	*         date={date}
	*         title={title}
	*         onConfirm={() => respond('meeting confirmed')}
	*         onCancel={() => respond('meeting canceled')}
	*       />
	*     );
	*   },
	* });
	*
	* @example
	* // Catch all action allows you to render actions that are not defined in the frontend
	* useCopilotAction({
	*   name: "*",
	*   render: ({ name, args, status, result, handler, respond }) => {
	*     return <div>Rendering action: {name}</div>;
	*   },
	* });
	*/
	/**
	* <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif" width="500" />
	* `useCopilotAction` is a React hook that you can use in your application to provide
	* custom actions that can be called by the AI. Essentially, it allows the Copilot to
	* execute these actions contextually during a chat, based on the user's interactions
	* and needs.
	*
	* Here's how it works:
	*
	* Use `useCopilotAction` to set up actions that the Copilot can call. To provide
	* more context to the Copilot, you can provide it with a `description` (for example to explain
	* what the action does, under which conditions it can be called, etc.).
	*
	* Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,
	* or complex, e.g. objects or arrays.
	*
	* Finally, you provide a `handler` function that receives the parameters and returns a result.
	* CopilotKit takes care of automatically inferring the parameter types, so you get type safety
	* and autocompletion for free.
	*
	* To render a custom UI for the action, you can provide a `render()` function. This function
	* lets you render a custom component or return a string to display.
	*
	* ## Usage
	*
	* ### Simple Usage
	*
	* ```tsx
	* useCopilotAction({
	*   name: "sayHello",
	*   description: "Say hello to someone.",
	*   parameters: [
	*     {
	*       name: "name",
	*       type: "string",
	*       description: "name of the person to say greet",
	*     },
	*   ],
	*   handler: async ({ name }) => {
	*     alert(`Hello, ${name}!`);
	*   },
	* });
	* ```
	*
	* ## Generative UI
	*
	* This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.
	*/
	function getActionConfig(action) {
		if (action.name === "*") return {
			type: "render",
			action
		};
		if ("renderAndWaitForResponse" in action || "renderAndWait" in action) {
			let render = action.render;
			if (!render && "renderAndWaitForResponse" in action) render = action.renderAndWaitForResponse;
			if (!render && "renderAndWait" in action) render = action.renderAndWait;
			return {
				type: "hitl",
				action: {
					...action,
					render
				}
			};
		}
		if ("available" in action) {
			if (action.available === "enabled" || action.available === "remote") return {
				type: "frontend",
				action
			};
			if (action.available === "frontend" || action.available === "disabled") return {
				type: "render",
				action
			};
		}
		if ("handler" in action) return {
			type: "frontend",
			action
		};
		throw new Error("Invalid action configuration");
	}
	/**
	* useCopilotAction is a legacy hook maintained for backwards compatibility.
	*
	* To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),
	* we use a registration pattern:
	* 1. This hook registers the action configuration with the CopilotContext
	* 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper
	* 3. React properly manages hook state since components are rendered, not conditionally called
	*
	* This allows action types to change between renders without corrupting React's hook state.
	*/
	function useCopilotAction(action, dependencies) {
		const [initialActionConfig] = (0, react.useState)(getActionConfig(action));
		const currentActionConfig = getActionConfig(action);
		/**
		* Calling hooks conditionally violates React's Rules of Hooks. This rule exists because
		* React maintains the call stack for hooks like useEffect or useState, and conditionally
		* calling a hook would result in inconsistent call stacks between renders.
		*
		* Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the
		* supplied parameters. In order to avoid breaking React's call stack tracking, while
		* breaking the Rule of Hooks, we use a ref to store the initial action configuration
		* and throw an error if the _configuration_ changes such that we would call a different hook.
		*/
		if (initialActionConfig.type !== currentActionConfig.type) throw new Error("Action configuration changed between renders");
		switch (currentActionConfig.type) {
			case "render": return useRenderToolCall(currentActionConfig.action, dependencies);
			case "hitl": return useHumanInTheLoop(currentActionConfig.action, dependencies);
			case "frontend": return useFrontendTool(currentActionConfig.action, dependencies);
			default: throw new Error("Invalid action configuration");
		}
	}

//#endregion
//#region src/hooks/use-coagent-state-render.ts
/**
	* The useCoAgentStateRender hook allows you to render UI or text based components on a Agentic Copilot's state in the chat.
	* This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.
	*
	* ## Usage
	*
	* ### Simple Usage
	*
	* ```tsx
	* import { useCoAgentStateRender } from "@copilotkit/react-core";
	*
	* type YourAgentState = {
	*   agent_state_property: string;
	* }
	*
	* useCoAgentStateRender<YourAgentState>({
	*   name: "basic_agent",
	*   nodeName: "optionally_specify_a_specific_node",
	*   render: ({ status, state, nodeName }) => {
	*     return (
	*       <YourComponent
	*         agentStateProperty={state.agent_state_property}
	*         status={status}
	*         nodeName={nodeName}
	*       />
	*     );
	*   },
	* });
	* ```
	*
	* This allows for you to render UI components or text based on what is happening within the agent.
	*
	* ### Example
	* A great example of this is in our Perplexity Clone where we render the progress of an agent's internet search as it is happening.
	* You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).
	*
	* <Callout type="info">
	*   This example is hosted on Vercel and may take a few seconds to load.
	* </Callout>
	*
	* <iframe src="https://examples-coagents-ai-researcher-ui.vercel.app/" className="w-full rounded-lg border h-[700px] my-4" />
	*/
	/**
	* This hook is used to render agent state with custom UI components or text. This is particularly
	* useful for showing intermediate state or progress during Agentic Copilot operations.
	* To get started using rendering intermediate state through this hook, checkout the documentation.
	*
	* https://docs.copilotkit.ai/langgraph-python/shared-state/predictive-state-updates
	*/
	function useCoAgentStateRender(action, dependencies) {
		const { chatComponentsCache, availableAgents } = (0, react.useContext)(CopilotContext);
		const { setCoAgentStateRender, removeCoAgentStateRender, coAgentStateRenders } = useCoAgentStateRenders();
		const idRef = (0, react.useRef)((0, _copilotkit_shared.randomId)());
		const { setBannerError, addToast } = useToast();
		(0, react.useEffect)(() => {
			if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {
				`${action.name}`;
				setBannerError(new _copilotkit_shared.CopilotKitAgentDiscoveryError({
					agentName: action.name,
					availableAgents: availableAgents.map((a) => ({
						name: a.name,
						id: a.id
					}))
				}));
			}
		}, [availableAgents]);
		const key = `${action.name}-${action.nodeName || "global"}`;
		if (dependencies === void 0) {
			if (coAgentStateRenders[idRef.current]) {
				coAgentStateRenders[idRef.current].handler = action.handler;
				if (typeof action.render === "function") {
					if (chatComponentsCache.current !== null) chatComponentsCache.current.coAgentStateRenders[key] = action.render;
				}
			}
		}
		(0, react.useEffect)(() => {
			const currentId = idRef.current;
			if (Object.entries(coAgentStateRenders).some(([id, otherAction]) => {
				if (id === currentId) return false;
				if (otherAction.name !== action.name) return false;
				const hasNodeName = !!action.nodeName;
				const hasOtherNodeName = !!otherAction.nodeName;
				if (!hasNodeName && !hasOtherNodeName) return true;
				if (hasNodeName !== hasOtherNodeName) return false;
				return action.nodeName === otherAction.nodeName;
			})) addToast({
				type: "warning",
				message: action.nodeName ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden` : `Found multiple state renders for agent ${action.name}. State renders might get overridden`,
				id: `dup-action-${action.name}`
			});
		}, [coAgentStateRenders]);
		(0, react.useEffect)(() => {
			setCoAgentStateRender(idRef.current, action);
			if (chatComponentsCache.current !== null && action.render !== void 0) chatComponentsCache.current.coAgentStateRenders[key] = action.render;
			return () => {
				removeCoAgentStateRender(idRef.current);
			};
		}, [
			setCoAgentStateRender,
			removeCoAgentStateRender,
			action.name,
			typeof action.render === "string" ? action.render : void 0,
			...dependencies || []
		]);
	}

//#endregion
//#region src/hooks/use-make-copilot-document-readable.ts
/**
	* Makes a document readable by Copilot.
	* @param document The document to make readable.
	* @param categories The categories to associate with the document.
	* @param dependencies The dependencies to use for the effect.
	* @returns The id of the document.
	*/
	function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
		const { addDocumentContext, removeDocumentContext } = useCopilotContext();
		const idRef = (0, react.useRef)(void 0);
		(0, react.useEffect)(() => {
			const id = addDocumentContext(document, categories);
			idRef.current = id;
			return () => {
				removeDocumentContext(id);
			};
		}, [
			addDocumentContext,
			removeDocumentContext,
			...dependencies
		]);
		return idRef.current;
	}

//#endregion
//#region src/hooks/use-copilot-readable.ts
/**
	* `useCopilotReadable` is a React hook that provides app-state and other information
	* to the Copilot.
	*
	* ## Usage
	*
	* ### Simple Usage
	*
	* In its most basic usage, useCopilotReadable accepts a single string argument
	* representing any piece of app state, making it available for the Copilot to use
	* as context when responding to user input.
	*
	* ```tsx
	* import { useCopilotReadable } from "@copilotkit/react-core";
	*
	* export function MyComponent() {
	*   const [employees, setEmployees] = useState([]);
	*
	*   useCopilotReadable({
	*     description: "The list of employees",
	*     value: employees,
	*   });
	* }
	* ```
	*
	* ### Custom Serialization
	*
	* By default the value is serialized with `JSON.stringify`. Pass `convert` to
	* control the string the Copilot sees. It is called with the description and the
	* value, in that order:
	*
	* ```tsx
	* useCopilotReadable({
	*   description: "The current user",
	*   value: user,
	*   convert: (description, value) => `${description}: ${value.firstName} ${value.lastName}`,
	* });
	* ```
	*
	* ### Conditional Usage
	*
	* Toggle `available` to add or remove the context as your app state changes.
	* Switching to `"disabled"` removes the entry from the Copilot context; switching
	* back to `"enabled"` re-adds it.
	*
	* ```tsx
	* useCopilotReadable({
	*   description: "The list of employees",
	*   value: employees,
	*   available: showEmployees ? "enabled" : "disabled",
	* });
	* ```
	*
	* ### Re-running on Custom Dependencies
	*
	* The context is refreshed whenever `description`, `value`, `convert` or
	* `available` change. Pass a second argument to add your own dependencies:
	*
	* ```tsx
	* useCopilotReadable(
	*   {
	*     description: "The selected employee",
	*     value: employee,
	*   },
	*   [departmentId],
	* );
	* ```
	*/
	/**
	* Adds the given information to the Copilot context to make it readable by Copilot.
	*/
	function useCopilotReadable({ description, value, convert, available = "enabled" }, dependencies) {
		const { copilotkit } = useCopilotKit();
		const ctxIdRef = (0, react.useRef)(void 0);
		(0, react.useEffect)(() => {
			if (!copilotkit) return;
			if (available === "disabled") return;
			const id = copilotkit.addContext({
				description,
				value: convert ? convert(description, value) : JSON.stringify(value)
			});
			ctxIdRef.current = id;
			return () => {
				copilotkit.removeContext(id);
				if (ctxIdRef.current === id) ctxIdRef.current = void 0;
			};
		}, [
			copilotkit,
			description,
			value,
			convert,
			available,
			...dependencies || []
		]);
		return ctxIdRef.current;
	}

//#endregion
//#region src/hooks/use-agent-nodename.ts
/**
	* Tracks the node the agent is currently executing.
	*
	* Backed by state rather than a ref: mutating a ref schedules no render, so
	* consumers such as `useCoAgent().nodeName` kept reporting whichever node was
	* current at their last render and never updated on their own.
	*/
	function useAgentNodeName(agentName) {
		const { agent } = useAgent({ agentId: agentName });
		const [nodeName, setNodeName] = (0, react.useState)("start");
		(0, react.useEffect)(() => {
			if (!agent) return;
			const subscription = agent.subscribe({
				onStepStartedEvent: ({ event }) => {
					setNodeName(event.stepName);
				},
				onRunStartedEvent: () => {
					setNodeName("start");
				},
				onRunFinishedEvent: () => {
					setNodeName("end");
				},
				onRunErrorEvent: () => {
					setNodeName("end");
				}
			});
			return () => {
				subscription.unsubscribe();
			};
		}, [agent]);
		return nodeName;
	}

//#endregion
//#region src/hooks/use-coagent.ts
/**
	* <Callout type="info">
	*   Usage of this hook assumes some additional setup in your application, for more information
	*   on that see the CoAgents <span className="text-blue-500">[getting started guide](/langgraph-python/quickstart)</span>.
	* </Callout>
	* <Frame className="my-12">
	*   <img
	*     src="https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif"
	*     alt="CoAgents demonstration"
	*     className="w-auto"
	*   />
	* </Frame>
	*
	* This hook is used to integrate an agent into your application. With its use, you can
	* render and update the state of an agent, allowing for a dynamic and interactive experience.
	* We call these shared state experiences agentic copilots, or CoAgents for short.
	*
	* ## Usage
	*
	* ### Simple Usage
	*
	* ```tsx
	* import { useCoAgent } from "@copilotkit/react-core";
	*
	* type AgentState = {
	*   count: number;
	* }
	*
	* const agent = useCoAgent<AgentState>({
	*   name: "my-agent",
	*   initialState: {
	*     count: 0,
	*   },
	* });
	*
	* ```
	*
	* In CopilotKit v2, `useCoAgent` is a thin compatibility wrapper over the v2
	* [`useAgent`](/reference/hooks/useAgent) hook. It returns an object with the
	* following properties:
	*
	* ```tsx
	* const {
	*   name,     // The name of the agent currently being used.
	*   nodeName, // The name of the current LangGraph node.
	*   threadId, // The ID of the thread the agent is running in.
	*   state,    // The current state of the agent.
	*   setState, // A function to update the state of the agent.
	*   running,  // A boolean indicating if the agent is currently running.
	*   start,    // A function to start the agent.
	*   stop,     // A function to stop the agent.
	*   run,      // A function to (re-)run the agent. Maps to the v2 agent's `runAgent()`.
	* } = agent;
	* ```
	*
	* Finally we can leverage these properties to create reactive experiences with the agent!
	*
	* ```tsx
	* const { state, setState } = useCoAgent<AgentState>({
	*   name: "my-agent",
	*   initialState: {
	*     count: 0,
	*   },
	* });
	*
	* return (
	*   <div>
	*     <p>Count: {state.count}</p>
	*     <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>
	*   </div>
	* );
	* ```
	*
	* This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.
	*
	* ## Parameters
	* <PropertyReference name="options" type="UseCoagentOptions<T>" required>
	*   The options to use when creating the coagent.
	*   <PropertyReference name="name" type="string" required>
	*     The name of the agent to use.
	*   </PropertyReference>
	*   <PropertyReference name="initialState" type="T | any">
	*     The initial state of the agent.
	*   </PropertyReference>
	*   <PropertyReference name="state" type="T | any">
	*     State to manage externally if you are using this hook with external state management.
	*   </PropertyReference>
	*   <PropertyReference name="setState" type="(newState: T | ((prevState: T | undefined) => T)) => void">
	*     A function to update the state of the agent if you are using this hook with external state management.
	*   </PropertyReference>
	* </PropertyReference>
	*/
	/**
	* This hook is used to integrate an agent into your application. With its use, you can
	* render and update the state of the agent, allowing for a dynamic and interactive experience.
	* We call these shared state experiences "agentic copilots". To get started using agentic copilots, which
	* we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/langgraph-python/quickstart.
	*/
	function useCoAgent(options) {
		const { agent } = useAgent({ agentId: options.name });
		const { copilotkit } = useCopilotKit();
		const nodeName = useAgentNodeName(options.name);
		const handleStateUpdate = (0, react.useCallback)((newState) => {
			if (!agent) return;
			if (typeof newState === "function") {
				const updater = newState;
				agent.setState(updater(agent.state));
			} else agent.setState({
				...agent.state,
				...newState
			});
		}, [agent?.state, agent?.setState]);
		(0, react.useEffect)(() => {
			if (!options.config && !options.configurable) return;
			let config = options.config ?? {};
			if (options.configurable) config = {
				...config,
				configurable: {
					...options.configurable,
					...config.configurable
				}
			};
			copilotkit.setProperties(config);
		}, [options.config, options.configurable]);
		(0, react.useEffect)(() => {
			if (agent?.state && isExternalStateManagement(options) && JSON.stringify(options.state) !== JSON.stringify(agent.state)) handleStateUpdate(options.state);
		}, [
			agent,
			(0, react.useMemo)(() => isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0, [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]),
			handleStateUpdate
		]);
		const hasStateValues = (0, react.useCallback)((value) => {
			return Boolean(value && Object.keys(value).length);
		}, []);
		const initialStateRef = (0, react.useRef)(isExternalStateManagement(options) ? options.state : "initialState" in options ? options.initialState : void 0);
		(0, react.useEffect)(() => {
			if (isExternalStateManagement(options)) initialStateRef.current = options.state;
			else if ("initialState" in options) initialStateRef.current = options.initialState;
		}, [isExternalStateManagement(options) ? JSON.stringify(options.state) : "initialState" in options ? JSON.stringify(options.initialState) : void 0]);
		(0, react.useEffect)(() => {
			if (!agent) return;
			const subscription = agent.subscribe({
				onStateChanged: (args) => {
					if (isExternalStateManagement(options)) options.setState(args.state);
				},
				onRunInitialized: (args) => {
					if (hasStateValues(args.state)) {
						handleStateUpdate(args.state);
						return;
					}
					if (hasStateValues(agent.state)) return;
					if (initialStateRef.current !== void 0) handleStateUpdate(initialStateRef.current);
				}
			});
			return () => {
				subscription.unsubscribe();
			};
		}, [
			agent,
			handleStateUpdate,
			hasStateValues
		]);
		return (0, react.useMemo)(() => {
			if (!agent) {
				const noop = () => {};
				const noopAsync = async () => {};
				const initialState = ("state" in options && options.state) ?? ("initialState" in options && options.initialState) ?? {};
				return {
					name: options.name,
					nodeName,
					threadId: void 0,
					running: false,
					state: initialState,
					setState: noop,
					start: noop,
					stop: noop,
					run: noopAsync
				};
			}
			return {
				name: agent?.agentId ?? options.name,
				nodeName,
				threadId: agent.threadId,
				running: agent.isRunning,
				state: agent.state,
				setState: handleStateUpdate,
				start: agent.runAgent,
				stop: agent.abortRun,
				run: agent.runAgent
			};
		}, [
			agent?.state,
			agent?.runAgent,
			agent?.abortRun,
			agent?.runAgent,
			agent?.threadId,
			agent?.isRunning,
			agent?.agentId,
			handleStateUpdate,
			options.name
		]);
	}
	const isExternalStateManagement = (options) => {
		return "state" in options && "setState" in options;
	};

//#endregion
//#region src/hooks/use-copilot-runtime-client.ts
	const useCopilotRuntimeClient = (options) => {
		const { setBannerError } = useToast();
		const { showDevConsole, onError, ...runtimeOptions } = options;
		const lastStructuredErrorRef = (0, react.useRef)(null);
		const traceUIError = async (error, originalError) => {
			try {
				await onError({
					type: "error",
					timestamp: Date.now(),
					context: {
						source: "ui",
						request: {
							operation: "runtimeClient",
							url: runtimeOptions.url,
							startTime: Date.now()
						},
						technical: {
							environment: "browser",
							userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
							stackTrace: originalError instanceof Error ? originalError.stack : void 0
						}
					},
					error
				});
			} catch (error) {
				console.error("Error in onError handler:", error);
			}
		};
		return (0, react.useMemo)(() => {
			return new _copilotkit_runtime_client_gql.CopilotRuntimeClient({
				...runtimeOptions,
				handleGQLErrors: (error) => {
					if (error.graphQLErrors?.length) {
						const graphQLErrors = error.graphQLErrors;
						const routeError = (gqlError) => {
							if (gqlError.extensions?.visibility === _copilotkit_shared.ErrorVisibility.SILENT) {
								console.error("CopilotKit Silent Error:", gqlError.message);
								return;
							}
							const now = Date.now();
							const errorMessage = gqlError.message;
							if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) return;
							lastStructuredErrorRef.current = {
								message: errorMessage,
								timestamp: now
							};
							const ckError = createStructuredError(gqlError);
							if (ckError) {
								setBannerError(ckError);
								traceUIError(ckError, gqlError);
							} else {
								const fallbackError = new _copilotkit_shared.CopilotKitError({
									message: gqlError.message,
									code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
								});
								setBannerError(fallbackError);
								traceUIError(fallbackError, gqlError);
							}
						};
						graphQLErrors.forEach(routeError);
					} else {
						const fallbackError = new _copilotkit_shared.CopilotKitError({
							message: error?.message || String(error),
							code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
						});
						setBannerError(fallbackError);
						traceUIError(fallbackError, error);
					}
				},
				handleGQLWarning: (message) => {
					console.warn(message);
					setBannerError(new _copilotkit_shared.CopilotKitError({
						message,
						code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
					}));
				}
			});
		}, [
			runtimeOptions,
			setBannerError,
			onError
		]);
	};
	function createStructuredError(gqlError) {
		const extensions = gqlError.extensions;
		const originalError = extensions?.originalError;
		const message = originalError?.message || gqlError.message;
		const code = extensions?.code;
		if (code) return new _copilotkit_shared.CopilotKitError({
			message,
			code
		});
		if (originalError?.stack?.includes("CopilotApiDiscoveryError")) return new _copilotkit_shared.CopilotKitApiDiscoveryError({ message });
		if (originalError?.stack?.includes("CopilotKitRemoteEndpointDiscoveryError")) return new _copilotkit_shared.CopilotKitRemoteEndpointDiscoveryError({ message });
		if (originalError?.stack?.includes("CopilotKitAgentDiscoveryError")) return new _copilotkit_shared.CopilotKitAgentDiscoveryError({
			agentName: "",
			availableAgents: []
		});
		return null;
	}

//#endregion
//#region src/hooks/use-copilot-authenticated-action.ts
/**
	* Hook to create an authenticated action that requires user sign-in before execution.
	*
	* @internal Defunct — retained for backward compatibility.
	*
	* @param action - The frontend action to be wrapped with authentication
	* @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed
	*/
	function useCopilotAuthenticatedAction_c(action, dependencies) {
		const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();
		const pendingActionRef = (0, react.useRef)(null);
		const executeAction = (0, react.useCallback)((props) => {
			if (typeof action.render === "function") return action.render(props);
			return action.render || react.default.createElement(react.Fragment);
		}, [action]);
		const wrappedRender = (0, react.useCallback)((props) => {
			if (!Object.values(authStates_c || {}).some((state) => state.status === "authenticated")) {
				pendingActionRef.current = props;
				return authConfig_c?.SignInComponent ? react.default.createElement(authConfig_c.SignInComponent, { onSignInComplete: (authState) => {
					setAuthStates_c?.((prev) => ({
						...prev,
						[action.name]: authState
					}));
					if (pendingActionRef.current) {
						executeAction(pendingActionRef.current);
						pendingActionRef.current = null;
					}
				} }) : react.default.createElement(react.Fragment);
			}
			return executeAction(props);
		}, [
			action,
			authStates_c,
			setAuthStates_c
		]);
		useCopilotAction({
			...action,
			render: wrappedRender
		}, dependencies);
	}

//#endregion
//#region src/hooks/use-langgraph-interrupt.ts
/**
	* Transforms a v2 InterruptEvent into the v1 LangGraphInterruptEvent shape
	* expected by existing useLangGraphInterrupt callbacks.
	*/
	function toV1Event(event) {
		const value = typeof event.value === "string" ? (0, _copilotkit_shared.parseJson)(event.value, event.value) : event.value;
		return {
			name: _copilotkit_runtime_client_gql.MetaEventName.LangGraphInterruptEvent,
			type: "MetaEvent",
			value
		};
	}
	function useLangGraphInterrupt(action, _dependencies) {
		const actionRef = (0, react.useRef)(action);
		actionRef.current = action;
		const existingConfig = useCopilotChatConfiguration();
		const resolvedAgentId = action.agentId ?? existingConfig?.agentId ?? "default";
		const threadId = existingConfig?.threadId;
		const nodeName = useAgentNodeName(resolvedAgentId);
		const metadataRef = (0, react.useRef)({
			agentName: resolvedAgentId,
			threadId,
			nodeName
		});
		metadataRef.current = {
			agentName: resolvedAgentId,
			threadId,
			nodeName
		};
		useInterrupt({
			render: (0, react.useCallback)(({ event, result, resolve }) => {
				const renderFn = actionRef.current.render;
				if (!renderFn) return react.default.createElement(react.default.Fragment);
				const rendered = renderFn({
					event: toV1Event(event),
					result,
					resolve: (r) => resolve(r)
				});
				if (typeof rendered === "string") return react.default.createElement(react.default.Fragment, null, rendered);
				return rendered;
			}, []),
			handler: (0, react.useCallback)(({ event, resolve }) => {
				return actionRef.current.handler?.({
					event: toV1Event(event),
					resolve: (r) => resolve(r)
				});
			}, []),
			enabled: (0, react.useCallback)((event) => {
				if (!actionRef.current.enabled) return true;
				return actionRef.current.enabled({
					eventValue: toV1Event(event).value,
					agentMetadata: metadataRef.current
				});
			}, []),
			agentId: resolvedAgentId
		});
	}

//#endregion
//#region src/hooks/use-copilot-additional-instructions.ts
/**
	* `useCopilotAdditionalInstructions` is a React hook that provides additional instructions
	* to the Copilot.
	*
	* ## Usage
	*
	* ### Simple Usage
	*
	* In its most basic usage, useCopilotAdditionalInstructions accepts a single string argument
	* representing the instructions to be added to the Copilot.
	*
	* ```tsx
	* import { useCopilotAdditionalInstructions } from "@copilotkit/react-core";
	*
	* export function MyComponent() {
	*   useCopilotAdditionalInstructions({
	*     instructions: "Do not answer questions about the weather.",
	*   });
	* }
	* ```
	*
	* ### Conditional Usage
	*
	* You can also conditionally add instructions based on the state of your app.
	*
	* ```tsx
	* import { useCopilotAdditionalInstructions } from "@copilotkit/react-core";
	*
	* export function MyComponent() {
	*   const [showInstructions, setShowInstructions] = useState(false);
	*
	*   useCopilotAdditionalInstructions({
	*     available: showInstructions ? "enabled" : "disabled",
	*     instructions: "Do not answer questions about the weather.",
	*   });
	* }
	* ```
	*/
	/**
	* Adds the given instructions to the Copilot context.
	*/
	function useCopilotAdditionalInstructions({ instructions, available = "enabled" }, dependencies) {
		const { setAdditionalInstructions } = useCopilotContext();
		(0, react.useEffect)(() => {
			if (available === "disabled") return;
			setAdditionalInstructions((prevInstructions) => [...prevInstructions || [], instructions]);
			return () => {
				setAdditionalInstructions((prevInstructions) => prevInstructions?.filter((instruction) => instruction !== instructions) || []);
			};
		}, [
			available,
			instructions,
			setAdditionalInstructions,
			...dependencies || []
		]);
	}

//#endregion
//#region src/hooks/use-default-tool.ts
	function useDefaultTool(tool, dependencies) {
		useCopilotAction({
			...tool,
			name: "*"
		}, dependencies);
	}

//#endregion
//#region src/hooks/use-copilot-chat-suggestions.tsx
/**
	* <Callout type="warning">
	*   useCopilotChatSuggestions is experimental. The interface is not final and
	*   can change without notice.
	* </Callout>
	*
	* `useCopilotReadable` is a React hook that provides app-state and other information
	* to the Copilot. Optionally, the hook can also handle hierarchical state within your
	* application, passing these parent-child relationships to the Copilot.
	*
	* <br/>
	* <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-chat-suggestions/use-copilot-chat-suggestions.gif" width="500" />
	*
	* ## Usage
	*
	* ### Install Dependencies
	*
	* This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.
	*
	* ```shell npm2yarn \"@copilotkit/react-ui"\
	* npm install @copilotkit/react-core @copilotkit/react-ui
	* ```
	*
	* ### Simple Usage
	*
	* ```tsx
	* import { useCopilotChatSuggestions } from "@copilotkit/react-ui";
	*
	* export function MyComponent() {
	*   const [employees, setEmployees] = useState([]);
	*
	*   useCopilotChatSuggestions({
	*     instructions: `The following employees are on duty: ${JSON.stringify(employees)}`,
	*   });
	* }
	* ```
	*
	* ### Dependency Management
	*
	* ```tsx
	* import { useCopilotChatSuggestions } from "@copilotkit/react-ui";
	*
	* export function MyComponent() {
	*   useCopilotChatSuggestions(
	*     {
	*       instructions: "Suggest the most relevant next actions.",
	*     },
	*     [appState],
	*   );
	* }
	* ```
	*
	* In the example above, the suggestions are generated based on the given instructions.
	* The hook monitors `appState`, and updates suggestions accordingly whenever it changes.
	*
	* ### Behavior and Lifecycle
	*
	* The hook registers the configuration with the chat context upon component mount and
	* removes it on unmount, ensuring a clean and efficient lifecycle management.
	*/
	function useCopilotChatSuggestions(config, dependencies = []) {
		const resolvedAgentId = useCopilotChatConfiguration()?.agentId ?? "default";
		const available = (config.available === "enabled" ? "always" : config.available) ?? "before-first-message";
		useConfigureSuggestions({
			...config,
			available,
			consumerAgentId: resolvedAgentId
		}, dependencies);
	}

//#endregion
//#region src/types/frontend-action.ts
	function processActionsForRuntimeRequest(actions) {
		return actions.filter((action) => action.available !== _copilotkit_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction).map((action) => {
			let available = _copilotkit_runtime_client_gql.ActionInputAvailability.Enabled;
			if (action.disabled) available = _copilotkit_runtime_client_gql.ActionInputAvailability.Disabled;
			else if (action.available === "disabled") available = _copilotkit_runtime_client_gql.ActionInputAvailability.Disabled;
			else if (action.available === "remote") available = _copilotkit_runtime_client_gql.ActionInputAvailability.Remote;
			return {
				name: action.name,
				description: action.description || "",
				jsonSchema: JSON.stringify((0, _copilotkit_shared.actionParametersToJsonSchema)(action.parameters || [])),
				available
			};
		});
	}

//#endregion
//#region src/lib/copilot-task.ts
/**
	* This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/v1/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/v1/hooks/useCopilotAction), or you can provide your own context and actions.
	*
	* ## Example
	* In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.
	*
	* ```tsx
	* import { CopilotTask, useCopilotContext } from "@copilotkit/react-core";
	*
	* export function MyComponent() {
	*   const context = useCopilotContext();
	*
	*   const task = new CopilotTask({
	*     instructions: "Set a random message",
	*     actions: [
	*       {
	*         name: "setMessage",
	*       description: "Set the message.",
	*       argumentAnnotations: [
	*         {
	*           name: "message",
	*           type: "string",
	*           description:
	*             "A message to display.",
	*           required: true,
	*         },
	*       ],
	*      }
	*     ]
	*   });
	*
	*   const executeTask = async () => {
	*     await task.run(context, action);
	*   }
	*
	*   return (
	*     <>
	*       <button onClick={executeTask}>
	*         Execute task
	*       </button>
	*     </>
	*   )
	* }
	* ```
	*
	* Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/examples/v1/next-openai/src/app/presentation/page.tsx) for a more complete example.
	*/
	var CopilotTask = class {
		constructor(config) {
			this.instructions = config.instructions;
			this.actions = config.actions || [];
			this.includeCopilotReadable = config.includeCopilotReadable !== false;
			this.includeCopilotActions = config.includeCopilotActions !== false;
			this.forwardedParameters = config.forwardedParameters;
		}
		/**
		* Run the task.
		* @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.
		* @param data The data to use for the task.
		*/
		async run(context, data) {
			const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
			for (const fn of this.actions) actions[fn.name] = fn;
			let contextString = "";
			if (data) contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
			if (this.includeCopilotReadable) contextString += context.getContextString([], defaultCopilotContextCategories);
			const messages = [new _copilotkit_runtime_client_gql.TextMessage({
				content: taskSystemMessage(contextString, this.instructions),
				role: _copilotkit_runtime_client_gql.Role.System
			})];
			const response = await new _copilotkit_runtime_client_gql.CopilotRuntimeClient({
				url: context.copilotApiConfig.chatApiEndpoint,
				publicApiKey: context.copilotApiConfig.publicApiKey,
				headers: context.copilotApiConfig.headers,
				credentials: context.copilotApiConfig.credentials
			}).generateCopilotResponse({
				data: {
					frontend: {
						actions: processActionsForRuntimeRequest(Object.values(actions)),
						url: window.location.href
					},
					messages: (0, _copilotkit_runtime_client_gql.convertMessagesToGqlInput)((0, _copilotkit_runtime_client_gql.filterAgentStateMessages)(messages)),
					metadata: { requestType: _copilotkit_runtime_client_gql.CopilotRequestType.Task },
					forwardedParameters: {
						toolChoice: "required",
						...this.forwardedParameters
					}
				},
				properties: context.copilotApiConfig.properties
			}).toPromise();
			const functionCallHandler = context.getFunctionCallHandler(actions);
			const functionCalls = (0, _copilotkit_runtime_client_gql.convertGqlOutputToMessages)(response.data?.generateCopilotResponse?.messages || []).filter((m) => m.isActionExecutionMessage());
			for (const functionCall of functionCalls) await functionCallHandler({
				messages,
				name: functionCall.name,
				args: functionCall.arguments
			});
		}
	};
	function taskSystemMessage(contextString, instructions) {
		return `
Please act as an efficient, competent, conscientious, and industrious professional assistant.

Help the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.
Always be polite and respectful, and prefer brevity over verbosity.

The user has provided you with the following context:
\`\`\`
${contextString}
\`\`\`

They have also provided you with functions you can call to initiate actions on their behalf.

Please assist them as best you can.

This is not a conversation, so please do not ask questions. Just call a function without saying anything else.

The user has given you the following task to complete:

\`\`\`
${instructions}
\`\`\`
`;
	}

//#endregion
exports.CoAgentStateRendersContext = CoAgentStateRendersContext;
exports.CoAgentStateRendersProvider = CoAgentStateRendersProvider;
exports.CopilotContext = CopilotContext;
exports.CopilotKit = CopilotKit;
exports.CopilotMessagesContext = CopilotMessagesContext;
exports.CopilotTask = CopilotTask;
exports.SUGGESTION_RETRY_CONFIG = SUGGESTION_RETRY_CONFIG;
exports.ThreadsContext = ThreadsContext;
exports.ThreadsProvider = ThreadsProvider;
exports.defaultCopilotContextCategories = defaultCopilotContextCategories;
exports.shouldShowDevConsole = shouldShowDevConsole;
exports.useCoAgent = useCoAgent;
exports.useCoAgentStateRender = useCoAgentStateRender;
exports.useCoAgentStateRenders = useCoAgentStateRenders;
exports.useCopilotAction = useCopilotAction;
exports.useCopilotAdditionalInstructions = useCopilotAdditionalInstructions;
exports.useCopilotAuthenticatedAction_c = useCopilotAuthenticatedAction_c;
exports.useCopilotChat = useCopilotChat;
exports.useCopilotChatHeadless_c = useCopilotChatHeadless_c;
exports.useCopilotChatInternal = useCopilotChatInternal;
exports.useCopilotChatSuggestions = useCopilotChatSuggestions;
exports.useCopilotContext = useCopilotContext;
exports.useCopilotMessagesContext = useCopilotMessagesContext;
exports.useCopilotReadable = useCopilotReadable;
exports.useCopilotRuntimeClient = useCopilotRuntimeClient;
exports.useDefaultTool = useDefaultTool;
exports.useFrontendTool = useFrontendTool;
exports.useHumanInTheLoop = useHumanInTheLoop;
exports.useLangGraphInterrupt = useLangGraphInterrupt;
exports.useLazyToolRenderer = useLazyToolRenderer;
exports.useMakeCopilotDocumentReadable = useMakeCopilotDocumentReadable;
exports.useRenderToolCall = useRenderToolCall;
exports.useThreads = useThreads;
});
//# sourceMappingURL=index.umd.js.map