@copilotkit/react-core 1.59.1 → 1.59.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -162,27 +162,26 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
162
162
  };
163
163
  const CopilotChatConfiguration = (0, react.createContext)(null);
164
164
  const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
165
- var _ref, _parentConfig$isModal, _parentConfig$setModa;
166
165
  const parentConfig = (0, react.useContext)(CopilotChatConfiguration);
167
166
  const stableLabels = useShallowStableRef(labels);
168
167
  const mergedLabels = (0, react.useMemo)(() => ({
169
168
  ...CopilotChatDefaultLabels,
170
- ...parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.labels,
169
+ ...parentConfig?.labels,
171
170
  ...stableLabels
172
- }), [stableLabels, parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.labels]);
173
- const resolvedAgentId = (_ref = agentId !== null && agentId !== void 0 ? agentId : parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.agentId) !== null && _ref !== void 0 ? _ref : _copilotkit_shared.DEFAULT_AGENT_ID;
171
+ }), [stableLabels, parentConfig?.labels]);
172
+ const resolvedAgentId = agentId ?? parentConfig?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
174
173
  const resolvedThreadId = (0, react.useMemo)(() => {
175
174
  if (threadId) return threadId;
176
- if (parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.threadId) return parentConfig.threadId;
175
+ if (parentConfig?.threadId) return parentConfig.threadId;
177
176
  return (0, _copilotkit_shared.randomUUID)();
178
- }, [threadId, parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.threadId]);
179
- const resolvedHasExplicitThreadId = (hasExplicitThreadId !== void 0 ? hasExplicitThreadId : !!threadId) || !!(parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.hasExplicitThreadId);
180
- const [internalModalOpen, setInternalModalOpen] = (0, react.useState)(isModalDefaultOpen !== null && isModalDefaultOpen !== void 0 ? isModalDefaultOpen : true);
177
+ }, [threadId, parentConfig?.threadId]);
178
+ const resolvedHasExplicitThreadId = (hasExplicitThreadId !== void 0 ? hasExplicitThreadId : !!threadId) || !!parentConfig?.hasExplicitThreadId;
179
+ const [internalModalOpen, setInternalModalOpen] = (0, react.useState)(isModalDefaultOpen ?? true);
181
180
  const hasExplicitDefault = isModalDefaultOpen !== void 0;
182
181
  const setAndSync = (0, react.useCallback)((open) => {
183
182
  setInternalModalOpen(open);
184
- parentConfig === null || parentConfig === void 0 || parentConfig.setModalOpen(open);
185
- }, [parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.setModalOpen]);
183
+ parentConfig?.setModalOpen(open);
184
+ }, [parentConfig?.setModalOpen]);
186
185
  const isMounted = (0, react.useRef)(false);
187
186
  (0, react.useEffect)(() => {
188
187
  if (!hasExplicitDefault) return;
@@ -190,11 +189,11 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
190
189
  isMounted.current = true;
191
190
  return;
192
191
  }
193
- if ((parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.isModalOpen) === void 0) return;
192
+ if (parentConfig?.isModalOpen === void 0) return;
194
193
  setInternalModalOpen(parentConfig.isModalOpen);
195
- }, [parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.isModalOpen, hasExplicitDefault]);
196
- const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : (_parentConfig$isModal = parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.isModalOpen) !== null && _parentConfig$isModal !== void 0 ? _parentConfig$isModal : internalModalOpen;
197
- const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : (_parentConfig$setModa = parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.setModalOpen) !== null && _parentConfig$setModa !== void 0 ? _parentConfig$setModa : setInternalModalOpen;
194
+ }, [parentConfig?.isModalOpen, hasExplicitDefault]);
195
+ const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : parentConfig?.isModalOpen ?? internalModalOpen;
196
+ const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : parentConfig?.setModalOpen ?? setInternalModalOpen;
198
197
  const configurationValue = (0, react.useMemo)(() => ({
199
198
  labels: mergedLabels,
200
199
  agentId: resolvedAgentId,
@@ -427,7 +426,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
427
426
  }
428
427
  if (mediaRecorderRef.current && mediaRecorderRef.current.state !== "inactive") try {
429
428
  mediaRecorderRef.current.stop();
430
- } catch (_unused) {}
429
+ } catch {}
431
430
  if (streamRef.current) {
432
431
  streamRef.current.getTracks().forEach((track) => track.stop());
433
432
  streamRef.current = null;
@@ -500,8 +499,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
500
499
  const calculateAmplitude = (dataArray) => {
501
500
  let sum = 0;
502
501
  for (let i = 0; i < dataArray.length; i++) {
503
- var _dataArray$i;
504
- const sample = ((_dataArray$i = dataArray[i]) !== null && _dataArray$i !== void 0 ? _dataArray$i : 128) / 128 - 1;
502
+ const sample = (dataArray[i] ?? 128) / 128 - 1;
505
503
  sum += sample * sample;
506
504
  }
507
505
  return Math.sqrt(sum / dataArray.length);
@@ -549,8 +547,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
549
547
  const offset = scrollOffsetRef.current;
550
548
  const edgeFadeWidth = 12;
551
549
  for (let i = 0; i < history.length; i++) {
552
- var _history$i;
553
- const amplitude = (_history$i = history[i]) !== null && _history$i !== void 0 ? _history$i : 0;
550
+ const amplitude = history[i] ?? 0;
554
551
  const scaledAmplitude = Math.min(amplitude * 4, 1);
555
552
  const barHeight = Math.max(2, scaledAmplitude * maxAmplitude * 2);
556
553
  const x = rect.width - (history.length - i) * barSpacing - offset;
@@ -603,13 +600,12 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
603
600
  const SLASH_MENU_MAX_VISIBLE_ITEMS = 5;
604
601
  const SLASH_MENU_ITEM_HEIGHT_PX = 40;
605
602
  function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning = false, onStartTranscribe, onCancelTranscribe, onFinishTranscribe, onFinishTranscribeWithAudio, onAddFile, onChange, value, toolsMenu, autoFocus = false, positioning = "static", keyboardHeight = 0, containerRef, showDisclaimer, bottomAnchored = false, textArea, sendButton, startTranscribeButton, cancelTranscribeButton, finishTranscribeButton, addMenuButton, audioRecorder, disclaimer, children, className, ...props }) {
606
- var _config$labels;
607
603
  const isControlled = value !== void 0;
608
- const [internalValue, setInternalValue] = (0, react.useState)(() => value !== null && value !== void 0 ? value : "");
604
+ const [internalValue, setInternalValue] = (0, react.useState)(() => value ?? "");
609
605
  (0, react.useEffect)(() => {
610
606
  if (!isControlled && value !== void 0) setInternalValue(value);
611
607
  }, [isControlled, value]);
612
- const resolvedValue = isControlled ? value !== null && value !== void 0 ? value : "" : internalValue;
608
+ const resolvedValue = isControlled ? value ?? "" : internalValue;
613
609
  const [layout, setLayout] = (0, react.useState)("compact");
614
610
  const ignoreResizeRef = (0, react.useRef)(false);
615
611
  const resizeEvaluationRafRef = (0, react.useRef)(null);
@@ -623,7 +619,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
623
619
  const audioRecorderRef = (0, react.useRef)(null);
624
620
  const slashMenuRef = (0, react.useRef)(null);
625
621
  const config = useCopilotChatConfiguration();
626
- const labels = (_config$labels = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels !== void 0 ? _config$labels : CopilotChatDefaultLabels;
622
+ const labels = config?.labels ?? CopilotChatDefaultLabels;
627
623
  const previousModalStateRef = (0, react.useRef)(void 0);
628
624
  const measurementCanvasRef = (0, react.useRef)(null);
629
625
  const measurementsRef = (0, react.useRef)({
@@ -674,15 +670,12 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
674
670
  }, [commandItems, commandQuery]);
675
671
  (0, react.useEffect)(() => {
676
672
  if (!autoFocus) {
677
- previousModalStateRef.current = config === null || config === void 0 ? void 0 : config.isModalOpen;
673
+ previousModalStateRef.current = config?.isModalOpen;
678
674
  return;
679
675
  }
680
- if ((config === null || config === void 0 ? void 0 : config.isModalOpen) && !previousModalStateRef.current) {
681
- var _inputRef$current;
682
- (_inputRef$current = inputRef.current) === null || _inputRef$current === void 0 || _inputRef$current.focus({ preventScroll: true });
683
- }
684
- previousModalStateRef.current = config === null || config === void 0 ? void 0 : config.isModalOpen;
685
- }, [config === null || config === void 0 ? void 0 : config.isModalOpen, autoFocus]);
676
+ if (config?.isModalOpen && !previousModalStateRef.current) inputRef.current?.focus({ preventScroll: true });
677
+ previousModalStateRef.current = config?.isModalOpen;
678
+ }, [config?.isModalOpen, autoFocus]);
686
679
  (0, react.useEffect)(() => {
687
680
  if (commandItems.length === 0 && commandQuery !== null) setCommandQuery(null);
688
681
  }, [commandItems.length, commandQuery]);
@@ -721,8 +714,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
721
714
  return;
722
715
  }
723
716
  if (value.startsWith("/")) {
724
- var _value$split$;
725
- const query = ((_value$split$ = value.split(/\r?\n/, 1)[0]) !== null && _value$split$ !== void 0 ? _value$split$ : "").slice(1);
717
+ const query = (value.split(/\r?\n/, 1)[0] ?? "").slice(1);
726
718
  setCommandQuery((prev) => prev === query ? prev : query);
727
719
  } else setCommandQuery((prev) => prev === null ? prev : null);
728
720
  }, [commandItems.length]);
@@ -732,7 +724,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
732
724
  const handleChange = (e) => {
733
725
  const nextValue = e.target.value;
734
726
  if (!isControlled) setInternalValue(nextValue);
735
- onChange === null || onChange === void 0 || onChange(nextValue);
727
+ onChange?.(nextValue);
736
728
  updateSlashState(nextValue);
737
729
  };
738
730
  const clearInputValue = (0, react.useCallback)(() => {
@@ -740,14 +732,12 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
740
732
  if (onChange) onChange("");
741
733
  }, [isControlled, onChange]);
742
734
  const runCommand = (0, react.useCallback)((item) => {
743
- var _item$action;
744
735
  clearInputValue();
745
- (_item$action = item.action) === null || _item$action === void 0 || _item$action.call(item);
736
+ item.action?.();
746
737
  setCommandQuery(null);
747
738
  setSlashHighlightIndex(0);
748
739
  requestAnimationFrame(() => {
749
- var _inputRef$current2;
750
- (_inputRef$current2 = inputRef.current) === null || _inputRef$current2 === void 0 || _inputRef$current2.focus();
740
+ inputRef.current?.focus();
751
741
  });
752
742
  }, [clearInputValue]);
753
743
  const handleKeyDown = (e) => {
@@ -790,7 +780,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
790
780
  }
791
781
  if (e.key === "Enter" && !e.shiftKey) {
792
782
  e.preventDefault();
793
- if (isProcessing) onStop === null || onStop === void 0 || onStop();
783
+ if (isProcessing) onStop?.();
794
784
  else send();
795
785
  }
796
786
  };
@@ -800,7 +790,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
800
790
  if (!trimmed) return;
801
791
  onSubmitMessage(trimmed);
802
792
  if (!isControlled) setInternalValue("");
803
- onChange === null || onChange === void 0 || onChange("");
793
+ onChange?.("");
804
794
  if (inputRef.current) inputRef.current.focus();
805
795
  };
806
796
  const BoundTextArea = renderSlot(textArea, CopilotChatInput.TextArea, {
@@ -822,7 +812,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
822
812
  const canStop = !!onStop;
823
813
  const handleSendButtonClick = () => {
824
814
  if (isProcessing) {
825
- onStop === null || onStop === void 0 || onStop();
815
+ onStop?.();
826
816
  return;
827
817
  }
828
818
  send();
@@ -843,7 +833,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
843
833
  } catch (error) {
844
834
  console.error("Failed to stop recording:", error);
845
835
  }
846
- onFinishTranscribe === null || onFinishTranscribe === void 0 || onFinishTranscribe();
836
+ onFinishTranscribe?.();
847
837
  }, [onFinishTranscribe, onFinishTranscribeWithAudio]);
848
838
  const BoundFinishTranscribeButton = renderSlot(finishTranscribeButton, CopilotChatInput.FinishTranscribeButton, { onClick: handleFinishTranscribe });
849
839
  const BoundAddMenuButton = renderSlot(addMenuButton, CopilotChatInput.AddMenuButton, {
@@ -852,7 +842,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
852
842
  toolsMenu
853
843
  });
854
844
  const BoundDisclaimer = renderSlot(disclaimer, CopilotChatInput.Disclaimer, {});
855
- const shouldShowDisclaimer = showDisclaimer !== null && showDisclaimer !== void 0 ? showDisclaimer : positioning === "absolute";
845
+ const shouldShowDisclaimer = showDisclaimer ?? positioning === "absolute";
856
846
  if (children) {
857
847
  const childProps = {
858
848
  textArea: BoundTextArea,
@@ -976,8 +966,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
976
966
  const renderedMultiline = baseline > 0 ? scrollHeight > baseline + 1 : false;
977
967
  let shouldExpand = hasExplicitBreak || renderedMultiline;
978
968
  if (!shouldExpand) {
979
- var _containerCacheRef$cu;
980
- const cache = (_containerCacheRef$cu = containerCacheRef.current) !== null && _containerCacheRef$cu !== void 0 ? _containerCacheRef$cu : updateContainerCache();
969
+ const cache = containerCacheRef.current ?? updateContainerCache();
981
970
  if (cache && cache.compactWidth > 0) {
982
971
  const compactInnerWidth = Math.max(cache.compactWidth - (measurementsRef.current.paddingLeft || 0) - (measurementsRef.current.paddingRight || 0), 0);
983
972
  if (compactInnerWidth > 0) {
@@ -987,9 +976,8 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
987
976
  const { fontStyle, fontVariant, fontWeight, fontSize, lineHeight, fontFamily } = textareaStyles;
988
977
  if (fontSize && fontFamily) font = `${fontStyle} ${fontVariant} ${fontWeight} ${fontSize}/${lineHeight} ${fontFamily}`;
989
978
  }
990
- if (font === null || font === void 0 ? void 0 : font.trim()) {
991
- var _measurementCanvasRef;
992
- const canvas = (_measurementCanvasRef = measurementCanvasRef.current) !== null && _measurementCanvasRef !== void 0 ? _measurementCanvasRef : document.createElement("canvas");
979
+ if (font?.trim()) {
980
+ const canvas = measurementCanvasRef.current ?? document.createElement("canvas");
993
981
  if (!measurementCanvasRef.current) measurementCanvasRef.current = canvas;
994
982
  const context = canvas.getContext("2d");
995
983
  if (context) {
@@ -1068,10 +1056,8 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1068
1056
  }, [evaluateLayout]);
1069
1057
  const slashMenuVisible = commandQuery !== null && commandItems.length > 0;
1070
1058
  (0, react.useEffect)(() => {
1071
- var _slashMenuRef$current;
1072
1059
  if (!slashMenuVisible || slashHighlightIndex < 0) return;
1073
- const active = (_slashMenuRef$current = slashMenuRef.current) === null || _slashMenuRef$current === void 0 ? void 0 : _slashMenuRef$current.querySelector(`[data-slash-index="${slashHighlightIndex}"]`);
1074
- active === null || active === void 0 || active.scrollIntoView({ block: "nearest" });
1060
+ (slashMenuRef.current?.querySelector(`[data-slash-index="${slashHighlightIndex}"]`))?.scrollIntoView({ block: "nearest" });
1075
1061
  }, [slashMenuVisible, slashHighlightIndex]);
1076
1062
  const slashMenu = slashMenuVisible ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1077
1063
  "data-testid": "copilot-slash-menu",
@@ -1157,13 +1143,11 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1157
1143
  size: "chatInputToolbarIcon",
1158
1144
  className,
1159
1145
  ...props,
1160
- children: children !== null && children !== void 0 ? children : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.ArrowUp, { className: "cpk:size-[18px]" })
1146
+ children: children ?? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.ArrowUp, { className: "cpk:size-[18px]" })
1161
1147
  })
1162
1148
  });
1163
1149
  const ToolbarButton = _CopilotChatInput.ToolbarButton = ({ icon, labelKey, defaultClassName, className, ...props }) => {
1164
- var _config$labels2;
1165
- const config = useCopilotChatConfiguration();
1166
- const labels = (_config$labels2 = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels2 !== void 0 ? _config$labels2 : CopilotChatDefaultLabels;
1150
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
1167
1151
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Tooltip, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(TooltipTrigger, {
1168
1152
  asChild: true,
1169
1153
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
@@ -1201,9 +1185,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1201
1185
  ...props
1202
1186
  });
1203
1187
  _CopilotChatInput.AddMenuButton = ({ className, toolsMenu, onAddFile, disabled, ...props }) => {
1204
- var _config$labels3;
1205
- const config = useCopilotChatConfiguration();
1206
- const labels = (_config$labels3 = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels3 !== void 0 ? _config$labels3 : CopilotChatDefaultLabels;
1188
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
1207
1189
  const [mounted, setMounted] = (0, react.useState)(false);
1208
1190
  (0, react.useEffect)(() => setMounted(true), []);
1209
1191
  const menuItems = (0, react.useMemo)(() => {
@@ -1269,21 +1251,16 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1269
1251
  })] });
1270
1252
  };
1271
1253
  _CopilotChatInput.TextArea = (0, react.forwardRef)(function TextArea({ style, className, autoFocus, placeholder, ...props }, ref) {
1272
- var _config$labels4;
1273
1254
  const internalTextareaRef = (0, react.useRef)(null);
1274
- const config = useCopilotChatConfiguration();
1275
- const labels = (_config$labels4 = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels4 !== void 0 ? _config$labels4 : CopilotChatDefaultLabels;
1255
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
1276
1256
  (0, react.useImperativeHandle)(ref, () => internalTextareaRef.current);
1277
1257
  (0, react.useEffect)(() => {
1278
- if (autoFocus) {
1279
- var _internalTextareaRef$;
1280
- (_internalTextareaRef$ = internalTextareaRef.current) === null || _internalTextareaRef$ === void 0 || _internalTextareaRef$.focus({ preventScroll: true });
1281
- }
1258
+ if (autoFocus) internalTextareaRef.current?.focus({ preventScroll: true });
1282
1259
  }, [autoFocus]);
1283
1260
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
1284
1261
  ref: internalTextareaRef,
1285
1262
  "data-testid": "copilot-chat-textarea",
1286
- placeholder: placeholder !== null && placeholder !== void 0 ? placeholder : labels.chatInputPlaceholder,
1263
+ placeholder: placeholder ?? labels.chatInputPlaceholder,
1287
1264
  className: (0, tailwind_merge.twMerge)("cpk:bg-transparent cpk:outline-none cpk:antialiased cpk:font-regular cpk:leading-relaxed cpk:text-[16px] cpk:placeholder:text-[#00000077] cpk:dark:placeholder:text-[#fffc]", className),
1288
1265
  style: {
1289
1266
  overflow: "auto",
@@ -1296,9 +1273,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1296
1273
  });
1297
1274
  _CopilotChatInput.AudioRecorder = CopilotChatAudioRecorder;
1298
1275
  _CopilotChatInput.Disclaimer = ({ className, ...props }) => {
1299
- var _config$labels5;
1300
- const config = useCopilotChatConfiguration();
1301
- const labels = (_config$labels5 = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels5 !== void 0 ? _config$labels5 : CopilotChatDefaultLabels;
1276
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
1302
1277
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1303
1278
  className: cn("cpk:text-center cpk:text-xs cpk:text-muted-foreground cpk:py-3 cpk:px-4 cpk:max-w-3xl cpk:mx-auto", className),
1304
1279
  ...props,
@@ -1339,7 +1314,6 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1339
1314
  //#region src/v2/lib/react-core.ts
1340
1315
  var CopilotKitCoreReact = class extends _copilotkit_core.CopilotKitCore {
1341
1316
  constructor(config) {
1342
- var _config$renderToolCal, _config$renderCustomM, _config$renderActivit;
1343
1317
  super(config);
1344
1318
  this._renderToolCalls = [];
1345
1319
  this._hookRenderToolCalls = /* @__PURE__ */ new Map();
@@ -1347,9 +1321,9 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1347
1321
  this._renderCustomMessages = [];
1348
1322
  this._renderActivityMessages = [];
1349
1323
  this._interruptElement = null;
1350
- this._renderToolCalls = (_config$renderToolCal = config.renderToolCalls) !== null && _config$renderToolCal !== void 0 ? _config$renderToolCal : [];
1351
- this._renderCustomMessages = (_config$renderCustomM = config.renderCustomMessages) !== null && _config$renderCustomM !== void 0 ? _config$renderCustomM : [];
1352
- this._renderActivityMessages = (_config$renderActivit = config.renderActivityMessages) !== null && _config$renderActivit !== void 0 ? _config$renderActivit : [];
1324
+ this._renderToolCalls = config.renderToolCalls ?? [];
1325
+ this._renderCustomMessages = config.renderCustomMessages ?? [];
1326
+ this._renderActivityMessages = config.renderActivityMessages ?? [];
1353
1327
  }
1354
1328
  get renderCustomMessages() {
1355
1329
  return this._renderCustomMessages;
@@ -1361,10 +1335,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1361
1335
  if (this._hookRenderToolCalls.size === 0) return this._renderToolCalls;
1362
1336
  if (this._cachedMergedRenderToolCalls) return this._cachedMergedRenderToolCalls;
1363
1337
  const merged = /* @__PURE__ */ new Map();
1364
- for (const rc of this._renderToolCalls) {
1365
- var _rc$agentId;
1366
- merged.set(`${(_rc$agentId = rc.agentId) !== null && _rc$agentId !== void 0 ? _rc$agentId : ""}:${rc.name}`, rc);
1367
- }
1338
+ for (const rc of this._renderToolCalls) merged.set(`${rc.agentId ?? ""}:${rc.name}`, rc);
1368
1339
  for (const [key, rc] of this._hookRenderToolCalls) merged.set(key, rc);
1369
1340
  this._cachedMergedRenderToolCalls = Array.from(merged.values());
1370
1341
  return this._cachedMergedRenderToolCalls;
@@ -1381,14 +1352,13 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1381
1352
  this._notifyRenderToolCallsChanged();
1382
1353
  }
1383
1354
  addHookRenderToolCall(entry) {
1384
- var _entry$agentId;
1385
- const key = `${(_entry$agentId = entry.agentId) !== null && _entry$agentId !== void 0 ? _entry$agentId : ""}:${entry.name}`;
1355
+ const key = `${entry.agentId ?? ""}:${entry.name}`;
1386
1356
  this._hookRenderToolCalls.set(key, entry);
1387
1357
  this._cachedMergedRenderToolCalls = null;
1388
1358
  this._notifyRenderToolCallsChanged();
1389
1359
  }
1390
1360
  removeHookRenderToolCall(name, agentId) {
1391
- const key = `${agentId !== null && agentId !== void 0 ? agentId : ""}:${name}`;
1361
+ const key = `${agentId ?? ""}:${name}`;
1392
1362
  if (this._hookRenderToolCalls.delete(key)) {
1393
1363
  this._cachedMergedRenderToolCalls = null;
1394
1364
  this._notifyRenderToolCallsChanged();
@@ -1409,9 +1379,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1409
1379
  setInterruptElement(element) {
1410
1380
  this._interruptElement = element;
1411
1381
  this.notifySubscribers((subscriber) => {
1412
- var _reactSubscriber$onIn;
1413
- const reactSubscriber = subscriber;
1414
- (_reactSubscriber$onIn = reactSubscriber.onInterruptElementChanged) === null || _reactSubscriber$onIn === void 0 || _reactSubscriber$onIn.call(reactSubscriber, {
1382
+ subscriber.onInterruptElementChanged?.({
1415
1383
  copilotkit: this,
1416
1384
  interruptElement: this._interruptElement
1417
1385
  });
@@ -1521,7 +1489,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1521
1489
  */
1522
1490
  function useRenderTool(config, deps) {
1523
1491
  const { copilotkit } = useCopilotKit();
1524
- const extraDeps = deps !== null && deps !== void 0 ? deps : EMPTY_DEPS$1;
1492
+ const extraDeps = deps ?? EMPTY_DEPS$1;
1525
1493
  (0, react.useEffect)(() => {
1526
1494
  const renderer = config.name === "*" && !config.parameters ? defineToolCallRenderer({
1527
1495
  name: "*",
@@ -1550,6 +1518,47 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1550
1518
  //#endregion
1551
1519
  //#region src/v2/hooks/use-default-render-tool.tsx
1552
1520
  /**
1521
+ * Module-level dedup set so an unknown status value only emits a console
1522
+ * warning the FIRST time we encounter it. Otherwise a stuck/unmapped status
1523
+ * would log on every re-render (potentially many per second).
1524
+ */
1525
+ const warnedUnknownStatuses = /* @__PURE__ */ new Set();
1526
+ /**
1527
+ * Map a {@link ToolCallStatus} enum value to the documented string-union
1528
+ * status the {@link DefaultRenderProps} contract exposes. Unknown / future
1529
+ * enum members log a warning (once per distinct value) and fall back to
1530
+ * `"inProgress"`.
1531
+ */
1532
+ function mapToolCallStatus(status) {
1533
+ switch (status) {
1534
+ case _copilotkit_core.ToolCallStatus.Complete: return "complete";
1535
+ case _copilotkit_core.ToolCallStatus.Executing: return "executing";
1536
+ case _copilotkit_core.ToolCallStatus.InProgress: return "inProgress";
1537
+ default: {
1538
+ const key = String(status);
1539
+ if (!warnedUnknownStatuses.has(key)) {
1540
+ warnedUnknownStatuses.add(key);
1541
+ console.warn(`[CopilotKit] Unknown ToolCallStatus "${key}" in default tool-call renderer; falling back to "inProgress".`);
1542
+ }
1543
+ return "inProgress";
1544
+ }
1545
+ }
1546
+ }
1547
+ /**
1548
+ * Convert the framework-internal renderer props (`args`, enum status) into
1549
+ * the documented {@link DefaultRenderProps} shape (`parameters`, string-union
1550
+ * status) so a user `config.render` always sees the documented contract.
1551
+ */
1552
+ function adaptRendererProps(props) {
1553
+ return {
1554
+ name: props.name,
1555
+ toolCallId: props.toolCallId,
1556
+ parameters: props.args,
1557
+ status: mapToolCallStatus(props.status),
1558
+ result: props.result
1559
+ };
1560
+ }
1561
+ /**
1553
1562
  * Registers a wildcard (`"*"`) tool-call renderer via `useRenderTool`.
1554
1563
  *
1555
1564
  * - Call with no config to use CopilotKit's built-in default tool-call card.
@@ -1586,17 +1595,33 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1586
1595
  * ```
1587
1596
  */
1588
1597
  function useDefaultRenderTool(config, deps) {
1589
- var _config$render;
1598
+ const userRender = config?.render;
1590
1599
  useRenderTool({
1591
1600
  name: "*",
1592
- render: (_config$render = config === null || config === void 0 ? void 0 : config.render) !== null && _config$render !== void 0 ? _config$render : DefaultToolCallRenderer
1601
+ render: userRender ? (raw) => userRender(adaptRendererProps(raw)) : (raw) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultToolCallRenderer, { ...adaptRendererProps(raw) })
1593
1602
  }, deps);
1594
1603
  }
1595
- function DefaultToolCallRenderer({ name, parameters, status, result }) {
1604
+ /**
1605
+ * Guarded JSON.stringify used inside the expanded `<pre>` blocks. A circular
1606
+ * reference would otherwise crash the entire React tree on render.
1607
+ */
1608
+ function safeStringifyForPre(value) {
1609
+ try {
1610
+ return JSON.stringify(value, null, 2);
1611
+ } catch (err) {
1612
+ console.warn("[CopilotKit] Failed to JSON.stringify tool-call payload for default renderer; falling back to String():", err);
1613
+ try {
1614
+ return String(value);
1615
+ } catch (innerErr) {
1616
+ console.warn("[CopilotKit] safeStringifyForPre: value could not be stringified:", innerErr);
1617
+ return "[unserializable]";
1618
+ }
1619
+ }
1620
+ }
1621
+ function DefaultToolCallRenderer({ name, toolCallId, parameters, status, result }) {
1596
1622
  const [isExpanded, setIsExpanded] = (0, react.useState)(false);
1597
- const statusString = String(status);
1598
- const isActive = statusString === "inProgress" || statusString === "executing";
1599
- const isComplete = statusString === "complete";
1623
+ const isActive = status === "inProgress" || status === "executing";
1624
+ const isComplete = status === "complete";
1600
1625
  const statusLabel = isActive ? "Running" : isComplete ? "Done" : status;
1601
1626
  const dotColor = isActive ? "#f59e0b" : isComplete ? "#10b981" : "#a1a1aa";
1602
1627
  const badgeBg = isActive ? "#fef3c7" : isComplete ? "#d1fae5" : "#f4f4f5";
@@ -1604,7 +1629,8 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1604
1629
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1605
1630
  "data-testid": "copilot-tool-render",
1606
1631
  "data-tool-name": name,
1607
- "data-status": statusString,
1632
+ "data-tool-call-id": toolCallId,
1633
+ "data-status": status,
1608
1634
  "data-args": safeStringifyForAttr(parameters),
1609
1635
  "data-result": safeStringifyForAttr(result),
1610
1636
  style: {
@@ -1618,7 +1644,9 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1618
1644
  backgroundColor: "#fafafa",
1619
1645
  padding: "14px 16px"
1620
1646
  },
1621
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1647
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1648
+ type: "button",
1649
+ "aria-expanded": isExpanded,
1622
1650
  onClick: () => setIsExpanded(!isExpanded),
1623
1651
  style: {
1624
1652
  display: "flex",
@@ -1626,7 +1654,15 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1626
1654
  justifyContent: "space-between",
1627
1655
  gap: "10px",
1628
1656
  cursor: "pointer",
1629
- userSelect: "none"
1657
+ userSelect: "none",
1658
+ width: "100%",
1659
+ border: "none",
1660
+ padding: 0,
1661
+ margin: 0,
1662
+ background: "transparent",
1663
+ textAlign: "left",
1664
+ font: "inherit",
1665
+ color: "inherit"
1630
1666
  },
1631
1667
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1632
1668
  style: {
@@ -1719,7 +1755,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1719
1755
  whiteSpace: "pre-wrap",
1720
1756
  wordBreak: "break-word"
1721
1757
  },
1722
- children: JSON.stringify(parameters !== null && parameters !== void 0 ? parameters : {}, null, 2)
1758
+ children: safeStringifyForPre(parameters ?? {})
1723
1759
  })] }), result !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1724
1760
  style: {
1725
1761
  fontSize: "10px",
@@ -1742,7 +1778,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1742
1778
  whiteSpace: "pre-wrap",
1743
1779
  wordBreak: "break-word"
1744
1780
  },
1745
- children: typeof result === "string" ? result : JSON.stringify(result, null, 2)
1781
+ children: typeof result === "string" ? result : safeStringifyForPre(result)
1746
1782
  })] })]
1747
1783
  })]
1748
1784
  })
@@ -1753,8 +1789,14 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1753
1789
  if (typeof value === "string") return value;
1754
1790
  try {
1755
1791
  return JSON.stringify(value);
1756
- } catch (_unused) {
1757
- return String(value);
1792
+ } catch (err) {
1793
+ console.warn("[CopilotKit] Failed to JSON.stringify tool-call payload for data-* attribute; falling back to String():", err);
1794
+ try {
1795
+ return String(value);
1796
+ } catch (innerErr) {
1797
+ console.warn("[CopilotKit] safeStringifyForAttr: value could not be stringified:", innerErr);
1798
+ return "";
1799
+ }
1758
1800
  }
1759
1801
  }
1760
1802
 
@@ -1790,11 +1832,10 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1790
1832
  result: void 0
1791
1833
  });
1792
1834
  }, (prevProps, nextProps) => {
1793
- var _prevProps$toolMessag, _nextProps$toolMessag;
1794
1835
  if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;
1795
1836
  if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name) return false;
1796
1837
  if (prevProps.toolCall.function.arguments !== nextProps.toolCall.function.arguments) return false;
1797
- if (((_prevProps$toolMessag = prevProps.toolMessage) === null || _prevProps$toolMessag === void 0 ? void 0 : _prevProps$toolMessag.content) !== ((_nextProps$toolMessag = nextProps.toolMessage) === null || _nextProps$toolMessag === void 0 ? void 0 : _nextProps$toolMessag.content)) return false;
1838
+ if (prevProps.toolMessage?.content !== nextProps.toolMessage?.content) return false;
1798
1839
  if (prevProps.isExecuting !== nextProps.isExecuting) return false;
1799
1840
  if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;
1800
1841
  return true;
@@ -1806,21 +1847,17 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1806
1847
  * @returns A function that takes a tool call and optional tool message and returns the rendered component
1807
1848
  */
1808
1849
  function useRenderToolCall() {
1809
- var _config$agentId;
1810
1850
  const { copilotkit, executingToolCallIds } = useCopilotKit();
1811
- const config = useCopilotChatConfiguration();
1812
- const agentId = (_config$agentId = config === null || config === void 0 ? void 0 : config.agentId) !== null && _config$agentId !== void 0 ? _config$agentId : _copilotkit_shared.DEFAULT_AGENT_ID;
1851
+ const agentId = useCopilotChatConfiguration()?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
1813
1852
  const renderToolCalls = (0, react.useSyncExternalStore)((callback) => {
1814
1853
  return copilotkit.subscribe({ onRenderToolCallsChanged: callback }).unsubscribe;
1815
1854
  }, () => copilotkit.renderToolCalls, () => copilotkit.renderToolCalls);
1816
1855
  return (0, react.useCallback)(({ toolCall, toolMessage }) => {
1817
- var _renderConfig$render;
1818
1856
  const exactMatches = renderToolCalls.filter((rc) => rc.name === toolCall.function.name);
1819
- const renderConfig = exactMatches.find((rc) => rc.agentId === agentId) || exactMatches.find((rc) => !rc.agentId) || exactMatches[0] || renderToolCalls.find((rc) => rc.name === "*");
1820
1857
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolCallRenderer, {
1821
1858
  toolCall,
1822
1859
  toolMessage,
1823
- RenderComponent: (_renderConfig$render = renderConfig === null || renderConfig === void 0 ? void 0 : renderConfig.render) !== null && _renderConfig$render !== void 0 ? _renderConfig$render : defaultToolCallRenderAdapter,
1860
+ RenderComponent: (exactMatches.find((rc) => rc.agentId === agentId) || exactMatches.find((rc) => !rc.agentId) || exactMatches[0] || renderToolCalls.find((rc) => rc.name === "*"))?.render ?? defaultToolCallRenderAdapter,
1824
1861
  isExecuting: executingToolCallIds.has(toolCall.id)
1825
1862
  }, toolCall.id);
1826
1863
  }, [
@@ -1830,11 +1867,11 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1830
1867
  ]);
1831
1868
  }
1832
1869
  function defaultToolCallRenderAdapter(props) {
1833
- const status = props.status === _copilotkit_core.ToolCallStatus.Complete ? "complete" : props.status === _copilotkit_core.ToolCallStatus.Executing ? "executing" : "inProgress";
1834
1870
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultToolCallRenderer, {
1835
1871
  name: props.name,
1872
+ toolCallId: props.toolCallId,
1836
1873
  parameters: props.args,
1837
- status,
1874
+ status: mapToolCallStatus(props.status),
1838
1875
  result: props.result
1839
1876
  });
1840
1877
  }
@@ -1846,8 +1883,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1846
1883
  react.useEffect(() => {
1847
1884
  let mounted = true;
1848
1885
  import("@copilotkit/web-inspector").then((mod) => {
1849
- var _mod$defineWebInspect;
1850
- (_mod$defineWebInspect = mod.defineWebInspector) === null || _mod$defineWebInspect === void 0 || _mod$defineWebInspect.call(mod);
1886
+ mod.defineWebInspector?.();
1851
1887
  const Component = (0, _lit_labs_react.createComponent)({
1852
1888
  tagName: mod.WEB_INSPECTOR_TAG,
1853
1889
  elementClass: mod.WebInspectorElement,
@@ -1862,7 +1898,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
1862
1898
  if (!InspectorComponent) return null;
1863
1899
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(InspectorComponent, {
1864
1900
  ...rest,
1865
- core: core !== null && core !== void 0 ? core : null
1901
+ core: core ?? null
1866
1902
  });
1867
1903
  };
1868
1904
  CopilotKitInspector.displayName = "CopilotKitInspector";
@@ -2031,7 +2067,7 @@ _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
2031
2067
  function buildSandboxHTML(extraCspDomains) {
2032
2068
  const baseScriptSrc = "'self' 'wasm-unsafe-eval' 'unsafe-inline' 'unsafe-eval' blob: data: http://localhost:* https://localhost:*";
2033
2069
  const baseFrameSrc = "* blob: data: http://localhost:* https://localhost:*";
2034
- const extra = (extraCspDomains === null || extraCspDomains === void 0 ? void 0 : extraCspDomains.length) ? " " + extraCspDomains.join(" ") : "";
2070
+ const extra = extraCspDomains?.length ? " " + extraCspDomains.join(" ") : "";
2035
2071
  return `<!doctype html>
2036
2072
  <html>
2037
2073
  <head>
@@ -2167,7 +2203,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2167
2203
  * Fetches resource content on-demand via proxied MCP requests.
2168
2204
  */
2169
2205
  const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, agent }) {
2170
- var _fetchedResource$_met2;
2171
2206
  const { copilotkit } = useCopilotKit();
2172
2207
  const containerRef = (0, react.useRef)(null);
2173
2208
  const iframeRef = (0, react.useRef)(null);
@@ -2186,8 +2221,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2186
2221
  resourceUri: null
2187
2222
  });
2188
2223
  const sendToIframe = (0, react.useCallback)((msg) => {
2189
- var _iframeRef$current;
2190
- if ((_iframeRef$current = iframeRef.current) === null || _iframeRef$current === void 0 ? void 0 : _iframeRef$current.contentWindow) {
2224
+ if (iframeRef.current?.contentWindow) {
2191
2225
  console.log("[MCPAppsRenderer] Sending to iframe:", msg);
2192
2226
  iframeRef.current.contentWindow.postMessage(msg, "*");
2193
2227
  }
@@ -2219,8 +2253,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2219
2253
  (0, react.useEffect)(() => {
2220
2254
  const { resourceUri, serverHash, serverId } = content;
2221
2255
  if (fetchStateRef.current.inProgress && fetchStateRef.current.resourceUri === resourceUri) {
2222
- var _fetchStateRef$curren;
2223
- (_fetchStateRef$curren = fetchStateRef.current.promise) === null || _fetchStateRef$curren === void 0 || _fetchStateRef$curren.then((resource) => {
2256
+ fetchStateRef.current.promise?.then((resource) => {
2224
2257
  if (resource) {
2225
2258
  setFetchedResource(resource);
2226
2259
  setIsLoading(false);
@@ -2240,14 +2273,12 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2240
2273
  fetchStateRef.current.resourceUri = resourceUri;
2241
2274
  const fetchPromise = (async () => {
2242
2275
  try {
2243
- var _resultData$contents;
2244
- const resultData = (await mcpAppsRequestQueue.enqueue(agent, () => agent.runAgent({ forwardedProps: { __proxiedMCPRequest: {
2276
+ const resource = (await mcpAppsRequestQueue.enqueue(agent, () => agent.runAgent({ forwardedProps: { __proxiedMCPRequest: {
2245
2277
  serverHash,
2246
2278
  serverId,
2247
2279
  method: "resources/read",
2248
2280
  params: { uri: resourceUri }
2249
- } } }))).result;
2250
- const resource = resultData === null || resultData === void 0 || (_resultData$contents = resultData.contents) === null || _resultData$contents === void 0 ? void 0 : _resultData$contents[0];
2281
+ } } }))).result?.contents?.[0];
2251
2282
  if (!resource) throw new Error("No resource content in response");
2252
2283
  return resource;
2253
2284
  } catch (err) {
@@ -2278,7 +2309,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2278
2309
  let createdIframe = null;
2279
2310
  const setup = async () => {
2280
2311
  try {
2281
- var _fetchedResource$_met;
2282
2312
  const iframe = document.createElement("iframe");
2283
2313
  createdIframe = iframe;
2284
2314
  iframe.style.width = "100%";
@@ -2290,8 +2320,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2290
2320
  const sandboxReady = new Promise((resolve) => {
2291
2321
  initialListener = (event) => {
2292
2322
  if (event.source === iframe.contentWindow) {
2293
- var _event$data;
2294
- if (((_event$data = event.data) === null || _event$data === void 0 ? void 0 : _event$data.method) === "ui/notifications/sandbox-proxy-ready") {
2323
+ if (event.data?.method === "ui/notifications/sandbox-proxy-ready") {
2295
2324
  if (initialListener) {
2296
2325
  window.removeEventListener("message", initialListener);
2297
2326
  initialListener = null;
@@ -2309,7 +2338,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2309
2338
  }
2310
2339
  return;
2311
2340
  }
2312
- iframe.srcdoc = buildSandboxHTML((_fetchedResource$_met = fetchedResource._meta) === null || _fetchedResource$_met === void 0 || (_fetchedResource$_met = _fetchedResource$_met.ui) === null || _fetchedResource$_met === void 0 || (_fetchedResource$_met = _fetchedResource$_met.csp) === null || _fetchedResource$_met === void 0 ? void 0 : _fetchedResource$_met.resourceDomains);
2341
+ const cspDomains = fetchedResource._meta?.ui?.csp?.resourceDomains;
2342
+ iframe.srcdoc = buildSandboxHTML(cspDomains);
2313
2343
  iframeRef.current = iframe;
2314
2344
  container.appendChild(iframe);
2315
2345
  await sandboxReady;
@@ -2346,17 +2376,16 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2346
2376
  break;
2347
2377
  }
2348
2378
  try {
2349
- var _params$content, _params$followUp;
2350
2379
  const params = msg.params;
2351
2380
  const role = params.role || "user";
2352
- const textContent = ((_params$content = params.content) === null || _params$content === void 0 ? void 0 : _params$content.filter((c) => c.type === "text" && c.text).map((c) => c.text).join("\n")) || "";
2381
+ const textContent = params.content?.filter((c) => c.type === "text" && c.text).map((c) => c.text).join("\n") || "";
2353
2382
  if (textContent) currentAgent.addMessage({
2354
2383
  id: crypto.randomUUID(),
2355
2384
  role,
2356
2385
  content: textContent
2357
2386
  });
2358
2387
  sendResponse(msg.id, { isError: false });
2359
- if (((_params$followUp = params.followUp) !== null && _params$followUp !== void 0 ? _params$followUp : role === "user") && textContent) mcpAppsRequestQueue.enqueue(currentAgent, () => copilotkit.runAgent({ agent: currentAgent })).catch((err) => console.error("[MCPAppsRenderer] ui/message agent run failed:", err));
2388
+ if ((params.followUp ?? role === "user") && textContent) mcpAppsRequestQueue.enqueue(currentAgent, () => copilotkit.runAgent({ agent: currentAgent })).catch((err) => console.error("[MCPAppsRenderer] ui/message agent run failed:", err));
2360
2389
  } catch (err) {
2361
2390
  console.error("[MCPAppsRenderer] ui/message error:", err);
2362
2391
  sendResponse(msg.id, { isError: true });
@@ -2364,8 +2393,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2364
2393
  break;
2365
2394
  }
2366
2395
  case "ui/open-link": {
2367
- var _msg$params;
2368
- const url = (_msg$params = msg.params) === null || _msg$params === void 0 ? void 0 : _msg$params.url;
2396
+ const url = msg.params?.url;
2369
2397
  if (url) {
2370
2398
  window.open(url, "_blank", "noopener,noreferrer");
2371
2399
  sendResponse(msg.id, { isError: false });
@@ -2482,7 +2510,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2482
2510
  content.result,
2483
2511
  sendNotification
2484
2512
  ]);
2485
- const borderStyle = (fetchedResource === null || fetchedResource === void 0 || (_fetchedResource$_met2 = fetchedResource._meta) === null || _fetchedResource$_met2 === void 0 || (_fetchedResource$_met2 = _fetchedResource$_met2.ui) === null || _fetchedResource$_met2 === void 0 ? void 0 : _fetchedResource$_met2.prefersBorder) === true ? {
2513
+ const borderStyle = fetchedResource?._meta?.ui?.prefersBorder === true ? {
2486
2514
  borderRadius: "8px",
2487
2515
  backgroundColor: "#f9f9f9",
2488
2516
  border: "1px solid #e0e0e0"
@@ -2588,13 +2616,12 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2588
2616
  * (no throttle delay).
2589
2617
  */
2590
2618
  function shouldFlushImmediately(prev, next) {
2591
- var _next$jsExpressions$l, _next$jsExpressions, _prev$jsExpressions$l, _prev$jsExpressions, _next$html, _prev$html;
2592
2619
  if (next.cssComplete && (!prev || !prev.cssComplete)) return true;
2593
2620
  if (next.htmlComplete) return true;
2594
2621
  if (next.generating === false) return true;
2595
2622
  if (next.jsFunctions && (!prev || !prev.jsFunctions)) return true;
2596
- if (((_next$jsExpressions$l = (_next$jsExpressions = next.jsExpressions) === null || _next$jsExpressions === void 0 ? void 0 : _next$jsExpressions.length) !== null && _next$jsExpressions$l !== void 0 ? _next$jsExpressions$l : 0) > ((_prev$jsExpressions$l = prev === null || prev === void 0 || (_prev$jsExpressions = prev.jsExpressions) === null || _prev$jsExpressions === void 0 ? void 0 : _prev$jsExpressions.length) !== null && _prev$jsExpressions$l !== void 0 ? _prev$jsExpressions$l : 0)) return true;
2597
- if (((_next$html = next.html) === null || _next$html === void 0 ? void 0 : _next$html.length) && (!prev || !((_prev$html = prev.html) === null || _prev$html === void 0 ? void 0 : _prev$html.length))) return true;
2623
+ if ((next.jsExpressions?.length ?? 0) > (prev?.jsExpressions?.length ?? 0)) return true;
2624
+ if (next.html?.length && (!prev || !prev.html?.length)) return true;
2598
2625
  return false;
2599
2626
  }
2600
2627
  /**
@@ -2644,8 +2671,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2644
2671
  return `<head><style>${css}</style></head>${html}`;
2645
2672
  }
2646
2673
  const OpenGenerativeUIActivityRendererInner = react.default.memo(function OpenGenerativeUIActivityRendererInner({ content }) {
2647
- var _content$initialHeigh, _content$html, _content$html2, _content$jsExpression;
2648
- const initialHeight = (_content$initialHeigh = content.initialHeight) !== null && _content$initialHeigh !== void 0 ? _content$initialHeigh : 200;
2674
+ const initialHeight = content.initialHeight ?? 200;
2649
2675
  const [autoHeight, setAutoHeight] = (0, react.useState)(null);
2650
2676
  const sandboxFunctions = useSandboxFunctions();
2651
2677
  const localApi = (0, react.useMemo)(() => {
@@ -2653,13 +2679,13 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2653
2679
  for (const fn of sandboxFunctions) api[fn.name] = fn.handler;
2654
2680
  return api;
2655
2681
  }, [sandboxFunctions]);
2656
- const fullHtml = content.htmlComplete && ((_content$html = content.html) === null || _content$html === void 0 ? void 0 : _content$html.length) ? content.html.join("") : void 0;
2682
+ const fullHtml = content.htmlComplete && content.html?.length ? content.html.join("") : void 0;
2657
2683
  const css = content.cssComplete ? content.css : void 0;
2658
2684
  const cssReady = !!content.cssComplete;
2659
- const partialHtml = !content.htmlComplete && ((_content$html2 = content.html) === null || _content$html2 === void 0 ? void 0 : _content$html2.length) ? content.html.join("") : void 0;
2685
+ const partialHtml = !content.htmlComplete && content.html?.length ? content.html.join("") : void 0;
2660
2686
  const previewBody = partialHtml ? processPartialHtml(partialHtml) : void 0;
2661
2687
  const previewStyles = partialHtml ? extractCompleteStyles(partialHtml) : "";
2662
- const hasPreview = cssReady && !!(previewBody === null || previewBody === void 0 ? void 0 : previewBody.trim());
2688
+ const hasPreview = cssReady && !!previewBody?.trim();
2663
2689
  const hasVisibleSandbox = !!fullHtml || hasPreview;
2664
2690
  const containerRef = (0, react.useRef)(null);
2665
2691
  const sandboxRef = (0, react.useRef)(null);
@@ -2674,9 +2700,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2674
2700
  if (!container || fullHtml || !hasPreview || previewSandboxRef.current) return;
2675
2701
  let cancelled = false;
2676
2702
  import("@jetbrains/websandbox").then((mod) => {
2677
- var _mod$default$default, _mod$default;
2678
2703
  if (cancelled) return;
2679
- const sandbox = ((_mod$default$default = (_mod$default = mod.default) === null || _mod$default === void 0 ? void 0 : _mod$default.default) !== null && _mod$default$default !== void 0 ? _mod$default$default : mod.default).create({}, {
2704
+ const sandbox = (mod.default?.default ?? mod.default).create({}, {
2680
2705
  frameContainer: container,
2681
2706
  frameContent: "<head></head><body></body>",
2682
2707
  allowAdditionalAttributes: ""
@@ -2735,9 +2760,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2735
2760
  pendingQueueRef.current = [];
2736
2761
  const htmlContent = css ? injectCssIntoHtml(fullHtml, css) : fullHtml;
2737
2762
  import("@jetbrains/websandbox").then((mod) => {
2738
- var _mod$default$default2, _mod$default2;
2739
2763
  if (cancelled) return;
2740
- const sandbox = ((_mod$default$default2 = (_mod$default2 = mod.default) === null || _mod$default2 === void 0 ? void 0 : _mod$default2.default) !== null && _mod$default$default2 !== void 0 ? _mod$default$default2 : mod.default).create(localApi, {
2764
+ const sandbox = (mod.default?.default ?? mod.default).create(localApi, {
2741
2765
  frameContainer: container,
2742
2766
  frameContent: ensureHead(htmlContent),
2743
2767
  allowAdditionalAttributes: ""
@@ -2800,16 +2824,15 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2800
2824
  for (const expr of newExprs) await sandbox.run(expr);
2801
2825
  })();
2802
2826
  else pendingQueueRef.current.push(...newExprs);
2803
- }, [(_content$jsExpression = content.jsExpressions) === null || _content$jsExpression === void 0 ? void 0 : _content$jsExpression.length]);
2827
+ }, [content.jsExpressions?.length]);
2804
2828
  const generationDone = content.generating === false;
2805
2829
  (0, react.useEffect)(() => {
2806
2830
  const sandbox = sandboxRef.current;
2807
2831
  if (!generationDone || !sandbox) return;
2808
2832
  let handled = false;
2809
2833
  const onMessage = (e) => {
2810
- var _e$data;
2811
2834
  if (handled) return;
2812
- if (e.source === sandbox.iframe.contentWindow && ((_e$data = e.data) === null || _e$data === void 0 ? void 0 : _e$data.type) === "__ck_resize") {
2835
+ if (e.source === sandbox.iframe.contentWindow && e.data?.type === "__ck_resize") {
2813
2836
  handled = true;
2814
2837
  setAutoHeight(e.data.height);
2815
2838
  window.removeEventListener("message", onMessage);
@@ -2835,7 +2858,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2835
2858
  window.removeEventListener("message", onMessage);
2836
2859
  };
2837
2860
  }, [generationDone]);
2838
- const height = autoHeight !== null && autoHeight !== void 0 ? autoHeight : initialHeight;
2861
+ const height = autoHeight ?? initialHeight;
2839
2862
  const isGenerating = content.generating !== false;
2840
2863
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2841
2864
  ref: containerRef,
@@ -2889,7 +2912,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2889
2912
  * Displays placeholder messages while the UI is being generated.
2890
2913
  */
2891
2914
  const OpenGenerativeUIToolRenderer = function OpenGenerativeUIToolRenderer(props) {
2892
- var _messages$visibleMess;
2893
2915
  const [visibleMessageIndex, setVisibleMessageIndex] = (0, react.useState)(0);
2894
2916
  const prevMessageCountRef = (0, react.useRef)(0);
2895
2917
  const messages = props.args.placeholderMessages;
@@ -2904,7 +2926,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2904
2926
  setVisibleMessageIndex((i) => (i + 1) % messages.length);
2905
2927
  }, 5e3);
2906
2928
  return () => clearInterval(timer);
2907
- }, [messages === null || messages === void 0 ? void 0 : messages.length, props.status]);
2929
+ }, [messages?.length, props.status]);
2908
2930
  if (props.status === _copilotkit_core.ToolCallStatus.Complete) return null;
2909
2931
  if (!messages || messages.length === 0) return null;
2910
2932
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
@@ -2913,7 +2935,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2913
2935
  color: "#999",
2914
2936
  fontSize: "14px"
2915
2937
  },
2916
- children: (_messages$visibleMess = messages[visibleMessageIndex]) !== null && _messages$visibleMess !== void 0 ? _messages$visibleMess : messages[0]
2938
+ children: messages[visibleMessageIndex] ?? messages[0]
2917
2939
  });
2918
2940
  };
2919
2941
 
@@ -2945,7 +2967,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2945
2967
  (0, react.useEffect)(() => {
2946
2968
  if (content === lastContentRef.current) return;
2947
2969
  lastContentRef.current = content;
2948
- const incoming = content === null || content === void 0 ? void 0 : content[A2UI_OPERATIONS_KEY];
2970
+ const incoming = content?.[A2UI_OPERATIONS_KEY];
2949
2971
  if (!content || !Array.isArray(incoming)) {
2950
2972
  setOperations([]);
2951
2973
  return;
@@ -2955,14 +2977,13 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2955
2977
  const groupedOperations = (0, react.useMemo)(() => {
2956
2978
  const groups = /* @__PURE__ */ new Map();
2957
2979
  for (const operation of operations) {
2958
- var _getOperationSurfaceI;
2959
- const surfaceId = (_getOperationSurfaceI = getOperationSurfaceId(operation)) !== null && _getOperationSurfaceI !== void 0 ? _getOperationSurfaceI : _copilotkit_a2ui_renderer.DEFAULT_SURFACE_ID;
2980
+ const surfaceId = getOperationSurfaceId(operation) ?? _copilotkit_a2ui_renderer.DEFAULT_SURFACE_ID;
2960
2981
  if (!groups.has(surfaceId)) groups.set(surfaceId, []);
2961
2982
  groups.get(surfaceId).push(operation);
2962
2983
  }
2963
2984
  return groups;
2964
2985
  }, [operations]);
2965
- if (!groupedOperations.size) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(loadingComponent !== null && loadingComponent !== void 0 ? loadingComponent : DefaultA2UILoading, {});
2986
+ if (!groupedOperations.size) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(loadingComponent ?? DefaultA2UILoading, {});
2966
2987
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2967
2988
  className: "cpk:flex cpk:min-h-0 cpk:flex-1 cpk:flex-col cpk:gap-6 cpk:overflow-auto cpk:py-6",
2968
2989
  children: Array.from(groupedOperations.entries()).map(([surfaceId, ops]) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ReactSurfaceHost, {
@@ -3036,7 +3057,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3036
3057
  const hash = JSON.stringify(operations);
3037
3058
  if (hash === lastHashRef.current) return;
3038
3059
  lastHashRef.current = hash;
3039
- processMessages(getSurface(surfaceId) ? operations.filter((op) => !(op === null || op === void 0 ? void 0 : op.createSurface)) : operations);
3060
+ processMessages(getSurface(surfaceId) ? operations.filter((op) => !op?.createSurface) : operations);
3040
3061
  }, [
3041
3062
  processMessages,
3042
3063
  getSurface,
@@ -3088,10 +3109,9 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3088
3109
  });
3089
3110
  }
3090
3111
  function getOperationSurfaceId(operation) {
3091
- var _ref, _ref2, _ref3, _operation$createSurf, _operation$createSurf2, _operation$updateComp, _operation$updateData, _operation$deleteSurf;
3092
3112
  if (!operation || typeof operation !== "object") return null;
3093
3113
  if (typeof operation.surfaceId === "string") return operation.surfaceId;
3094
- return (_ref = (_ref2 = (_ref3 = (_operation$createSurf = operation === null || operation === void 0 || (_operation$createSurf2 = operation.createSurface) === null || _operation$createSurf2 === void 0 ? void 0 : _operation$createSurf2.surfaceId) !== null && _operation$createSurf !== void 0 ? _operation$createSurf : operation === null || operation === void 0 || (_operation$updateComp = operation.updateComponents) === null || _operation$updateComp === void 0 ? void 0 : _operation$updateComp.surfaceId) !== null && _ref3 !== void 0 ? _ref3 : operation === null || operation === void 0 || (_operation$updateData = operation.updateDataModel) === null || _operation$updateData === void 0 ? void 0 : _operation$updateData.surfaceId) !== null && _ref2 !== void 0 ? _ref2 : operation === null || operation === void 0 || (_operation$deleteSurf = operation.deleteSurface) === null || _operation$deleteSurf === void 0 ? void 0 : _operation$deleteSurf.surfaceId) !== null && _ref !== void 0 ? _ref : null;
3114
+ return operation?.createSurface?.surfaceId ?? operation?.updateComponents?.surfaceId ?? operation?.updateDataModel?.surfaceId ?? operation?.deleteSurface?.surfaceId ?? null;
3095
3115
  }
3096
3116
 
3097
3117
  //#endregion
@@ -3116,7 +3136,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3116
3136
  const now = Date.now();
3117
3137
  let { tokens } = lastRef.current;
3118
3138
  if (now - lastRef.current.time > 200) {
3119
- const chars = JSON.stringify(parameters !== null && parameters !== void 0 ? parameters : {}).length;
3139
+ const chars = JSON.stringify(parameters ?? {}).length;
3120
3140
  tokens = Math.round(chars / 4);
3121
3141
  lastRef.current = {
3122
3142
  time: now,
@@ -3404,21 +3424,20 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3404
3424
  function A2UIBuiltInToolCallRenderer() {
3405
3425
  const { copilotkit } = useCopilotKit();
3406
3426
  (0, react.useEffect)(() => {
3407
- var _renderToolCalls;
3408
3427
  const renderer = defineToolCallRenderer({
3409
3428
  name: RENDER_A2UI_TOOL_NAME,
3410
3429
  args: zod.z.any(),
3411
3430
  render: ({ status, args: parameters }) => {
3412
3431
  if (status === "complete") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {});
3413
3432
  const params = parameters;
3414
- const items = params === null || params === void 0 ? void 0 : params.items;
3433
+ const items = params?.items;
3415
3434
  if (Array.isArray(items) && items.length > 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {});
3416
- const components = params === null || params === void 0 ? void 0 : params.components;
3435
+ const components = params?.components;
3417
3436
  if (Array.isArray(components) && components.length > 2) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {});
3418
3437
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIProgressIndicator, { parameters });
3419
3438
  }
3420
3439
  });
3421
- const existing = (_renderToolCalls = copilotkit._renderToolCalls) !== null && _renderToolCalls !== void 0 ? _renderToolCalls : [];
3440
+ const existing = copilotkit._renderToolCalls ?? [];
3422
3441
  copilotkit.setRenderToolCalls([...existing.filter((rc) => rc.name !== RENDER_A2UI_TOOL_NAME), renderer]);
3423
3442
  }, [copilotkit]);
3424
3443
  return null;
@@ -3508,7 +3527,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3508
3527
  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)";
3509
3528
  function useStableArrayProp(prop, warningMessage, isMeaningfulChange) {
3510
3529
  const empty = (0, react.useMemo)(() => [], []);
3511
- const value = prop !== null && prop !== void 0 ? prop : empty;
3530
+ const value = prop ?? empty;
3512
3531
  const initial = (0, react.useRef)(value);
3513
3532
  (0, react.useEffect)(() => {
3514
3533
  if (warningMessage && value !== initial.current && (isMeaningfulChange ? isMeaningfulChange(initial.current, value) : true)) console.error(warningMessage);
@@ -3516,7 +3535,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3516
3535
  return value;
3517
3536
  }
3518
3537
  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 }) => {
3519
- var _openGenerativeUI$des;
3520
3538
  const [shouldRenderInspector, setShouldRenderInspector] = (0, react.useState)(false);
3521
3539
  const [runtimeA2UIEnabled, setRuntimeA2UIEnabled] = (0, react.useState)(false);
3522
3540
  const [runtimeOpenGenUIEnabled, setRuntimeOpenGenUIEnabled] = (0, react.useState)(false);
@@ -3530,10 +3548,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3530
3548
  else setShouldRenderInspector(false);
3531
3549
  }, [showDevConsole]);
3532
3550
  const renderToolCallsList = useStableArrayProp(renderToolCalls, "renderToolCalls must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.", (initial, next) => {
3533
- const key = (rc) => {
3534
- var _rc$agentId, _rc$name;
3535
- return `${(_rc$agentId = rc === null || rc === void 0 ? void 0 : rc.agentId) !== null && _rc$agentId !== void 0 ? _rc$agentId : ""}:${(_rc$name = rc === null || rc === void 0 ? void 0 : rc.name) !== null && _rc$name !== void 0 ? _rc$name : ""}`;
3536
- };
3551
+ const key = (rc) => `${rc?.agentId ?? ""}:${rc?.name ?? ""}`;
3537
3552
  const setFrom = (arr) => new Set(arr.map(key));
3538
3553
  const a = setFrom(initial);
3539
3554
  const b = setFrom(next);
@@ -3554,14 +3569,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3554
3569
  content: OpenGenerativeUIContentSchema,
3555
3570
  render: OpenGenerativeUIActivityRenderer
3556
3571
  });
3557
- if (runtimeA2UIEnabled) {
3558
- var _a2ui$theme;
3559
- renderers.unshift(createA2UIMessageRenderer({
3560
- theme: (_a2ui$theme = a2ui === null || a2ui === void 0 ? void 0 : a2ui.theme) !== null && _a2ui$theme !== void 0 ? _a2ui$theme : _copilotkit_a2ui_renderer.viewerTheme,
3561
- catalog: a2ui === null || a2ui === void 0 ? void 0 : a2ui.catalog,
3562
- loadingComponent: a2ui === null || a2ui === void 0 ? void 0 : a2ui.loadingComponent
3563
- }));
3564
- }
3572
+ if (runtimeA2UIEnabled) renderers.unshift(createA2UIMessageRenderer({
3573
+ theme: a2ui?.theme ?? _copilotkit_a2ui_renderer.viewerTheme,
3574
+ catalog: a2ui?.catalog,
3575
+ loadingComponent: a2ui?.loadingComponent
3576
+ }));
3565
3577
  return renderers;
3566
3578
  }, [
3567
3579
  runtimeA2UIEnabled,
@@ -3571,7 +3583,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3571
3583
  const allActivityRenderers = (0, react.useMemo)(() => {
3572
3584
  return [...renderActivityMessagesList, ...builtInActivityRenderers];
3573
3585
  }, [renderActivityMessagesList, builtInActivityRenderers]);
3574
- const resolvedPublicKey = publicApiKey !== null && publicApiKey !== void 0 ? publicApiKey : publicLicenseKey;
3586
+ const resolvedPublicKey = publicApiKey ?? publicLicenseKey;
3575
3587
  const mergedAgents = (0, react.useMemo)(() => ({
3576
3588
  ...agents,
3577
3589
  ...selfManagedAgents
@@ -3591,10 +3603,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3591
3603
  if (process.env.NODE_ENV === "production") throw new Error(message);
3592
3604
  else console.warn(message);
3593
3605
  }
3594
- const chatApiEndpoint = runtimeUrl !== null && runtimeUrl !== void 0 ? runtimeUrl : resolvedPublicKey ? COPILOT_CLOUD_CHAT_URL$1 : void 0;
3606
+ const chatApiEndpoint = runtimeUrl ?? (resolvedPublicKey ? COPILOT_CLOUD_CHAT_URL$1 : void 0);
3595
3607
  const frontendToolsList = useStableArrayProp(frontendTools, "frontendTools must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.");
3596
3608
  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.");
3597
- const sandboxFunctionsList = useStableArrayProp(openGenerativeUI === null || openGenerativeUI === void 0 ? void 0 : openGenerativeUI.sandboxFunctions, "openGenerativeUI.sandboxFunctions must be a stable array.");
3609
+ const sandboxFunctionsList = useStableArrayProp(openGenerativeUI?.sandboxFunctions, "openGenerativeUI.sandboxFunctions must be a stable array.");
3598
3610
  const processedHumanInTheLoopTools = (0, react.useMemo)(() => {
3599
3611
  const processedTools = [];
3600
3612
  const processedRenderToolCalls = [];
@@ -3736,10 +3748,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3736
3748
  (0, react.useEffect)(() => {
3737
3749
  const subscription = copilotkit.subscribe({ onError: (event) => {
3738
3750
  if (onErrorRef.current) onErrorRef.current(event);
3739
- else {
3740
- var _event$context;
3741
- console.error(`[CopilotKit] Error (${event.code}):`, event.error, (_event$context = event.context) !== null && _event$context !== void 0 ? _event$context : {});
3742
- }
3751
+ else console.error(`[CopilotKit] Error (${event.code}):`, event.error, event.context ?? {});
3743
3752
  } });
3744
3753
  return () => {
3745
3754
  subscription.unsubscribe();
@@ -3786,7 +3795,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3786
3795
  (0, react.useEffect)(() => {
3787
3796
  copilotkit.setDefaultThrottleMs(defaultThrottleMs);
3788
3797
  }, [copilotkit, defaultThrottleMs]);
3789
- const designSkill = (_openGenerativeUI$des = openGenerativeUI === null || openGenerativeUI === void 0 ? void 0 : openGenerativeUI.designSkill) !== null && _openGenerativeUI$des !== void 0 ? _openGenerativeUI$des : DEFAULT_DESIGN_SKILL;
3798
+ const designSkill = openGenerativeUI?.designSkill ?? DEFAULT_DESIGN_SKILL;
3790
3799
  (0, react.useLayoutEffect)(() => {
3791
3800
  if (!copilotkit || !openGenUIActive) return;
3792
3801
  const id = copilotkit.addContext({
@@ -3837,8 +3846,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3837
3846
  children: [
3838
3847
  runtimeA2UIEnabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIBuiltInToolCallRenderer, {}),
3839
3848
  runtimeA2UIEnabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UICatalogContext, {
3840
- catalog: a2ui === null || a2ui === void 0 ? void 0 : a2ui.catalog,
3841
- includeSchema: a2ui === null || a2ui === void 0 ? void 0 : a2ui.includeSchema
3849
+ catalog: a2ui?.catalog,
3850
+ includeSchema: a2ui?.includeSchema
3842
3851
  }),
3843
3852
  children,
3844
3853
  shouldRenderInspector ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitInspector, {
@@ -3868,11 +3877,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3868
3877
  return aHasAgent ? -1 : 1;
3869
3878
  });
3870
3879
  return function(params) {
3871
- var _copilotkit$getRunIdF;
3872
3880
  if (!customMessageRenderers.length) return null;
3873
3881
  const { message, position } = params;
3874
- const resolvedRunId = (_copilotkit$getRunIdF = copilotkit.getRunIdForMessage(agentId, threadId, message.id)) !== null && _copilotkit$getRunIdF !== void 0 ? _copilotkit$getRunIdF : copilotkit.getRunIdsForThread(agentId, threadId).slice(-1)[0];
3875
- const runId = resolvedRunId !== null && resolvedRunId !== void 0 ? resolvedRunId : `missing-run-id:${message.id}`;
3882
+ const resolvedRunId = copilotkit.getRunIdForMessage(agentId, threadId, message.id) ?? copilotkit.getRunIdsForThread(agentId, threadId).slice(-1)[0];
3883
+ const runId = resolvedRunId ?? `missing-run-id:${message.id}`;
3876
3884
  const agent = copilotkit.getAgent(agentId);
3877
3885
  if (!agent) return null;
3878
3886
  const messagesIdsInRun = resolvedRunId ? agent.messages.filter((msg) => copilotkit.getRunIdForMessage(agentId, threadId, msg.id) === resolvedRunId).map((msg) => msg.id) : [message.id];
@@ -3904,15 +3912,13 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3904
3912
  //#endregion
3905
3913
  //#region src/v2/hooks/use-render-activity-message.tsx
3906
3914
  function useRenderActivityMessage() {
3907
- var _useCopilotChatConfig, _useCopilotChatConfig2;
3908
3915
  const { copilotkit } = useCopilotKit();
3909
- const agentId = (_useCopilotChatConfig = (_useCopilotChatConfig2 = useCopilotChatConfiguration()) === null || _useCopilotChatConfig2 === void 0 ? void 0 : _useCopilotChatConfig2.agentId) !== null && _useCopilotChatConfig !== void 0 ? _useCopilotChatConfig : _copilotkit_shared.DEFAULT_AGENT_ID;
3916
+ const agentId = useCopilotChatConfiguration()?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
3910
3917
  const renderers = copilotkit.renderActivityMessages;
3911
3918
  const findRenderer = (0, react.useCallback)((activityType) => {
3912
- var _ref, _ref2, _matches$find;
3913
3919
  if (!renderers.length) return null;
3914
3920
  const matches = renderers.filter((renderer) => renderer.activityType === activityType);
3915
- return (_ref = (_ref2 = (_matches$find = matches.find((candidate) => candidate.agentId === agentId)) !== null && _matches$find !== void 0 ? _matches$find : matches.find((candidate) => candidate.agentId === void 0)) !== null && _ref2 !== void 0 ? _ref2 : renderers.find((candidate) => candidate.activityType === "*")) !== null && _ref !== void 0 ? _ref : null;
3921
+ return matches.find((candidate) => candidate.agentId === agentId) ?? matches.find((candidate) => candidate.agentId === void 0) ?? renderers.find((candidate) => candidate.activityType === "*") ?? null;
3916
3922
  }, [agentId, renderers]);
3917
3923
  const renderActivityMessage = (0, react.useCallback)((message) => {
3918
3924
  const renderer = findRenderer(message.activityType);
@@ -3946,7 +3952,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
3946
3952
  const EMPTY_DEPS = [];
3947
3953
  function useFrontendTool(tool, deps) {
3948
3954
  const { copilotkit } = useCopilotKit();
3949
- const extraDeps = deps !== null && deps !== void 0 ? deps : EMPTY_DEPS;
3955
+ const extraDeps = deps ?? EMPTY_DEPS;
3950
3956
  (0, react.useEffect)(() => {
3951
3957
  const name = tool.name;
3952
3958
  if (copilotkit.getTool({
@@ -4122,15 +4128,13 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4122
4128
  UseAgentUpdate.OnRunStatusChanged
4123
4129
  ];
4124
4130
  function useAgent({ agentId, updates, throttleMs } = {}) {
4125
- var _agentId;
4126
- (_agentId = agentId) !== null && _agentId !== void 0 || (agentId = _copilotkit_shared.DEFAULT_AGENT_ID);
4131
+ agentId ?? (agentId = _copilotkit_shared.DEFAULT_AGENT_ID);
4127
4132
  const { copilotkit } = useCopilotKit();
4128
4133
  const providerThrottleMs = copilotkit.defaultThrottleMs;
4129
4134
  const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
4130
- const updateFlags = (0, react.useMemo)(() => updates !== null && updates !== void 0 ? updates : ALL_UPDATES, [JSON.stringify(updates)]);
4135
+ const updateFlags = (0, react.useMemo)(() => updates ?? ALL_UPDATES, [JSON.stringify(updates)]);
4131
4136
  const provisionalAgentCache = (0, react.useRef)(/* @__PURE__ */ new Map());
4132
4137
  const agent = (0, react.useMemo)(() => {
4133
- var _copilotkit$agents;
4134
4138
  const existing = copilotkit.getAgent(agentId);
4135
4139
  if (existing) {
4136
4140
  provisionalAgentCache.current.delete(agentId);
@@ -4170,7 +4174,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4170
4174
  provisionalAgentCache.current.set(agentId, provisional);
4171
4175
  return provisional;
4172
4176
  }
4173
- const knownAgents = Object.keys((_copilotkit$agents = copilotkit.agents) !== null && _copilotkit$agents !== void 0 ? _copilotkit$agents : {});
4177
+ const knownAgents = Object.keys(copilotkit.agents ?? {});
4174
4178
  const runtimePart = isRuntimeConfigured ? `runtimeUrl=${copilotkit.runtimeUrl}` : "no runtimeUrl";
4175
4179
  throw new Error(`useAgent: Agent '${agentId}' 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.");
4176
4180
  }, [
@@ -4220,8 +4224,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4220
4224
  if (agent instanceof _ag_ui_client.HttpAgent) agent.headers = { ...copilotkit.headers };
4221
4225
  }, [agent, JSON.stringify(copilotkit.headers)]);
4222
4226
  const chatConfig = useCopilotChatConfiguration();
4223
- const configThreadId = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.threadId;
4224
- const configHasExplicitThreadId = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.hasExplicitThreadId;
4227
+ const configThreadId = chatConfig?.threadId;
4228
+ const configHasExplicitThreadId = chatConfig?.hasExplicitThreadId;
4225
4229
  (0, react.useEffect)(() => {
4226
4230
  if (!configHasExplicitThreadId || !configThreadId) return;
4227
4231
  agent.threadId = configThreadId;
@@ -4256,10 +4260,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4256
4260
  function useSuggestions({ agentId } = {}) {
4257
4261
  const { copilotkit } = useCopilotKit();
4258
4262
  const config = useCopilotChatConfiguration();
4259
- const resolvedAgentId = (0, react.useMemo)(() => {
4260
- var _ref;
4261
- return (_ref = agentId !== null && agentId !== void 0 ? agentId : config === null || config === void 0 ? void 0 : config.agentId) !== null && _ref !== void 0 ? _ref : _copilotkit_shared.DEFAULT_AGENT_ID;
4262
- }, [agentId, config === null || config === void 0 ? void 0 : config.agentId]);
4263
+ const resolvedAgentId = (0, react.useMemo)(() => agentId ?? config?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID, [agentId, config?.agentId]);
4263
4264
  const [suggestions, setSuggestions] = (0, react.useState)(() => {
4264
4265
  return copilotkit.getSuggestions(resolvedAgentId).suggestions;
4265
4266
  });
@@ -4312,11 +4313,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4312
4313
  function useConfigureSuggestions(config, deps) {
4313
4314
  const { copilotkit } = useCopilotKit();
4314
4315
  const chatConfig = useCopilotChatConfiguration();
4315
- const extraDeps = deps !== null && deps !== void 0 ? deps : [];
4316
- const resolvedConsumerAgentId = (0, react.useMemo)(() => {
4317
- var _chatConfig$agentId;
4318
- return (_chatConfig$agentId = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.agentId) !== null && _chatConfig$agentId !== void 0 ? _chatConfig$agentId : _copilotkit_shared.DEFAULT_AGENT_ID;
4319
- }, [chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.agentId]);
4316
+ const extraDeps = deps ?? [];
4317
+ const resolvedConsumerAgentId = (0, react.useMemo)(() => chatConfig?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID, [chatConfig?.agentId]);
4320
4318
  const rawConsumerAgentId = (0, react.useMemo)(() => config ? config.consumerAgentId : void 0, [config]);
4321
4319
  const normalizationCacheRef = (0, react.useRef)({
4322
4320
  serialized: null,
@@ -4385,9 +4383,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4385
4383
  const requestReload = (0, react.useCallback)(() => {
4386
4384
  if (!normalizedConfig) return;
4387
4385
  if (isGlobalConfig) {
4388
- var _copilotkit$agents;
4389
4386
  const seen = /* @__PURE__ */ new Set();
4390
- const agents = Object.values((_copilotkit$agents = copilotkit.agents) !== null && _copilotkit$agents !== void 0 ? _copilotkit$agents : {});
4387
+ const agents = Object.values(copilotkit.agents ?? {});
4391
4388
  for (const entry of agents) {
4392
4389
  const agentId = entry.agentId;
4393
4390
  if (!agentId) continue;
@@ -4464,13 +4461,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4464
4461
  return "instructions" in config;
4465
4462
  }
4466
4463
  function normalizeStaticSuggestions(suggestions) {
4467
- return suggestions.map((suggestion) => {
4468
- var _suggestion$isLoading;
4469
- return {
4470
- ...suggestion,
4471
- isLoading: (_suggestion$isLoading = suggestion.isLoading) !== null && _suggestion$isLoading !== void 0 ? _suggestion$isLoading : false
4472
- };
4473
- });
4464
+ return suggestions.map((suggestion) => ({
4465
+ ...suggestion,
4466
+ isLoading: suggestion.isLoading ?? false
4467
+ }));
4474
4468
  }
4475
4469
 
4476
4470
  //#endregion
@@ -4572,54 +4566,75 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4572
4566
  return () => subscription.unsubscribe();
4573
4567
  }, [agent]);
4574
4568
  const resolve = (0, react.useCallback)((response) => {
4575
- var _pendingEventRef$curr;
4576
- setPendingEvent(null);
4577
4569
  copilotkit.runAgent({
4578
4570
  agent,
4579
4571
  forwardedProps: { command: {
4580
4572
  resume: response,
4581
- interruptEvent: (_pendingEventRef$curr = pendingEventRef.current) === null || _pendingEventRef$curr === void 0 ? void 0 : _pendingEventRef$curr.value
4573
+ interruptEvent: pendingEventRef.current?.value
4582
4574
  } }
4583
4575
  });
4584
4576
  }, [agent, copilotkit]);
4577
+ const renderRef = (0, react.useRef)(config.render);
4578
+ renderRef.current = config.render;
4579
+ const enabledRef = (0, react.useRef)(config.enabled);
4580
+ enabledRef.current = config.enabled;
4581
+ const handlerRef = (0, react.useRef)(config.handler);
4582
+ handlerRef.current = config.handler;
4583
+ const resolveRef = (0, react.useRef)(resolve);
4584
+ resolveRef.current = resolve;
4585
+ const isEnabled = (event) => {
4586
+ const predicate = enabledRef.current;
4587
+ if (!predicate) return true;
4588
+ try {
4589
+ return predicate(event);
4590
+ } catch (err) {
4591
+ console.error("[CopilotKit] useInterrupt enabled predicate threw; treating interrupt as disabled:", err);
4592
+ return false;
4593
+ }
4594
+ };
4585
4595
  (0, react.useEffect)(() => {
4586
4596
  if (!pendingEvent) {
4587
4597
  setHandlerResult(null);
4588
4598
  return;
4589
4599
  }
4590
- if (config.enabled && !config.enabled(pendingEvent)) {
4600
+ if (!isEnabled(pendingEvent)) {
4591
4601
  setHandlerResult(null);
4592
4602
  return;
4593
4603
  }
4594
- const handler = config.handler;
4604
+ const handler = handlerRef.current;
4595
4605
  if (!handler) {
4596
4606
  setHandlerResult(null);
4597
4607
  return;
4598
4608
  }
4599
4609
  let cancelled = false;
4600
- const maybePromise = handler({
4601
- event: pendingEvent,
4602
- resolve
4603
- });
4610
+ let maybePromise;
4611
+ try {
4612
+ maybePromise = handler({
4613
+ event: pendingEvent,
4614
+ resolve: resolveRef.current
4615
+ });
4616
+ } catch (err) {
4617
+ console.error("[CopilotKit] useInterrupt handler threw; result will be null:", err);
4618
+ if (!cancelled) setHandlerResult(null);
4619
+ return () => {
4620
+ cancelled = true;
4621
+ };
4622
+ }
4604
4623
  if (isPromiseLike(maybePromise)) Promise.resolve(maybePromise).then((resolved) => {
4605
4624
  if (!cancelled) setHandlerResult(resolved);
4606
- }).catch(() => {
4625
+ }).catch((err) => {
4626
+ console.error("[CopilotKit] useInterrupt handler rejected; result will be null:", err);
4607
4627
  if (!cancelled) setHandlerResult(null);
4608
4628
  });
4609
4629
  else setHandlerResult(maybePromise);
4610
4630
  return () => {
4611
4631
  cancelled = true;
4612
4632
  };
4613
- }, [
4614
- pendingEvent,
4615
- config.enabled,
4616
- config.handler,
4617
- resolve
4618
- ]);
4633
+ }, [pendingEvent]);
4619
4634
  const element = (0, react.useMemo)(() => {
4620
4635
  if (!pendingEvent) return null;
4621
- if (config.enabled && !config.enabled(pendingEvent)) return null;
4622
- return config.render({
4636
+ if (!isEnabled(pendingEvent)) return null;
4637
+ return renderRef.current({
4623
4638
  event: pendingEvent,
4624
4639
  result: handlerResult,
4625
4640
  resolve
@@ -4627,19 +4642,22 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4627
4642
  }, [
4628
4643
  pendingEvent,
4629
4644
  handlerResult,
4630
- config.enabled,
4631
- config.render,
4632
4645
  resolve
4633
4646
  ]);
4634
4647
  (0, react.useEffect)(() => {
4635
4648
  if (config.renderInChat === false) return;
4636
4649
  copilotkit.setInterruptElement(element);
4637
- return () => copilotkit.setInterruptElement(null);
4638
4650
  }, [
4639
4651
  element,
4640
4652
  config.renderInChat,
4641
4653
  copilotkit
4642
4654
  ]);
4655
+ (0, react.useEffect)(() => {
4656
+ if (config.renderInChat === false) return;
4657
+ return () => {
4658
+ copilotkit.setInterruptElement(null);
4659
+ };
4660
+ }, []);
4643
4661
  if (config.renderInChat === false) return element;
4644
4662
  }
4645
4663
 
@@ -4693,7 +4711,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4693
4711
  * ```
4694
4712
  */
4695
4713
  function useThreads({ agentId, includeArchived, limit }) {
4696
- var _copilotkit$intellige2;
4697
4714
  const { copilotkit } = useCopilotKit();
4698
4715
  const [store] = (0, react.useState)(() => (0, _copilotkit_core.ɵcreateThreadStore)({ fetch: globalThis.fetch }));
4699
4716
  const coreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectThreads);
@@ -4711,8 +4728,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4711
4728
  const hasMoreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectHasNextPage);
4712
4729
  const isFetchingMoreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectIsFetchingNextPage);
4713
4730
  const headersKey = (0, react.useMemo)(() => {
4714
- var _copilotkit$headers;
4715
- return JSON.stringify(Object.entries((_copilotkit$headers = copilotkit.headers) !== null && _copilotkit$headers !== void 0 ? _copilotkit$headers : {}).sort(([left], [right]) => left.localeCompare(right)));
4731
+ return JSON.stringify(Object.entries(copilotkit.headers ?? {}).sort(([left], [right]) => left.localeCompare(right)));
4716
4732
  }, [copilotkit.headers]);
4717
4733
  const runtimeError = (0, react.useMemo)(() => {
4718
4734
  if (copilotkit.runtimeUrl) return null;
@@ -4721,7 +4737,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4721
4737
  const [hasDispatchedContext, setHasDispatchedContext] = (0, react.useState)(false);
4722
4738
  const preConnectLoading = !!copilotkit.runtimeUrl && !hasDispatchedContext;
4723
4739
  const isLoading = runtimeError ? false : preConnectLoading || storeIsLoading;
4724
- const error = runtimeError !== null && runtimeError !== void 0 ? runtimeError : storeError;
4740
+ const error = runtimeError ?? storeError;
4725
4741
  (0, react.useEffect)(() => {
4726
4742
  store.start();
4727
4743
  return () => {
@@ -4740,7 +4756,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4740
4756
  store
4741
4757
  ]);
4742
4758
  (0, react.useEffect)(() => {
4743
- var _copilotkit$intellige;
4744
4759
  if (!copilotkit.runtimeUrl) {
4745
4760
  store.setContext(null);
4746
4761
  return;
@@ -4749,7 +4764,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4749
4764
  const context = {
4750
4765
  runtimeUrl: copilotkit.runtimeUrl,
4751
4766
  headers: { ...copilotkit.headers },
4752
- wsUrl: (_copilotkit$intellige = copilotkit.intelligence) === null || _copilotkit$intellige === void 0 ? void 0 : _copilotkit$intellige.wsUrl,
4767
+ wsUrl: copilotkit.intelligence?.wsUrl,
4753
4768
  agentId,
4754
4769
  includeArchived,
4755
4770
  limit
@@ -4761,7 +4776,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4761
4776
  copilotkit.runtimeUrl,
4762
4777
  runtimeStatus,
4763
4778
  headersKey,
4764
- (_copilotkit$intellige2 = copilotkit.intelligence) === null || _copilotkit$intellige2 === void 0 ? void 0 : _copilotkit$intellige2.wsUrl,
4779
+ copilotkit.intelligence?.wsUrl,
4765
4780
  agentId,
4766
4781
  includeArchived,
4767
4782
  limit
@@ -4790,8 +4805,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4790
4805
  * renders (via useCallback) to avoid destabilizing downstream memoization.
4791
4806
  */
4792
4807
  function useAttachments({ config }) {
4793
- var _config$enabled;
4794
- const enabled = (_config$enabled = config === null || config === void 0 ? void 0 : config.enabled) !== null && _config$enabled !== void 0 ? _config$enabled : false;
4808
+ const enabled = config?.enabled ?? false;
4795
4809
  const [attachments, setAttachments] = (0, react.useState)([]);
4796
4810
  const [dragOver, setDragOver] = (0, react.useState)(false);
4797
4811
  const fileInputRef = (0, react.useRef)(null);
@@ -4801,24 +4815,19 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4801
4815
  const attachmentsRef = (0, react.useRef)([]);
4802
4816
  attachmentsRef.current = attachments;
4803
4817
  const processFiles = (0, react.useCallback)(async (files) => {
4804
- var _cfg$accept, _cfg$maxSize;
4805
4818
  const cfg = configRef.current;
4806
- const accept = (_cfg$accept = cfg === null || cfg === void 0 ? void 0 : cfg.accept) !== null && _cfg$accept !== void 0 ? _cfg$accept : "*/*";
4807
- const maxSize = (_cfg$maxSize = cfg === null || cfg === void 0 ? void 0 : cfg.maxSize) !== null && _cfg$maxSize !== void 0 ? _cfg$maxSize : 20 * 1024 * 1024;
4819
+ const accept = cfg?.accept ?? "*/*";
4820
+ const maxSize = cfg?.maxSize ?? 20 * 1024 * 1024;
4808
4821
  const rejectedFiles = files.filter((file) => !(0, _copilotkit_shared.matchesAcceptFilter)(file, accept));
4809
- for (const file of rejectedFiles) {
4810
- var _cfg$onUploadFailed;
4811
- cfg === null || cfg === void 0 || (_cfg$onUploadFailed = cfg.onUploadFailed) === null || _cfg$onUploadFailed === void 0 || _cfg$onUploadFailed.call(cfg, {
4812
- reason: "invalid-type",
4813
- file,
4814
- message: `File "${file.name}" is not accepted. Supported types: ${accept}`
4815
- });
4816
- }
4822
+ for (const file of rejectedFiles) cfg?.onUploadFailed?.({
4823
+ reason: "invalid-type",
4824
+ file,
4825
+ message: `File "${file.name}" is not accepted. Supported types: ${accept}`
4826
+ });
4817
4827
  const validFiles = files.filter((file) => (0, _copilotkit_shared.matchesAcceptFilter)(file, accept));
4818
4828
  for (const file of validFiles) {
4819
4829
  if ((0, _copilotkit_shared.exceedsMaxSize)(file, maxSize)) {
4820
- var _cfg$onUploadFailed2;
4821
- cfg === null || cfg === void 0 || (_cfg$onUploadFailed2 = cfg.onUploadFailed) === null || _cfg$onUploadFailed2 === void 0 || _cfg$onUploadFailed2.call(cfg, {
4830
+ cfg?.onUploadFailed?.({
4822
4831
  reason: "file-too-large",
4823
4832
  file,
4824
4833
  message: `File "${file.name}" exceeds the maximum size of ${(0, _copilotkit_shared.formatFileSize)(maxSize)}`
@@ -4843,7 +4852,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4843
4852
  try {
4844
4853
  let source;
4845
4854
  let uploadMetadata;
4846
- if (cfg === null || cfg === void 0 ? void 0 : cfg.onUpload) {
4855
+ if (cfg?.onUpload) {
4847
4856
  const { metadata: meta, ...uploadSource } = await cfg.onUpload(file);
4848
4857
  source = uploadSource;
4849
4858
  uploadMetadata = meta;
@@ -4862,10 +4871,9 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4862
4871
  metadata: uploadMetadata
4863
4872
  } : att));
4864
4873
  } catch (error) {
4865
- var _cfg$onUploadFailed3;
4866
4874
  setAttachments((prev) => prev.filter((att) => att.id !== placeholderId));
4867
4875
  console.error(`[CopilotKit] Failed to upload "${file.name}":`, error);
4868
- cfg === null || cfg === void 0 || (_cfg$onUploadFailed3 = cfg.onUploadFailed) === null || _cfg$onUploadFailed3 === void 0 || _cfg$onUploadFailed3.call(cfg, {
4876
+ cfg?.onUploadFailed?.({
4869
4877
  reason: "upload-failed",
4870
4878
  file,
4871
4879
  message: error instanceof Error ? error.message : `Failed to upload "${file.name}"`
@@ -4874,8 +4882,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4874
4882
  }
4875
4883
  }, []);
4876
4884
  const handleFileUpload = (0, react.useCallback)(async (e) => {
4877
- var _e$target$files;
4878
- if (!((_e$target$files = e.target.files) === null || _e$target$files === void 0 ? void 0 : _e$target$files.length)) return;
4885
+ if (!e.target.files?.length) return;
4879
4886
  try {
4880
4887
  await processFiles(Array.from(e.target.files));
4881
4888
  } catch (error) {
@@ -4883,8 +4890,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4883
4890
  }
4884
4891
  }, [processFiles]);
4885
4892
  const handleDragOver = (0, react.useCallback)((e) => {
4886
- var _configRef$current;
4887
- if (!((_configRef$current = configRef.current) === null || _configRef$current === void 0 ? void 0 : _configRef$current.enabled)) return;
4893
+ if (!configRef.current?.enabled) return;
4888
4894
  e.preventDefault();
4889
4895
  e.stopPropagation();
4890
4896
  setDragOver(true);
@@ -4895,11 +4901,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4895
4901
  setDragOver(false);
4896
4902
  }, []);
4897
4903
  const handleDrop = (0, react.useCallback)(async (e) => {
4898
- var _configRef$current2;
4899
4904
  e.preventDefault();
4900
4905
  e.stopPropagation();
4901
4906
  setDragOver(false);
4902
- if (!((_configRef$current2 = configRef.current) === null || _configRef$current2 === void 0 ? void 0 : _configRef$current2.enabled)) return;
4907
+ if (!configRef.current?.enabled) return;
4903
4908
  const files = Array.from(e.dataTransfer.files);
4904
4909
  if (files.length > 0) try {
4905
4910
  await processFiles(files);
@@ -4910,11 +4915,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4910
4915
  (0, react.useEffect)(() => {
4911
4916
  if (!enabled) return;
4912
4917
  const handlePaste = async (e) => {
4913
- var _containerRef$current, _configRef$current$ac, _configRef$current3, _e$clipboardData;
4914
4918
  const target = e.target;
4915
- if (!target || !((_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 ? void 0 : _containerRef$current.contains(target))) return;
4916
- const accept = (_configRef$current$ac = (_configRef$current3 = configRef.current) === null || _configRef$current3 === void 0 ? void 0 : _configRef$current3.accept) !== null && _configRef$current$ac !== void 0 ? _configRef$current$ac : "*/*";
4917
- const fileItems = Array.from(((_e$clipboardData = e.clipboardData) === null || _e$clipboardData === void 0 ? void 0 : _e$clipboardData.items) || []).filter((item) => item.kind === "file" && item.getAsFile() !== null && (0, _copilotkit_shared.matchesAcceptFilter)(item.getAsFile(), accept));
4919
+ if (!target || !containerRef.current?.contains(target)) return;
4920
+ const accept = configRef.current?.accept ?? "*/*";
4921
+ const fileItems = Array.from(e.clipboardData?.items || []).filter((item) => item.kind === "file" && item.getAsFile() !== null && (0, _copilotkit_shared.matchesAcceptFilter)(item.getAsFile(), accept));
4918
4922
  if (fileItems.length === 0) return;
4919
4923
  e.preventDefault();
4920
4924
  const files = fileItems.map((item) => item.getAsFile()).filter((f) => f !== null);
@@ -4968,7 +4972,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4968
4972
  //#endregion
4969
4973
  //#region src/v2/components/chat/CopilotChatAssistantMessage.tsx
4970
4974
  function CopilotChatAssistantMessage({ message, messages, isRunning, onThumbsUp, onThumbsDown, onReadAloud, onRegenerate, additionalToolbarItems, toolbarVisible = true, markdownRenderer, toolbar, copyButton, thumbsUpButton, thumbsDownButton, readAloudButton, regenerateButton, toolCallsView, children, className, ...props }) {
4971
- var _messages;
4972
4975
  useKatexStyles();
4973
4976
  const boundMarkdownRenderer = renderSlot(markdownRenderer, CopilotChatAssistantMessage.MarkdownRenderer, { content: message.content || "" });
4974
4977
  const boundCopyButton = renderSlot(copyButton, CopilotChatAssistantMessage.CopyButton, { onClick: async () => {
@@ -4995,7 +4998,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
4995
4998
  messages
4996
4999
  });
4997
5000
  const hasContent = !!(message.content && message.content.trim().length > 0);
4998
- const isLatestAssistantMessage = message.role === "assistant" && (messages === null || messages === void 0 || (_messages = messages[messages.length - 1]) === null || _messages === void 0 ? void 0 : _messages.id) === message.id;
5001
+ const isLatestAssistantMessage = message.role === "assistant" && messages?.[messages.length - 1]?.id === message.id;
4999
5002
  const shouldShowToolbar = toolbarVisible && hasContent && !(isRunning && isLatestAssistantMessage);
5000
5003
  if (children) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
5001
5004
  "data-copilotkit": true,
@@ -5040,7 +5043,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5040
5043
  _CopilotChatAssistantMessage.MarkdownRenderer = ({ content, className, ...props }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(streamdown.Streamdown, {
5041
5044
  className,
5042
5045
  ...props,
5043
- children: content !== null && content !== void 0 ? content : ""
5046
+ children: content ?? ""
5044
5047
  });
5045
5048
  _CopilotChatAssistantMessage.Toolbar = ({ className, ...props }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
5046
5049
  "data-testid": "copilot-assistant-toolbar",
@@ -5063,9 +5066,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5063
5066
  })] });
5064
5067
  };
5065
5068
  _CopilotChatAssistantMessage.CopyButton = ({ className, title, onClick, ...props }) => {
5066
- var _config$labels;
5067
- const config = useCopilotChatConfiguration();
5068
- const labels = (_config$labels = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels !== void 0 ? _config$labels : CopilotChatDefaultLabels;
5069
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
5069
5070
  const [copied, setCopied] = (0, react.useState)(false);
5070
5071
  const timerRef = (0, react.useRef)(null);
5071
5072
  (0, react.useEffect)(() => {
@@ -5095,9 +5096,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5095
5096
  });
5096
5097
  };
5097
5098
  _CopilotChatAssistantMessage.ThumbsUpButton = ({ title, ...props }) => {
5098
- var _config$labels2;
5099
- const config = useCopilotChatConfiguration();
5100
- const labels = (_config$labels2 = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels2 !== void 0 ? _config$labels2 : CopilotChatDefaultLabels;
5099
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
5101
5100
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolbarButton, {
5102
5101
  "data-testid": "copilot-thumbs-up-button",
5103
5102
  title: title || labels.assistantMessageToolbarThumbsUpLabel,
@@ -5106,9 +5105,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5106
5105
  });
5107
5106
  };
5108
5107
  _CopilotChatAssistantMessage.ThumbsDownButton = ({ title, ...props }) => {
5109
- var _config$labels3;
5110
- const config = useCopilotChatConfiguration();
5111
- const labels = (_config$labels3 = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels3 !== void 0 ? _config$labels3 : CopilotChatDefaultLabels;
5108
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
5112
5109
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolbarButton, {
5113
5110
  "data-testid": "copilot-thumbs-down-button",
5114
5111
  title: title || labels.assistantMessageToolbarThumbsDownLabel,
@@ -5117,9 +5114,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5117
5114
  });
5118
5115
  };
5119
5116
  _CopilotChatAssistantMessage.ReadAloudButton = ({ title, ...props }) => {
5120
- var _config$labels4;
5121
- const config = useCopilotChatConfiguration();
5122
- const labels = (_config$labels4 = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels4 !== void 0 ? _config$labels4 : CopilotChatDefaultLabels;
5117
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
5123
5118
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolbarButton, {
5124
5119
  "data-testid": "copilot-read-aloud-button",
5125
5120
  title: title || labels.assistantMessageToolbarReadAloudLabel,
@@ -5128,9 +5123,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5128
5123
  });
5129
5124
  };
5130
5125
  _CopilotChatAssistantMessage.RegenerateButton = ({ title, ...props }) => {
5131
- var _config$labels5;
5132
- const config = useCopilotChatConfiguration();
5133
- const labels = (_config$labels5 = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels5 !== void 0 ? _config$labels5 : CopilotChatDefaultLabels;
5126
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
5134
5127
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolbarButton, {
5135
5128
  "data-testid": "copilot-regenerate-button",
5136
5129
  title: title || labels.assistantMessageToolbarRegenerateLabel,
@@ -5267,12 +5260,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5267
5260
  });
5268
5261
  });
5269
5262
  const DocumentAttachment = (0, react.memo)(function DocumentAttachment({ source, filename, className }) {
5270
- var _source$mimeType;
5271
5263
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
5272
5264
  className: cn("cpk:inline-flex cpk:items-center cpk:gap-2 cpk:px-3 cpk:py-2 cpk:border cpk:border-border cpk:rounded-lg cpk:bg-muted", className),
5273
5265
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
5274
5266
  className: "cpk:text-xs cpk:font-bold cpk:uppercase",
5275
- children: (0, _copilotkit_shared.getDocumentIcon)((_source$mimeType = source.mimeType) !== null && _source$mimeType !== void 0 ? _source$mimeType : "")
5267
+ children: (0, _copilotkit_shared.getDocumentIcon)(source.mimeType ?? "")
5276
5268
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
5277
5269
  className: "cpk:text-sm cpk:text-muted-foreground cpk:truncate",
5278
5270
  children: filename || source.mimeType || "Unknown type"
@@ -5329,7 +5321,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5329
5321
  if (flattenedContent) return await (0, _copilotkit_shared.copyToClipboard)(flattenedContent);
5330
5322
  return false;
5331
5323
  } });
5332
- const BoundEditButton = renderSlot(editButton, CopilotChatUserMessage.EditButton, { onClick: () => onEditMessage === null || onEditMessage === void 0 ? void 0 : onEditMessage({ message }) });
5324
+ const BoundEditButton = renderSlot(editButton, CopilotChatUserMessage.EditButton, { onClick: () => onEditMessage?.({ message }) });
5333
5325
  const BoundBranchNavigation = renderSlot(branchNavigation, CopilotChatUserMessage.BranchNavigation, {
5334
5326
  currentBranch: branchIndex,
5335
5327
  numberOfBranches,
@@ -5413,9 +5405,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5413
5405
  })] });
5414
5406
  };
5415
5407
  _CopilotChatUserMessage.CopyButton = ({ className, title, onClick, ...props }) => {
5416
- var _config$labels;
5417
- const config = useCopilotChatConfiguration();
5418
- const labels = (_config$labels = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels !== void 0 ? _config$labels : CopilotChatDefaultLabels;
5408
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
5419
5409
  const [copied, setCopied] = (0, react.useState)(false);
5420
5410
  const handleClick = async (event) => {
5421
5411
  let success = false;
@@ -5435,9 +5425,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5435
5425
  });
5436
5426
  };
5437
5427
  _CopilotChatUserMessage.EditButton = ({ className, title, ...props }) => {
5438
- var _config$labels2;
5439
- const config = useCopilotChatConfiguration();
5440
- const labels = (_config$labels2 = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels2 !== void 0 ? _config$labels2 : CopilotChatDefaultLabels;
5428
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
5441
5429
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolbarButton, {
5442
5430
  "data-testid": "copilot-edit-button",
5443
5431
  title: title || labels.userMessageToolbarEditMessageLabel,
@@ -5458,7 +5446,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5458
5446
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
5459
5447
  type: "button",
5460
5448
  variant: "assistantMessageToolbarButton",
5461
- onClick: () => onSwitchToBranch === null || onSwitchToBranch === void 0 ? void 0 : onSwitchToBranch({
5449
+ onClick: () => onSwitchToBranch?.({
5462
5450
  branchIndex: currentBranch - 1,
5463
5451
  numberOfBranches,
5464
5452
  message
@@ -5478,7 +5466,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5478
5466
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
5479
5467
  type: "button",
5480
5468
  variant: "assistantMessageToolbarButton",
5481
- onClick: () => onSwitchToBranch === null || onSwitchToBranch === void 0 ? void 0 : onSwitchToBranch({
5469
+ onClick: () => onSwitchToBranch?.({
5482
5470
  branchIndex: currentBranch + 1,
5483
5471
  numberOfBranches,
5484
5472
  message
@@ -5514,8 +5502,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5514
5502
  return `${mins}m ${secs}s`;
5515
5503
  }
5516
5504
  function CopilotChatReasoningMessage({ message, messages, isRunning, header, contentView, toggle, children, className, ...props }) {
5517
- var _messages;
5518
- const isLatest = (messages === null || messages === void 0 || (_messages = messages[messages.length - 1]) === null || _messages === void 0 ? void 0 : _messages.id) === message.id;
5505
+ const isLatest = messages?.[messages.length - 1]?.id === message.id;
5519
5506
  const isStreaming = !!(isRunning && isLatest);
5520
5507
  const hasContent = !!(message.content && message.content.length > 0);
5521
5508
  const startTimeRef = (0, react.useRef)(null);
@@ -5645,7 +5632,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5645
5632
  "data-testid": "copilot-suggestion",
5646
5633
  "data-slot": "suggestion-pill",
5647
5634
  className: cn(baseClasses, className),
5648
- type: type !== null && type !== void 0 ? type : "button",
5635
+ type: type ?? "button",
5649
5636
  "aria-busy": isLoading || void 0,
5650
5637
  disabled: isLoading || props.disabled,
5651
5638
  ...props,
@@ -5694,16 +5681,15 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5694
5681
  className: suggestion.className,
5695
5682
  isLoading,
5696
5683
  type: "button",
5697
- onClick: () => onSelectSuggestion === null || onSelectSuggestion === void 0 ? void 0 : onSelectSuggestion(suggestion, index)
5684
+ onClick: () => onSelectSuggestion?.(suggestion, index)
5698
5685
  });
5699
5686
  return react.default.cloneElement(pill, { key: `${suggestion.title}-${index}` });
5700
5687
  });
5701
5688
  const boundContainer = react.default.cloneElement(ContainerElement, void 0, suggestionElements);
5702
5689
  if (typeof children === "function") {
5703
- var _suggestions$0$title, _suggestions$, _suggestions$2;
5704
5690
  const sampleSuggestion = renderSlot(suggestionSlot, CopilotChatSuggestionPill, {
5705
- children: (_suggestions$0$title = (_suggestions$ = suggestions[0]) === null || _suggestions$ === void 0 ? void 0 : _suggestions$.title) !== null && _suggestions$0$title !== void 0 ? _suggestions$0$title : "",
5706
- isLoading: suggestions.length > 0 ? loadingSet.has(0) || ((_suggestions$2 = suggestions[0]) === null || _suggestions$2 === void 0 ? void 0 : _suggestions$2.isLoading) === true : false,
5691
+ children: suggestions[0]?.title ?? "",
5692
+ isLoading: suggestions.length > 0 ? loadingSet.has(0) || suggestions[0]?.isLoading === true : false,
5707
5693
  type: "button"
5708
5694
  });
5709
5695
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
@@ -5835,10 +5821,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5835
5821
  if (message.role !== "assistant") return [];
5836
5822
  const tcs = Array.isArray(message.toolCalls) ? message.toolCalls : [];
5837
5823
  const ids = [];
5838
- for (const tc of tcs) {
5839
- var _tc$function;
5840
- if (isMatchingToolCallName(tc === null || tc === void 0 || (_tc$function = tc.function) === null || _tc$function === void 0 ? void 0 : _tc$function.name) && (tc === null || tc === void 0 ? void 0 : tc.id)) ids.push(tc.id);
5841
- }
5824
+ for (const tc of tcs) if (isMatchingToolCallName(tc?.function?.name) && tc?.id) ids.push(tc.id);
5842
5825
  return ids;
5843
5826
  }, [message]);
5844
5827
  const hasPending = (0, react.useMemo)(() => {
@@ -5882,18 +5865,12 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5882
5865
  if (!config) return null;
5883
5866
  if (phase === "idle" || phase === "hidden") return null;
5884
5867
  if (message.role !== "assistant") return null;
5885
- if (!(Array.isArray(message.toolCalls) ? message.toolCalls : []).some((tc) => {
5886
- var _tc$function2;
5887
- return isMatchingToolCallName(tc === null || tc === void 0 || (_tc$function2 = tc.function) === null || _tc$function2 === void 0 ? void 0 : _tc$function2.name);
5888
- })) return null;
5868
+ if (!(Array.isArray(message.toolCalls) ? message.toolCalls : []).some((tc) => isMatchingToolCallName(tc?.function?.name))) return null;
5889
5869
  let latestMatchingAssistantId;
5890
5870
  for (let i = agent.messages.length - 1; i >= 0; i -= 1) {
5891
5871
  const m = agent.messages[i];
5892
5872
  if (m.role !== "assistant") continue;
5893
- if ((Array.isArray(m.toolCalls) ? m.toolCalls : []).some((tc) => {
5894
- var _tc$function3;
5895
- return isMatchingToolCallName(tc === null || tc === void 0 || (_tc$function3 = tc.function) === null || _tc$function3 === void 0 ? void 0 : _tc$function3.name);
5896
- })) {
5873
+ if ((Array.isArray(m.toolCalls) ? m.toolCalls : []).some((tc) => isMatchingToolCallName(tc?.function?.name))) {
5897
5874
  latestMatchingAssistantId = m.id;
5898
5875
  break;
5899
5876
  }
@@ -5969,12 +5946,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5969
5946
  ...slotProps
5970
5947
  });
5971
5948
  }, (prevProps, nextProps) => {
5972
- var _nextProps$messages;
5973
5949
  if (prevProps.message.id !== nextProps.message.id) return false;
5974
5950
  if (prevProps.message.content !== nextProps.message.content) return false;
5975
5951
  const prevToolCalls = prevProps.message.toolCalls;
5976
5952
  const nextToolCalls = nextProps.message.toolCalls;
5977
- if ((prevToolCalls === null || prevToolCalls === void 0 ? void 0 : prevToolCalls.length) !== (nextToolCalls === null || nextToolCalls === void 0 ? void 0 : nextToolCalls.length)) return false;
5953
+ if (prevToolCalls?.length !== nextToolCalls?.length) return false;
5978
5954
  if (prevToolCalls && nextToolCalls) for (let i = 0; i < prevToolCalls.length; i++) {
5979
5955
  const prevTc = prevToolCalls[i];
5980
5956
  const nextTc = nextToolCalls[i];
@@ -5988,7 +5964,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5988
5964
  if (prevToolResults.length !== nextToolResults.length) return false;
5989
5965
  for (let i = 0; i < prevToolResults.length; i++) if (prevToolResults[i].content !== nextToolResults[i].content) return false;
5990
5966
  }
5991
- if (((_nextProps$messages = nextProps.messages[nextProps.messages.length - 1]) === null || _nextProps$messages === void 0 ? void 0 : _nextProps$messages.id) === nextProps.message.id && prevProps.isRunning !== nextProps.isRunning) return false;
5967
+ if (nextProps.messages[nextProps.messages.length - 1]?.id === nextProps.message.id && prevProps.isRunning !== nextProps.isRunning) return false;
5992
5968
  if (prevProps.AssistantMessageComponent !== nextProps.AssistantMessageComponent) return false;
5993
5969
  if (prevProps.slotProps !== nextProps.slotProps) return false;
5994
5970
  return true;
@@ -6030,11 +6006,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6030
6006
  ...slotProps
6031
6007
  });
6032
6008
  }, (prevProps, nextProps) => {
6033
- var _prevProps$messages, _nextProps$messages2;
6034
6009
  if (prevProps.message.id !== nextProps.message.id) return false;
6035
6010
  if (prevProps.message.content !== nextProps.message.content) return false;
6036
- const prevIsLatest = ((_prevProps$messages = prevProps.messages[prevProps.messages.length - 1]) === null || _prevProps$messages === void 0 ? void 0 : _prevProps$messages.id) === prevProps.message.id;
6037
- const nextIsLatest = ((_nextProps$messages2 = nextProps.messages[nextProps.messages.length - 1]) === null || _nextProps$messages2 === void 0 ? void 0 : _nextProps$messages2.id) === nextProps.message.id;
6011
+ const prevIsLatest = prevProps.messages[prevProps.messages.length - 1]?.id === prevProps.message.id;
6012
+ const nextIsLatest = nextProps.messages[nextProps.messages.length - 1]?.id === nextProps.message.id;
6038
6013
  if (prevIsLatest !== nextIsLatest) return false;
6039
6014
  if (nextIsLatest && prevProps.isRunning !== nextProps.isRunning) return false;
6040
6015
  if (prevProps.ReasoningMessageComponent !== nextProps.ReasoningMessageComponent) return false;
@@ -6072,9 +6047,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6072
6047
  for (const message of messages) {
6073
6048
  const existing = acc.get(message.id);
6074
6049
  if (existing && message.role === "assistant" && existing.role === "assistant") {
6075
- var _message$toolCalls;
6076
6050
  const content = message.content || existing.content;
6077
- const toolCalls = (_message$toolCalls = message.toolCalls) !== null && _message$toolCalls !== void 0 ? _message$toolCalls : existing.toolCalls;
6051
+ const toolCalls = message.toolCalls ?? existing.toolCalls;
6078
6052
  acc.set(message.id, {
6079
6053
  ...existing,
6080
6054
  ...message,
@@ -6087,20 +6061,19 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6087
6061
  }
6088
6062
  const VIRTUALIZE_THRESHOLD = 50;
6089
6063
  function CopilotChatMessageView({ messages = [], assistantMessage, userMessage, reasoningMessage, cursor, isRunning = false, children, className, ...props }) {
6090
- var _deduplicatedMessages;
6091
6064
  const renderCustomMessage = useRenderCustomMessages();
6092
6065
  const { renderActivityMessage } = useRenderActivityMessage();
6093
6066
  const { copilotkit } = useCopilotKit();
6094
6067
  const config = useCopilotChatConfiguration();
6095
6068
  const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
6096
6069
  (0, react.useEffect)(() => {
6097
- if (!(config === null || config === void 0 ? void 0 : config.agentId)) return;
6070
+ if (!config?.agentId) return;
6098
6071
  const agent = copilotkit.getAgent(config.agentId);
6099
6072
  if (!agent) return;
6100
6073
  const subscription = agent.subscribe({ onStateChanged: forceUpdate });
6101
6074
  return () => subscription.unsubscribe();
6102
6075
  }, [
6103
- config === null || config === void 0 ? void 0 : config.agentId,
6076
+ config?.agentId,
6104
6077
  copilotkit,
6105
6078
  forceUpdate
6106
6079
  ]);
@@ -6113,9 +6086,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6113
6086
  return () => subscription.unsubscribe();
6114
6087
  }, [copilotkit]);
6115
6088
  const getStateSnapshotForMessage = (messageId) => {
6116
- var _copilotkit$getRunIdF;
6117
6089
  if (!config) return void 0;
6118
- const resolvedRunId = (_copilotkit$getRunIdF = copilotkit.getRunIdForMessage(config.agentId, config.threadId, messageId)) !== null && _copilotkit$getRunIdF !== void 0 ? _copilotkit$getRunIdF : copilotkit.getRunIdsForThread(config.agentId, config.threadId).slice(-1)[0];
6090
+ const resolvedRunId = copilotkit.getRunIdForMessage(config.agentId, config.threadId, messageId) ?? copilotkit.getRunIdsForThread(config.agentId, config.threadId).slice(-1)[0];
6119
6091
  if (!resolvedRunId) return void 0;
6120
6092
  return copilotkit.getStateByRun(config.agentId, config.threadId, resolvedRunId);
6121
6093
  };
@@ -6135,19 +6107,17 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6135
6107
  getScrollElement: () => scrollElement,
6136
6108
  estimateSize: () => 100,
6137
6109
  overscan: 5,
6138
- measureElement: (el) => {
6139
- var _el$getBoundingClient;
6140
- return (_el$getBoundingClient = el === null || el === void 0 ? void 0 : el.getBoundingClientRect().height) !== null && _el$getBoundingClient !== void 0 ? _el$getBoundingClient : 0;
6141
- },
6110
+ measureElement: (el) => el?.getBoundingClientRect().height ?? 0,
6142
6111
  initialRect: {
6143
6112
  width: 0,
6144
6113
  height: 600
6145
6114
  }
6146
6115
  });
6116
+ const firstMessageId = deduplicatedMessages[0]?.id;
6147
6117
  (0, react.useLayoutEffect)(() => {
6148
6118
  if (!shouldVirtualize || !deduplicatedMessages.length) return;
6149
6119
  virtualizer.scrollToIndex(deduplicatedMessages.length - 1, { align: "end" });
6150
- }, [shouldVirtualize, (_deduplicatedMessages = deduplicatedMessages[0]) === null || _deduplicatedMessages === void 0 ? void 0 : _deduplicatedMessages.id]);
6120
+ }, [shouldVirtualize, firstMessageId]);
6151
6121
  const renderMessageBlock = (message) => {
6152
6122
  const elements = [];
6153
6123
  const stateSnapshot = getStateSnapshotForMessage(message.id);
@@ -6186,13 +6156,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6186
6156
  renderCustomMessage,
6187
6157
  stateSnapshot
6188
6158
  }, `${message.id}-custom-after`));
6189
- if (copilotkit.intelligence !== void 0 && message.role === "assistant") {
6190
- var _config$agentId;
6191
- elements.push(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(IntelligenceIndicator, {
6192
- message,
6193
- agentId: (_config$agentId = config === null || config === void 0 ? void 0 : config.agentId) !== null && _config$agentId !== void 0 ? _config$agentId : _copilotkit_shared.DEFAULT_AGENT_ID
6194
- }, `${message.id}-intelligence`));
6195
- }
6159
+ if (copilotkit.intelligence !== void 0 && message.role === "assistant") elements.push(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(IntelligenceIndicator, {
6160
+ message,
6161
+ agentId: config?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID
6162
+ }, `${message.id}-intelligence`));
6196
6163
  return elements.filter(Boolean);
6197
6164
  };
6198
6165
  const messageElements = shouldVirtualize ? [] : deduplicatedMessages.flatMap(renderMessageBlock);
@@ -6207,7 +6174,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6207
6174
  })
6208
6175
  });
6209
6176
  const lastMessage = messages[messages.length - 1];
6210
- const showCursor = isRunning && (lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.role) !== "reasoning";
6177
+ const showCursor = isRunning && lastMessage?.role !== "reasoning";
6211
6178
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
6212
6179
  "data-copilotkit": true,
6213
6180
  "data-testid": "copilot-message-list",
@@ -6416,7 +6383,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6416
6383
  const textContent = attachment.source.type === "data" ? (() => {
6417
6384
  try {
6418
6385
  return atob(attachment.source.value);
6419
- } catch (_unused) {
6386
+ } catch {
6420
6387
  return attachment.source.value;
6421
6388
  }
6422
6389
  })() : null;
@@ -6442,7 +6409,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6442
6409
  children: [
6443
6410
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
6444
6411
  className: "cpk:w-16 cpk:h-16 cpk:rounded-xl cpk:bg-primary cpk:text-primary-foreground cpk:flex cpk:items-center cpk:justify-center cpk:text-xl cpk:font-bold",
6445
- children: (0, _copilotkit_shared.getDocumentIcon)(mimeType !== null && mimeType !== void 0 ? mimeType : "")
6412
+ children: (0, _copilotkit_shared.getDocumentIcon)(mimeType ?? "")
6446
6413
  }),
6447
6414
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
6448
6415
  className: "cpk:text-center",
@@ -6471,7 +6438,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6471
6438
  onClick: previewable ? openLightbox : void 0,
6472
6439
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
6473
6440
  className: "cpk:w-8 cpk:h-8 cpk:rounded-md cpk:bg-primary cpk:text-primary-foreground cpk:flex cpk:items-center cpk:justify-center cpk:text-[10px] cpk:font-semibold cpk:shrink-0",
6474
- children: (0, _copilotkit_shared.getDocumentIcon)(mimeType !== null && mimeType !== void 0 ? mimeType : "")
6441
+ children: (0, _copilotkit_shared.getDocumentIcon)(mimeType ?? "")
6475
6442
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
6476
6443
  className: "cpk:flex cpk:flex-col cpk:min-w-0",
6477
6444
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
@@ -6731,13 +6698,13 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6731
6698
  className: "cpk:w-full",
6732
6699
  children: [attachments && attachments.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatAttachmentQueue, {
6733
6700
  attachments,
6734
- onRemoveAttachment: (id) => onRemoveAttachment === null || onRemoveAttachment === void 0 ? void 0 : onRemoveAttachment(id),
6701
+ onRemoveAttachment: (id) => onRemoveAttachment?.(id),
6735
6702
  className: "cpk:mb-2"
6736
6703
  }), BoundInputForWelcome]
6737
6704
  });
6738
6705
  const BoundWelcomeScreen = renderSlot(welcomeScreenSlot, CopilotChatView.WelcomeScreen, {
6739
6706
  input: inputWithAttachments,
6740
- suggestionView: BoundSuggestionView !== null && BoundSuggestionView !== void 0 ? BoundSuggestionView : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {})
6707
+ suggestionView: BoundSuggestionView ?? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {})
6741
6708
  });
6742
6709
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
6743
6710
  "data-copilotkit": true,
@@ -6758,7 +6725,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6758
6725
  messageView: BoundMessageView,
6759
6726
  input: BoundInput,
6760
6727
  scrollView: BoundScrollView,
6761
- suggestionView: BoundSuggestionView !== null && BoundSuggestionView !== void 0 ? BoundSuggestionView : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {})
6728
+ suggestionView: BoundSuggestionView ?? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {})
6762
6729
  })
6763
6730
  });
6764
6731
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
@@ -6781,7 +6748,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6781
6748
  className: "cpk:max-w-3xl cpk:mx-auto cpk:w-full cpk:pointer-events-auto",
6782
6749
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatAttachmentQueue, {
6783
6750
  attachments,
6784
- onRemoveAttachment: (id) => onRemoveAttachment === null || onRemoveAttachment === void 0 ? void 0 : onRemoveAttachment(id),
6751
+ onRemoveAttachment: (id) => onRemoveAttachment?.(id),
6785
6752
  className: "cpk:px-4"
6786
6753
  })
6787
6754
  }), BoundInput]
@@ -6794,8 +6761,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6794
6761
  const { isAtBottom, scrollToBottom, scrollRef } = (0, use_stick_to_bottom.useStickToBottomContext)();
6795
6762
  const [scrollEl, setScrollEl] = (0, react.useState)(null);
6796
6763
  (0, react.useLayoutEffect)(() => {
6797
- var _scrollRef$current;
6798
- setScrollEl((_scrollRef$current = scrollRef.current) !== null && _scrollRef$current !== void 0 ? _scrollRef$current : null);
6764
+ setScrollEl(scrollRef.current ?? null);
6799
6765
  }, []);
6800
6766
  const BoundFeather = renderSlot(feather, CopilotChatView.Feather, {});
6801
6767
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ScrollElementContext.Provider, {
@@ -6973,9 +6939,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
6973
6939
  ...props
6974
6940
  });
6975
6941
  _CopilotChatView.WelcomeMessage = ({ className, ...props }) => {
6976
- var _config$labels;
6977
- const config = useCopilotChatConfiguration();
6978
- const labels = (_config$labels = config === null || config === void 0 ? void 0 : config.labels) !== null && _config$labels !== void 0 ? _config$labels : CopilotChatDefaultLabels;
6942
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
6979
6943
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h1", {
6980
6944
  className: cn("cpk:text-xl cpk:sm:text-2xl cpk:font-medium cpk:text-foreground cpk:text-center", className),
6981
6945
  ...props,
@@ -7031,7 +6995,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7031
6995
  const reader = new FileReader();
7032
6996
  reader.onloadend = () => {
7033
6997
  const base64 = reader.result.split(",")[1];
7034
- resolve(base64 !== null && base64 !== void 0 ? base64 : "");
6998
+ resolve(base64 ?? "");
7035
6999
  };
7036
7000
  reader.onerror = () => reject(/* @__PURE__ */ new Error("Failed to read audio data"));
7037
7001
  reader.readAsDataURL(blob);
@@ -7047,11 +7011,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7047
7011
  * Parse error info from a transcription error response
7048
7012
  */
7049
7013
  function parseTranscriptionError(response) {
7050
- var _response$retryable;
7051
7014
  return {
7052
7015
  code: response.error,
7053
7016
  message: response.message,
7054
- retryable: (_response$retryable = response.retryable) !== null && _response$retryable !== void 0 ? _response$retryable : false
7017
+ retryable: response.retryable ?? false
7055
7018
  };
7056
7019
  }
7057
7020
  /**
@@ -7118,7 +7081,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7118
7081
  let errorData;
7119
7082
  try {
7120
7083
  errorData = await response.json();
7121
- } catch (_unused) {
7084
+ } catch {
7122
7085
  throw new TranscriptionError({
7123
7086
  code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
7124
7087
  message: `HTTP ${response.status}: ${response.statusText}`,
@@ -7138,12 +7101,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7138
7101
  //#endregion
7139
7102
  //#region src/v2/components/chat/CopilotChat.tsx
7140
7103
  function CopilotChat({ agentId, threadId, labels, chatView, isModalDefaultOpen, attachments: attachmentsConfig, onError, throttleMs, ...props }) {
7141
- var _ref, _attachmentsConfig$ac;
7142
7104
  const existingConfig = useCopilotChatConfiguration();
7143
- const resolvedAgentId = (_ref = agentId !== null && agentId !== void 0 ? agentId : existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.agentId) !== null && _ref !== void 0 ? _ref : _copilotkit_shared.DEFAULT_AGENT_ID;
7144
- const providedThreadId = threadId !== null && threadId !== void 0 ? threadId : existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.threadId;
7145
- const resolvedThreadId = (0, react.useMemo)(() => providedThreadId !== null && providedThreadId !== void 0 ? providedThreadId : (0, _copilotkit_shared.randomUUID)(), [providedThreadId]);
7146
- const hasExplicitThreadId = !!threadId || !!(existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.hasExplicitThreadId);
7105
+ const resolvedAgentId = agentId ?? existingConfig?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
7106
+ const providedThreadId = threadId ?? existingConfig?.threadId;
7107
+ const resolvedThreadId = (0, react.useMemo)(() => providedThreadId ?? (0, _copilotkit_shared.randomUUID)(), [providedThreadId]);
7108
+ const hasExplicitThreadId = !!threadId || !!existingConfig?.hasExplicitThreadId;
7147
7109
  const { agent } = useAgent({
7148
7110
  agentId: resolvedAgentId,
7149
7111
  throttleMs
@@ -7162,15 +7124,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7162
7124
  (0, react.useEffect)(() => {
7163
7125
  if (!onErrorRef.current) return;
7164
7126
  const subscription = copilotkit.subscribe({ onError: (event) => {
7165
- var _event$context, _event$context2;
7166
- if (((_event$context = event.context) === null || _event$context === void 0 ? void 0 : _event$context.agentId) === resolvedAgentId || !((_event$context2 = event.context) === null || _event$context2 === void 0 ? void 0 : _event$context2.agentId)) {
7167
- var _onErrorRef$current;
7168
- (_onErrorRef$current = onErrorRef.current) === null || _onErrorRef$current === void 0 || _onErrorRef$current.call(onErrorRef, {
7169
- error: event.error,
7170
- code: event.code,
7171
- context: event.context
7172
- });
7173
- }
7127
+ if (event.context?.agentId === resolvedAgentId || !event.context?.agentId) onErrorRef.current?.({
7128
+ error: event.error,
7129
+ code: event.code,
7130
+ context: event.context
7131
+ });
7174
7132
  } });
7175
7133
  return () => {
7176
7134
  subscription.unsubscribe();
@@ -7347,8 +7305,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7347
7305
  const stableSuggestionView = useShallowStableRef(providedSuggestionView);
7348
7306
  const handleAddFile = (0, react.useCallback)(() => {
7349
7307
  setTimeout(() => {
7350
- var _fileInputRef$current;
7351
- (_fileInputRef$current = fileInputRef.current) === null || _fileInputRef$current === void 0 || _fileInputRef$current.click();
7308
+ fileInputRef.current?.click();
7352
7309
  }, 100);
7353
7310
  }, []);
7354
7311
  const mergedProps = {
@@ -7360,15 +7317,12 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7360
7317
  };
7361
7318
  if (stableMessageView !== void 0) mergedProps.messageView = stableMessageView;
7362
7319
  const hasMessages = agent.messages.length > 0;
7363
- const effectiveStopHandler = agent.isRunning && hasMessages ? providedStopHandler !== null && providedStopHandler !== void 0 ? providedStopHandler : stopCurrentRun : providedStopHandler;
7320
+ const effectiveStopHandler = agent.isRunning && hasMessages ? providedStopHandler ?? stopCurrentRun : providedStopHandler;
7364
7321
  const showTranscription = isTranscriptionEnabled && isMediaRecorderSupported;
7365
7322
  const effectiveMode = isTranscribing ? "processing" : transcribeMode;
7366
7323
  const messages = (0, react.useMemo)(() => [...agent.messages], [agent.messages.map((m) => {
7367
7324
  const contentKey = typeof m.content === "string" ? m.content.length : Array.isArray(m.content) ? m.content.length : 0;
7368
- const toolCallsKey = "toolCalls" in m && Array.isArray(m.toolCalls) ? m.toolCalls.map((tc) => {
7369
- var _tc$function$argument, _tc$function;
7370
- return `${tc.id}:${(_tc$function$argument = (_tc$function = tc.function) === null || _tc$function === void 0 || (_tc$function = _tc$function.arguments) === null || _tc$function === void 0 ? void 0 : _tc$function.length) !== null && _tc$function$argument !== void 0 ? _tc$function$argument : 0}`;
7371
- }).join(";") : "";
7325
+ const toolCallsKey = "toolCalls" in m && Array.isArray(m.toolCalls) ? m.toolCalls.map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`).join(";") : "";
7372
7326
  return `${m.id}:${m.role}:${contentKey}:${toolCallsKey}`;
7373
7327
  }).join(",")]);
7374
7328
  const lastUserMessageId = (0, react.useMemo)(() => {
@@ -7424,7 +7378,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7424
7378
  multiple: true,
7425
7379
  ref: fileInputRef,
7426
7380
  onChange: handleFileUpload,
7427
- accept: (_attachmentsConfig$ac = attachmentsConfig === null || attachmentsConfig === void 0 ? void 0 : attachmentsConfig.accept) !== null && _attachmentsConfig$ac !== void 0 ? _attachmentsConfig$ac : "*/*",
7381
+ accept: attachmentsConfig?.accept ?? "*/*",
7428
7382
  style: { display: "none" }
7429
7383
  }),
7430
7384
  !isChatLicensed && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(InlineFeatureWarning, { featureName: "Chat" }),
@@ -7474,13 +7428,12 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7474
7428
  const ICON_WRAPPER_BASE = "cpk:pointer-events-none cpk:absolute cpk:inset-0 cpk:flex cpk:items-center cpk:justify-center cpk:will-change-transform";
7475
7429
  const BUTTON_BASE_CLASSES = cn("copilotKitButton", "cpk:fixed cpk:bottom-6 cpk:right-6 cpk:z-[1100] cpk:flex cpk:h-14 cpk:w-14 cpk:items-center cpk:justify-center", "cpk:rounded-full cpk:border cpk:border-primary cpk:bg-primary cpk:text-primary-foreground", "cpk:shadow-sm cpk:transition-all cpk:duration-200 cpk:ease-out", "cpk:hover:scale-[1.04] cpk:hover:shadow-md", "cpk:cursor-pointer", "cpk:active:scale-[0.96]", "cpk:focus-visible:outline-none cpk:focus-visible:ring-2 cpk:focus-visible:ring-primary/50 cpk:focus-visible:ring-offset-2 cpk:focus-visible:ring-offset-background", "cpk:disabled:pointer-events-none cpk:disabled:opacity-60");
7476
7430
  const CopilotChatToggleButton = react.default.forwardRef(function CopilotChatToggleButton({ openIcon, closeIcon, className, ...buttonProps }, ref) {
7477
- var _configuration$labels, _configuration$isModa, _configuration$setMod;
7478
7431
  const { onClick, type, disabled, ...restProps } = buttonProps;
7479
7432
  const configuration = useCopilotChatConfiguration();
7480
- const labels = (_configuration$labels = configuration === null || configuration === void 0 ? void 0 : configuration.labels) !== null && _configuration$labels !== void 0 ? _configuration$labels : CopilotChatDefaultLabels;
7433
+ const labels = configuration?.labels ?? CopilotChatDefaultLabels;
7481
7434
  const [fallbackOpen, setFallbackOpen] = (0, react.useState)(false);
7482
- const isOpen = (_configuration$isModa = configuration === null || configuration === void 0 ? void 0 : configuration.isModalOpen) !== null && _configuration$isModa !== void 0 ? _configuration$isModa : fallbackOpen;
7483
- const setModalOpen = (_configuration$setMod = configuration === null || configuration === void 0 ? void 0 : configuration.setModalOpen) !== null && _configuration$setMod !== void 0 ? _configuration$setMod : setFallbackOpen;
7435
+ const isOpen = configuration?.isModalOpen ?? fallbackOpen;
7436
+ const setModalOpen = configuration?.setModalOpen ?? setFallbackOpen;
7484
7437
  const handleClick = (event) => {
7485
7438
  if (disabled) return;
7486
7439
  if (onClick) onClick(event);
@@ -7521,7 +7474,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7521
7474
  });
7522
7475
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
7523
7476
  ref,
7524
- type: type !== null && type !== void 0 ? type : "button",
7477
+ type: type ?? "button",
7525
7478
  "data-copilotkit": true,
7526
7479
  "data-testid": "copilot-chat-toggle",
7527
7480
  "data-slot": "chat-toggle-button",
@@ -7540,13 +7493,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7540
7493
  //#endregion
7541
7494
  //#region src/v2/components/chat/CopilotModalHeader.tsx
7542
7495
  function CopilotModalHeader({ title, titleContent, closeButton, children, className, ...rest }) {
7543
- var _configuration$labels;
7544
7496
  const configuration = useCopilotChatConfiguration();
7545
- const fallbackTitle = (_configuration$labels = configuration === null || configuration === void 0 ? void 0 : configuration.labels.modalHeaderTitle) !== null && _configuration$labels !== void 0 ? _configuration$labels : CopilotChatDefaultLabels.modalHeaderTitle;
7546
- const resolvedTitle = title !== null && title !== void 0 ? title : fallbackTitle;
7497
+ const fallbackTitle = configuration?.labels.modalHeaderTitle ?? CopilotChatDefaultLabels.modalHeaderTitle;
7498
+ const resolvedTitle = title ?? fallbackTitle;
7547
7499
  const handleClose = (0, react.useCallback)(() => {
7548
- var _configuration$setMod;
7549
- configuration === null || configuration === void 0 || (_configuration$setMod = configuration.setModalOpen) === null || _configuration$setMod === void 0 || _configuration$setMod.call(configuration, false);
7500
+ configuration?.setModalOpen?.(false);
7550
7501
  }, [configuration]);
7551
7502
  const BoundTitle = renderSlot(titleContent, CopilotModalHeader.Title, { children: resolvedTitle });
7552
7503
  const BoundCloseButton = renderSlot(closeButton, CopilotModalHeader.CloseButton, { onClick: handleClose });
@@ -7620,11 +7571,9 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7620
7571
  });
7621
7572
  }
7622
7573
  function CopilotSidebarViewInternal({ header, toggleButton, width, position = "right", ...props }) {
7623
- var _configuration$isModa;
7624
- const configuration = useCopilotChatConfiguration();
7625
- const isSidebarOpen = (_configuration$isModa = configuration === null || configuration === void 0 ? void 0 : configuration.isModalOpen) !== null && _configuration$isModa !== void 0 ? _configuration$isModa : false;
7574
+ const isSidebarOpen = useCopilotChatConfiguration()?.isModalOpen ?? false;
7626
7575
  const sidebarRef = (0, react.useRef)(null);
7627
- const [sidebarWidth, setSidebarWidth] = (0, react.useState)(width !== null && width !== void 0 ? width : DEFAULT_SIDEBAR_WIDTH);
7576
+ const [sidebarWidth, setSidebarWidth] = (0, react.useState)(width ?? DEFAULT_SIDEBAR_WIDTH);
7628
7577
  const widthToCss = (w) => {
7629
7578
  return typeof w === "number" ? `${w}px` : w;
7630
7579
  };
@@ -7758,11 +7707,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7758
7707
  });
7759
7708
  }
7760
7709
  function CopilotPopupViewInternal({ header, toggleButton, width, height, clickOutsideToClose, className, ...restProps }) {
7761
- var _configuration$isModa, _configuration$labels;
7762
7710
  const configuration = useCopilotChatConfiguration();
7763
- const isPopupOpen = (_configuration$isModa = configuration === null || configuration === void 0 ? void 0 : configuration.isModalOpen) !== null && _configuration$isModa !== void 0 ? _configuration$isModa : false;
7764
- const setModalOpen = configuration === null || configuration === void 0 ? void 0 : configuration.setModalOpen;
7765
- const labels = (_configuration$labels = configuration === null || configuration === void 0 ? void 0 : configuration.labels) !== null && _configuration$labels !== void 0 ? _configuration$labels : CopilotChatDefaultLabels;
7711
+ const isPopupOpen = configuration?.isModalOpen ?? false;
7712
+ const setModalOpen = configuration?.setModalOpen;
7713
+ const labels = configuration?.labels ?? CopilotChatDefaultLabels;
7766
7714
  const containerRef = (0, react.useRef)(null);
7767
7715
  const [isRendered, setIsRendered] = (0, react.useState)(isPopupOpen);
7768
7716
  const [isAnimatingOut, setIsAnimatingOut] = (0, react.useState)(false);
@@ -7786,7 +7734,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7786
7734
  const handleKeyDown = (event) => {
7787
7735
  if (event.key === "Escape") {
7788
7736
  event.preventDefault();
7789
- setModalOpen === null || setModalOpen === void 0 || setModalOpen(false);
7737
+ setModalOpen?.(false);
7790
7738
  }
7791
7739
  };
7792
7740
  window.addEventListener("keydown", handleKeyDown);
@@ -7806,11 +7754,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7806
7754
  const handlePointerDown = (event) => {
7807
7755
  const target = event.target;
7808
7756
  if (!target) return;
7809
- const container = containerRef.current;
7810
- if (container === null || container === void 0 ? void 0 : container.contains(target)) return;
7757
+ if (containerRef.current?.contains(target)) return;
7811
7758
  const toggleButton = document.querySelector("[data-slot='chat-toggle-button']");
7812
7759
  if (toggleButton && toggleButton.contains(target)) return;
7813
- setModalOpen === null || setModalOpen === void 0 || setModalOpen(false);
7760
+ setModalOpen?.(false);
7814
7761
  };
7815
7762
  document.addEventListener("pointerdown", handlePointerDown);
7816
7763
  return () => document.removeEventListener("pointerdown", handlePointerDown);
@@ -7900,11 +7847,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7900
7847
  const { header: viewHeader, toggleButton: viewToggleButton, width: viewWidth, defaultOpen: viewDefaultOpen, position: viewPosition, ...restProps } = viewProps;
7901
7848
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotSidebarView, {
7902
7849
  ...restProps,
7903
- header: header !== null && header !== void 0 ? header : viewHeader,
7904
- toggleButton: toggleButton !== null && toggleButton !== void 0 ? toggleButton : viewToggleButton,
7905
- width: width !== null && width !== void 0 ? width : viewWidth,
7906
- defaultOpen: defaultOpen !== null && defaultOpen !== void 0 ? defaultOpen : viewDefaultOpen,
7907
- position: position !== null && position !== void 0 ? position : viewPosition
7850
+ header: header ?? viewHeader,
7851
+ toggleButton: toggleButton ?? viewToggleButton,
7852
+ width: width ?? viewWidth,
7853
+ defaultOpen: defaultOpen ?? viewDefaultOpen,
7854
+ position: position ?? viewPosition
7908
7855
  });
7909
7856
  };
7910
7857
  return Object.assign(Component, CopilotChatView_default);
@@ -7937,12 +7884,12 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
7937
7884
  const { header: viewHeader, toggleButton: viewToggleButton, width: viewWidth, height: viewHeight, clickOutsideToClose: viewClickOutsideToClose, defaultOpen: viewDefaultOpen, ...restProps } = viewProps;
7938
7885
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotPopupView_default, {
7939
7886
  ...restProps,
7940
- header: header !== null && header !== void 0 ? header : viewHeader,
7941
- toggleButton: toggleButton !== null && toggleButton !== void 0 ? toggleButton : viewToggleButton,
7942
- width: width !== null && width !== void 0 ? width : viewWidth,
7943
- height: height !== null && height !== void 0 ? height : viewHeight,
7944
- clickOutsideToClose: clickOutsideToClose !== null && clickOutsideToClose !== void 0 ? clickOutsideToClose : viewClickOutsideToClose,
7945
- defaultOpen: defaultOpen !== null && defaultOpen !== void 0 ? defaultOpen : viewDefaultOpen
7887
+ header: header ?? viewHeader,
7888
+ toggleButton: toggleButton ?? viewToggleButton,
7889
+ width: width ?? viewWidth,
7890
+ height: height ?? viewHeight,
7891
+ clickOutsideToClose: clickOutsideToClose ?? viewClickOutsideToClose,
7892
+ defaultOpen: defaultOpen ?? viewDefaultOpen
7946
7893
  });
7947
7894
  };
7948
7895
  return Object.assign(Component, CopilotChatView_default);
@@ -8009,7 +7956,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
8009
7956
  children: "Arguments"
8010
7957
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
8011
7958
  className: "cpk:mt-2 cpk:max-h-64 cpk:overflow-auto cpk:rounded-md cpk:bg-zinc-50 cpk:dark:bg-zinc-800/60 cpk:p-3 cpk:text-xs cpk:leading-relaxed cpk:text-zinc-800 cpk:dark:text-zinc-200 cpk:whitespace-pre-wrap cpk:break-words",
8012
- children: JSON.stringify(args !== null && args !== void 0 ? args : {}, null, 2)
7959
+ children: JSON.stringify(args ?? {}, null, 2)
8013
7960
  })] }), result !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
8014
7961
  className: "cpk:text-xs cpk:uppercase cpk:tracking-wide cpk:text-zinc-500 cpk:dark:text-zinc-400",
8015
7962
  children: "Result"
@@ -8354,6 +8301,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
8354
8301
  const details = bannerError.details;
8355
8302
  const link = extractUrl(bannerError.message);
8356
8303
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
8304
+ "data-testid": "copilot-error-banner",
8357
8305
  style: {
8358
8306
  position: "fixed",
8359
8307
  bottom: "20px",
@@ -8553,9 +8501,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
8553
8501
  setToasts((prev) => prev.filter((toast) => toast.id !== id));
8554
8502
  }, []);
8555
8503
  const addToast = (0, react.useCallback)((toast) => {
8556
- var _toast$id;
8557
8504
  if (!enabled) return;
8558
- const id = (_toast$id = toast.id) !== null && _toast$id !== void 0 ? _toast$id : Math.random().toString(36).substring(2, 9);
8505
+ const id = toast.id ?? Math.random().toString(36).slice(2, 9);
8559
8506
  setToasts((currentToasts) => {
8560
8507
  if (currentToasts.find((toast) => toast.id === id)) return currentToasts;
8561
8508
  return [...currentToasts, {
@@ -8682,8 +8629,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
8682
8629
  ]);
8683
8630
  const createStructuredError = (gqlError) => {
8684
8631
  const extensions = gqlError.extensions;
8685
- const originalError = extensions === null || extensions === void 0 ? void 0 : extensions.originalError;
8686
- if (originalError === null || originalError === void 0 ? void 0 : originalError.stack) {
8632
+ const originalError = extensions?.originalError;
8633
+ if (originalError?.stack) {
8687
8634
  if (originalError.stack.includes("CopilotApiDiscoveryError")) return new _copilotkit_shared.CopilotKitApiDiscoveryError({ message: originalError.message });
8688
8635
  if (originalError.stack.includes("CopilotKitRemoteEndpointDiscoveryError")) return new _copilotkit_shared.CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });
8689
8636
  if (originalError.stack.includes("CopilotKitAgentDiscoveryError")) return new _copilotkit_shared.CopilotKitAgentDiscoveryError({
@@ -8691,8 +8638,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
8691
8638
  availableAgents: []
8692
8639
  });
8693
8640
  }
8694
- const message = (originalError === null || originalError === void 0 ? void 0 : originalError.message) || gqlError.message;
8695
- const code = extensions === null || extensions === void 0 ? void 0 : extensions.code;
8641
+ const message = originalError?.message || gqlError.message;
8642
+ const code = extensions?.code;
8696
8643
  if (code) return new _copilotkit_shared.CopilotKitError({
8697
8644
  message,
8698
8645
  code
@@ -8700,12 +8647,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
8700
8647
  return null;
8701
8648
  };
8702
8649
  (0, react.useCallback)((error) => {
8703
- var _error$graphQLErrors;
8704
- if ((_error$graphQLErrors = error.graphQLErrors) === null || _error$graphQLErrors === void 0 ? void 0 : _error$graphQLErrors.length) {
8650
+ if (error.graphQLErrors?.length) {
8705
8651
  const graphQLErrors = error.graphQLErrors;
8706
8652
  const routeError = (gqlError) => {
8707
- const extensions = gqlError.extensions;
8708
- const suppression = getErrorSuppression(extensions === null || extensions === void 0 ? void 0 : extensions.visibility, shouldShowDevConsole(showDevConsole));
8653
+ const visibility = gqlError.extensions?.visibility;
8654
+ const suppression = getErrorSuppression(visibility, shouldShowDevConsole(showDevConsole));
8709
8655
  if (suppression) {
8710
8656
  console.error(suppression, gqlError.message);
8711
8657
  return;
@@ -8726,7 +8672,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
8726
8672
  graphQLErrors.forEach(routeError);
8727
8673
  } else {
8728
8674
  const fallbackError = new _copilotkit_shared.CopilotKitError({
8729
- message: (error === null || error === void 0 ? void 0 : error.message) || String(error),
8675
+ message: error?.message || String(error),
8730
8676
  code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
8731
8677
  });
8732
8678
  setBannerError(fallbackError);
@@ -8913,6 +8859,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
8913
8859
  }
8914
8860
  ` }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
8915
8861
  className: "usage-banner",
8862
+ "data-testid": "copilot-error-banner",
8916
8863
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
8917
8864
  className: "banner-content",
8918
8865
  children: [
@@ -8920,7 +8867,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
8920
8867
  className: "banner-message",
8921
8868
  children: message
8922
8869
  }),
8923
- (actions === null || actions === void 0 ? void 0 : actions.primary) && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
8870
+ actions?.primary && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
8924
8871
  className: "btn-primary",
8925
8872
  onClick: actions.primary.onClick,
8926
8873
  children: actions.primary.label
@@ -8970,7 +8917,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
8970
8917
  headers: { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey }
8971
8918
  }).then((response) => response.json());
8972
8919
  this.lastResponse = response;
8973
- onUpdate === null || onUpdate === void 0 || onUpdate(response);
8920
+ onUpdate?.(response);
8974
8921
  return response;
8975
8922
  } catch (error) {
8976
8923
  return null;
@@ -9014,8 +8961,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9014
8961
  componentDidMount() {
9015
8962
  if (this.props.publicApiKey) statusChecker.start(this.props.publicApiKey, (newStatus) => {
9016
8963
  this.setState((prevState) => {
9017
- var _prevState$status;
9018
- if ((newStatus === null || newStatus === void 0 ? void 0 : newStatus.severity) !== ((_prevState$status = prevState.status) === null || _prevState$status === void 0 ? void 0 : _prevState$status.severity)) return { status: newStatus !== null && newStatus !== void 0 ? newStatus : void 0 };
8964
+ if (newStatus?.severity !== prevState.status?.severity) return { status: newStatus ?? void 0 };
9019
8965
  return null;
9020
8966
  });
9021
8967
  });
@@ -9028,14 +8974,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9028
8974
  }
9029
8975
  render() {
9030
8976
  if (this.state.hasError) {
9031
- if (this.state.error instanceof _copilotkit_shared.CopilotKitError) {
9032
- var _this$state$status$se, _this$state$status, _this$state$status$me, _this$state$status2;
9033
- 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, {
9034
- severity: (_this$state$status$se = (_this$state$status = this.state.status) === null || _this$state$status === void 0 ? void 0 : _this$state$status.severity) !== null && _this$state$status$se !== void 0 ? _this$state$status$se : this.state.error.severity,
9035
- message: (_this$state$status$me = (_this$state$status2 = this.state.status) === null || _this$state$status2 === void 0 ? void 0 : _this$state$status2.message) !== null && _this$state$status$me !== void 0 ? _this$state$status$me : this.state.error.message,
9036
- actions: getErrorActions(this.state.error)
9037
- })] });
9038
- }
8977
+ 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, {
8978
+ severity: this.state.status?.severity ?? this.state.error.severity,
8979
+ message: this.state.status?.message ?? this.state.error.message,
8980
+ actions: getErrorActions(this.state.error)
8981
+ })] });
9039
8982
  throw this.state.error;
9040
8983
  }
9041
8984
  return this.props.children;
@@ -9083,7 +9026,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9083
9026
  function ThreadsProvider({ children, threadId: explicitThreadId }) {
9084
9027
  const [internalThreadId, setInternalThreadId] = (0, react.useState)(() => (0, _copilotkit_shared.randomUUID)());
9085
9028
  const [internalIsExplicit, setInternalIsExplicit] = (0, react.useState)(false);
9086
- const threadId = explicitThreadId !== null && explicitThreadId !== void 0 ? explicitThreadId : internalThreadId;
9029
+ const threadId = explicitThreadId ?? internalThreadId;
9087
9030
  const isThreadIdExplicit = explicitThreadId != null || internalIsExplicit;
9088
9031
  const setThreadId = (0, react.useCallback)((value) => {
9089
9032
  setInternalThreadId(value);
@@ -9164,13 +9107,10 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9164
9107
  updateRunId: shouldUpdateRunId ? runId : void 0
9165
9108
  };
9166
9109
  }
9167
- const normalizedRunId = runId !== null && runId !== void 0 ? runId : "pending";
9168
- const renderClaimedByOtherMessageEntry = Object.entries(claims).find(([, claim]) => {
9169
- var _claim$runId;
9170
- return claim.stateRenderId === stateRenderId && ((_claim$runId = claim.runId) !== null && _claim$runId !== void 0 ? _claim$runId : "pending") === normalizedRunId && (0, _copilotkit_shared.dataToUUID)(getStateWithoutConstantKeys(claim.stateSnapshot)) === (0, _copilotkit_shared.dataToUUID)(getStateWithoutConstantKeys(stateSnapshot));
9171
- });
9172
- const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry === null || renderClaimedByOtherMessageEntry === void 0 ? void 0 : renderClaimedByOtherMessageEntry[1];
9173
- const claimedMessageId = renderClaimedByOtherMessageEntry === null || renderClaimedByOtherMessageEntry === void 0 ? void 0 : renderClaimedByOtherMessageEntry[0];
9110
+ const normalizedRunId = runId ?? "pending";
9111
+ 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)));
9112
+ const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry?.[1];
9113
+ const claimedMessageId = renderClaimedByOtherMessageEntry?.[0];
9174
9114
  if (renderClaimedByOtherMessage) {
9175
9115
  if (messageIndex !== void 0 && renderClaimedByOtherMessage.messageIndex !== void 0 && messageIndex > renderClaimedByOtherMessage.messageIndex) return {
9176
9116
  canRender: true,
@@ -9239,17 +9179,14 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9239
9179
  * 5) last cached snapshot for stateRenderId
9240
9180
  */
9241
9181
  function selectSnapshot({ messageId, messageName, allowLiveState, skipLatestCache, stateRenderId, effectiveRunId, stateSnapshotProp, agentState, agentMessages, existingClaim, caches }) {
9242
- var _toReversed$find, _agentMessages$messag, _existingClaim$stateS, _existingClaim$stateS2;
9243
- const lastAssistantId = agentMessages ? (_toReversed$find = [...agentMessages].toReversed().find((msg) => msg.role === "assistant")) === null || _toReversed$find === void 0 ? void 0 : _toReversed$find.id : void 0;
9182
+ const lastAssistantId = agentMessages ? [...agentMessages].toReversed().find((msg) => msg.role === "assistant")?.id : void 0;
9244
9183
  const latestSnapshot = stateRenderId !== void 0 ? caches.byStateRenderAndRun[`${stateRenderId}::latest`] : void 0;
9245
9184
  const messageIndex = agentMessages ? agentMessages.findIndex((msg) => msg.id === messageId) : -1;
9246
- const messageRole = messageIndex >= 0 && agentMessages ? (_agentMessages$messag = agentMessages[messageIndex]) === null || _agentMessages$messag === void 0 ? void 0 : _agentMessages$messag.role : void 0;
9185
+ const messageRole = messageIndex >= 0 && agentMessages ? agentMessages[messageIndex]?.role : void 0;
9247
9186
  let previousUserMessageId;
9248
- if (messageIndex > 0 && agentMessages) for (let i = messageIndex - 1; i >= 0; i -= 1) {
9249
- var _agentMessages$i;
9250
- if (((_agentMessages$i = agentMessages[i]) === null || _agentMessages$i === void 0 ? void 0 : _agentMessages$i.role) === "user") {
9251
- var _agentMessages$i2;
9252
- previousUserMessageId = (_agentMessages$i2 = agentMessages[i]) === null || _agentMessages$i2 === void 0 ? void 0 : _agentMessages$i2.id;
9187
+ if (messageIndex > 0 && agentMessages) {
9188
+ for (let i = messageIndex - 1; i >= 0; i -= 1) if (agentMessages[i]?.role === "user") {
9189
+ previousUserMessageId = agentMessages[i]?.id;
9253
9190
  break;
9254
9191
  }
9255
9192
  }
@@ -9261,11 +9198,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9261
9198
  const messageCacheEntry = caches.byMessageId[messageId];
9262
9199
  const cachedMessageSnapshot = readCachedMessageEntry(messageCacheEntry).snapshot;
9263
9200
  const cacheKey = stateRenderId !== void 0 ? `${stateRenderId}::${effectiveRunId}` : void 0;
9264
- let cachedSnapshot = cachedMessageSnapshot !== null && cachedMessageSnapshot !== void 0 ? cachedMessageSnapshot : caches.byMessageId[messageId];
9201
+ let cachedSnapshot = cachedMessageSnapshot ?? caches.byMessageId[messageId];
9265
9202
  if (cachedSnapshot === void 0 && cacheKey && caches.byStateRenderAndRun[cacheKey] !== void 0) cachedSnapshot = caches.byStateRenderAndRun[cacheKey];
9266
9203
  if (cachedSnapshot === void 0 && stateRenderId && previousUserMessageId && caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`] !== void 0) cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`];
9267
9204
  if (cachedSnapshot === void 0 && !skipLatestCache && stateRenderId && messageRole !== "assistant" && (stateSnapshotProp !== void 0 || agentState && Object.keys(agentState).length > 0)) cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`];
9268
- const snapshotForClaim = (existingClaim === null || existingClaim === void 0 ? void 0 : existingClaim.locked) ? (_existingClaim$stateS = existingClaim.stateSnapshot) !== null && _existingClaim$stateS !== void 0 ? _existingClaim$stateS : cachedSnapshot : hasSnapshotKeys ? snapshot : (_existingClaim$stateS2 = existingClaim === null || existingClaim === void 0 ? void 0 : existingClaim.stateSnapshot) !== null && _existingClaim$stateS2 !== void 0 ? _existingClaim$stateS2 : cachedSnapshot;
9205
+ const snapshotForClaim = existingClaim?.locked ? existingClaim.stateSnapshot ?? cachedSnapshot : hasSnapshotKeys ? snapshot : existingClaim?.stateSnapshot ?? cachedSnapshot;
9269
9206
  return {
9270
9207
  snapshot,
9271
9208
  hasSnapshotKeys,
@@ -9283,37 +9220,36 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9283
9220
  return claimsRef.current;
9284
9221
  }
9285
9222
  function getSnapshotCaches(claimsRef) {
9286
- var _store$LAST_SNAPSHOTS, _store$LAST_SNAPSHOTS2;
9287
9223
  const store = getClaimsStore(claimsRef);
9288
9224
  return {
9289
- byStateRenderAndRun: (_store$LAST_SNAPSHOTS = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) !== null && _store$LAST_SNAPSHOTS !== void 0 ? _store$LAST_SNAPSHOTS : {},
9290
- byMessageId: (_store$LAST_SNAPSHOTS2 = store[LAST_SNAPSHOTS_BY_MESSAGE]) !== null && _store$LAST_SNAPSHOTS2 !== void 0 ? _store$LAST_SNAPSHOTS2 : {}
9225
+ byStateRenderAndRun: store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {},
9226
+ byMessageId: store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}
9291
9227
  };
9292
9228
  }
9293
9229
  function useStateRenderRegistry({ agentId, stateRenderId, message, messageIndex, stateSnapshot, agentState, agentMessages, claimsRef }) {
9294
- var _store$LAST_SNAPSHOTS3, _claimsRef$current$me;
9295
9230
  const store = getClaimsStore(claimsRef);
9296
9231
  const runId = message.runId;
9297
- const { runId: cachedMessageRunId } = readCachedMessageEntry((_store$LAST_SNAPSHOTS3 = store[LAST_SNAPSHOTS_BY_MESSAGE]) === null || _store$LAST_SNAPSHOTS3 === void 0 ? void 0 : _store$LAST_SNAPSHOTS3[message.id]);
9232
+ const cachedMessageEntry = store[LAST_SNAPSHOTS_BY_MESSAGE]?.[message.id];
9233
+ const { runId: cachedMessageRunId } = readCachedMessageEntry(cachedMessageEntry);
9234
+ const existingClaimRunId = claimsRef.current[message.id]?.runId;
9298
9235
  const effectiveRunId = getEffectiveRunId({
9299
- existingClaimRunId: (_claimsRef$current$me = claimsRef.current[message.id]) === null || _claimsRef$current$me === void 0 ? void 0 : _claimsRef$current$me.runId,
9236
+ existingClaimRunId,
9300
9237
  cachedMessageRunId,
9301
9238
  runId
9302
9239
  });
9303
9240
  (0, react.useEffect)(() => {
9304
9241
  return () => {
9305
9242
  const existingClaim = claimsRef.current[message.id];
9306
- if ((existingClaim === null || existingClaim === void 0 ? void 0 : existingClaim.stateSnapshot) && Object.keys(existingClaim.stateSnapshot).length > 0) {
9307
- var _existingClaim$runId, _existingClaim$runId2;
9243
+ if (existingClaim?.stateSnapshot && Object.keys(existingClaim.stateSnapshot).length > 0) {
9308
9244
  const snapshotCache = { ...store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] };
9309
- const cacheKey = `${existingClaim.stateRenderId}::${(_existingClaim$runId = existingClaim.runId) !== null && _existingClaim$runId !== void 0 ? _existingClaim$runId : "pending"}`;
9245
+ const cacheKey = `${existingClaim.stateRenderId}::${existingClaim.runId ?? "pending"}`;
9310
9246
  snapshotCache[cacheKey] = existingClaim.stateSnapshot;
9311
9247
  snapshotCache[`${existingClaim.stateRenderId}::latest`] = existingClaim.stateSnapshot;
9312
9248
  store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
9313
9249
  const messageCache = { ...store[LAST_SNAPSHOTS_BY_MESSAGE] };
9314
9250
  messageCache[message.id] = {
9315
9251
  snapshot: existingClaim.stateSnapshot,
9316
- runId: (_existingClaim$runId2 = existingClaim.runId) !== null && _existingClaim$runId2 !== void 0 ? _existingClaim$runId2 : effectiveRunId
9252
+ runId: existingClaim.runId ?? effectiveRunId
9317
9253
  };
9318
9254
  store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
9319
9255
  }
@@ -9357,7 +9293,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9357
9293
  if (resolution.lockOthers) Object.entries(claimsRef.current).forEach(([id, claim]) => {
9358
9294
  if (id !== message.id && claim.stateRenderId === stateRenderId) claim.locked = true;
9359
9295
  });
9360
- if (existingClaim && !existingClaim.locked && (agentMessages === null || agentMessages === void 0 ? void 0 : agentMessages.length)) {
9296
+ if (existingClaim && !existingClaim.locked && agentMessages?.length) {
9361
9297
  const indexInAgentMessages = agentMessages.findIndex((msg) => msg.id === message.id);
9362
9298
  if (indexInAgentMessages >= 0 && indexInAgentMessages < agentMessages.length - 1) existingClaim.locked = true;
9363
9299
  }
@@ -9401,7 +9337,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9401
9337
  //#endregion
9402
9338
  //#region src/hooks/use-coagent-state-render-bridge.tsx
9403
9339
  function useCoagentStateRenderBridge(agentId, props) {
9404
- var _props$runId;
9405
9340
  const { stateSnapshot, message } = props;
9406
9341
  const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();
9407
9342
  const { agent } = useAgent({ agentId });
@@ -9437,46 +9372,42 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9437
9372
  agentId
9438
9373
  ]);
9439
9374
  const stateRenderEntry = (0, react.useMemo)(() => getStateRender(message.id), [getStateRender, message.id]);
9440
- const stateRenderId = stateRenderEntry === null || stateRenderEntry === void 0 ? void 0 : stateRenderEntry[0];
9441
- const stateRender = stateRenderEntry === null || stateRenderEntry === void 0 ? void 0 : stateRenderEntry[1];
9375
+ const stateRenderId = stateRenderEntry?.[0];
9376
+ const stateRender = stateRenderEntry?.[1];
9442
9377
  const { canRender } = useStateRenderRegistry({
9443
9378
  agentId,
9444
9379
  stateRenderId,
9445
9380
  message: {
9446
9381
  ...message,
9447
- runId: (_props$runId = props.runId) !== null && _props$runId !== void 0 ? _props$runId : message.runId
9382
+ runId: props.runId ?? message.runId
9448
9383
  },
9449
9384
  messageIndex: props.messageIndex,
9450
9385
  stateSnapshot,
9451
- agentState: agent === null || agent === void 0 ? void 0 : agent.state,
9452
- agentMessages: agent === null || agent === void 0 ? void 0 : agent.messages,
9386
+ agentState: agent?.state,
9387
+ agentMessages: agent?.messages,
9453
9388
  claimsRef
9454
9389
  });
9455
9390
  return (0, react.useMemo)(() => {
9456
9391
  if (!stateRender || !stateRenderId) return null;
9457
9392
  if (!canRender) return null;
9458
- if (stateRender.handler) {
9459
- var _agent$state;
9460
- stateRender.handler({
9461
- state: stateSnapshot ? (0, _copilotkit_shared.parseJson)(stateSnapshot, stateSnapshot) : (_agent$state = agent === null || agent === void 0 ? void 0 : agent.state) !== null && _agent$state !== void 0 ? _agent$state : {},
9462
- nodeName: nodeName !== null && nodeName !== void 0 ? nodeName : ""
9463
- });
9464
- }
9393
+ if (stateRender.handler) stateRender.handler({
9394
+ state: stateSnapshot ? (0, _copilotkit_shared.parseJson)(stateSnapshot, stateSnapshot) : agent?.state ?? {},
9395
+ nodeName: nodeName ?? ""
9396
+ });
9465
9397
  if (stateRender.render) {
9466
- var _claimsRef$current$me;
9467
- const status = (agent === null || agent === void 0 ? void 0 : agent.isRunning) ? RenderStatus.InProgress : RenderStatus.Complete;
9398
+ const status = agent?.isRunning ? RenderStatus.InProgress : RenderStatus.Complete;
9468
9399
  if (typeof stateRender.render === "string") return stateRender.render;
9469
9400
  return stateRender.render({
9470
9401
  status,
9471
- state: (_claimsRef$current$me = claimsRef.current[message.id].stateSnapshot) !== null && _claimsRef$current$me !== void 0 ? _claimsRef$current$me : {},
9472
- nodeName: nodeName !== null && nodeName !== void 0 ? nodeName : ""
9402
+ state: claimsRef.current[message.id].stateSnapshot ?? {},
9403
+ nodeName: nodeName ?? ""
9473
9404
  });
9474
9405
  }
9475
9406
  }, [
9476
9407
  stateRender,
9477
9408
  stateRenderId,
9478
- agent === null || agent === void 0 ? void 0 : agent.state,
9479
- agent === null || agent === void 0 ? void 0 : agent.isRunning,
9409
+ agent?.state,
9410
+ agent?.isRunning,
9480
9411
  nodeName,
9481
9412
  message.id,
9482
9413
  stateSnapshot,
@@ -9497,7 +9428,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9497
9428
  },
9498
9429
  onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {
9499
9430
  predictStateToolsRef.current.forEach((t) => {
9500
- if ((t === null || t === void 0 ? void 0 : t.tool) !== toolCallName) return;
9431
+ if (t?.tool !== toolCallName) return;
9501
9432
  const emittedState = typeof partialToolCallArgs === "string" ? (0, _copilotkit_shared.parseJson)(partialToolCallArgs, partialToolCallArgs) : partialToolCallArgs;
9502
9433
  agent.setState({ [t.state_key]: emittedState[t.state_key] });
9503
9434
  });
@@ -9513,16 +9444,15 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9513
9444
  }, [agent, getSubscriber]);
9514
9445
  };
9515
9446
  function CopilotListenersAgentSubscription() {
9516
- const existingConfig = useCopilotChatConfiguration();
9517
- const { agent } = useAgent({ agentId: existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.agentId });
9447
+ const resolvedAgentId = useCopilotChatConfiguration()?.agentId;
9448
+ const { agent } = useAgent({ agentId: resolvedAgentId });
9518
9449
  usePredictStateSubscription(agent);
9519
9450
  return null;
9520
9451
  }
9521
9452
  function CopilotListeners() {
9522
- var _copilotkit$agents;
9523
9453
  const { copilotkit } = useCopilotKit();
9524
9454
  const { setBannerError } = useToast();
9525
- const hasAgents = Object.keys((_copilotkit$agents = copilotkit.agents) !== null && _copilotkit$agents !== void 0 ? _copilotkit$agents : {}).length > 0;
9455
+ const hasAgents = Object.keys(copilotkit.agents ?? {}).length > 0;
9526
9456
  const hasRuntime = copilotkit.runtimeUrl !== void 0;
9527
9457
  (0, react.useEffect)(() => {
9528
9458
  const subscription = copilotkit.subscribe({ onError: ({ error, code, context }) => {
@@ -9544,7 +9474,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9544
9474
  return () => {
9545
9475
  subscription.unsubscribe();
9546
9476
  };
9547
- }, [copilotkit === null || copilotkit === void 0 ? void 0 : copilotkit.subscribe]);
9477
+ }, [copilotkit?.subscribe]);
9548
9478
  return hasAgents || hasRuntime ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotListenersAgentSubscription, {}) : null;
9549
9479
  }
9550
9480
 
@@ -9566,7 +9496,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9566
9496
  * ```
9567
9497
  */
9568
9498
  function CopilotKit({ children, ...props }) {
9569
- var _props$useSingleEndpo;
9570
9499
  const enabled = shouldShowDevConsole(props.showDevConsole);
9571
9500
  const showInspector = shouldShowDevConsole(props.enableInspector);
9572
9501
  const publicApiKey = props.publicApiKey || props.publicLicenseKey;
@@ -9582,7 +9511,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9582
9511
  ...props,
9583
9512
  showDevConsole: showInspector,
9584
9513
  renderCustomMessages: renderArr,
9585
- useSingleEndpoint: (_props$useSingleEndpo = props.useSingleEndpoint) !== null && _props$useSingleEndpo !== void 0 ? _props$useSingleEndpo : true,
9514
+ useSingleEndpoint: props.useSingleEndpoint ?? true,
9586
9515
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitInternal, {
9587
9516
  ...props,
9588
9517
  children
@@ -9611,7 +9540,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9611
9540
  source: "agent",
9612
9541
  request: {
9613
9542
  operation: event.code || "unknown",
9614
- url: copilotApiConfig === null || copilotApiConfig === void 0 ? void 0 : copilotApiConfig.chatApiEndpoint,
9543
+ url: copilotApiConfig?.chatApiEndpoint,
9615
9544
  startTime: Date.now()
9616
9545
  },
9617
9546
  technical: {
@@ -9640,7 +9569,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9640
9569
  return null;
9641
9570
  }
9642
9571
  function CopilotKitInternal(cpkProps) {
9643
- var _props$agent2;
9644
9572
  const { children, ...props } = cpkProps;
9645
9573
  /**
9646
9574
  * This will throw an error if the props are invalid.
@@ -9704,14 +9632,11 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9704
9632
  }, [removeDocument]);
9705
9633
  const copilotApiConfig = (0, react.useMemo)(() => {
9706
9634
  let cloud = void 0;
9707
- if (publicApiKey) {
9708
- var _props$guardrails_c, _props$guardrails_c2;
9709
- cloud = { guardrails: { input: { restrictToTopic: {
9710
- enabled: Boolean(props.guardrails_c),
9711
- validTopics: ((_props$guardrails_c = props.guardrails_c) === null || _props$guardrails_c === void 0 ? void 0 : _props$guardrails_c.validTopics) || [],
9712
- invalidTopics: ((_props$guardrails_c2 = props.guardrails_c) === null || _props$guardrails_c2 === void 0 ? void 0 : _props$guardrails_c2.invalidTopics) || []
9713
- } } } };
9714
- }
9635
+ if (publicApiKey) cloud = { guardrails: { input: { restrictToTopic: {
9636
+ enabled: Boolean(props.guardrails_c),
9637
+ validTopics: props.guardrails_c?.validTopics || [],
9638
+ invalidTopics: props.guardrails_c?.invalidTopics || []
9639
+ } } } };
9715
9640
  return {
9716
9641
  publicApiKey,
9717
9642
  ...cloud ? { cloud } : {},
@@ -9867,14 +9792,8 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
9867
9792
  }, []);
9868
9793
  const memoizedChildren = (0, react.useMemo)(() => children, [children]);
9869
9794
  const [bannerError, setBannerError] = (0, react.useState)(null);
9870
- const agentLock = (0, react.useMemo)(() => {
9871
- var _props$agent;
9872
- return (_props$agent = props.agent) !== null && _props$agent !== void 0 ? _props$agent : null;
9873
- }, [props.agent]);
9874
- const forwardedParameters = (0, react.useMemo)(() => {
9875
- var _props$forwardedParam;
9876
- return (_props$forwardedParam = props.forwardedParameters) !== null && _props$forwardedParam !== void 0 ? _props$forwardedParam : {};
9877
- }, [props.forwardedParameters]);
9795
+ const agentLock = (0, react.useMemo)(() => props.agent ?? null, [props.agent]);
9796
+ const forwardedParameters = (0, react.useMemo)(() => props.forwardedParameters ?? {}, [props.forwardedParameters]);
9878
9797
  const updateExtensions = (0, react.useCallback)((newExtensions) => {
9879
9798
  setExtensions((prev) => {
9880
9799
  const resolved = typeof newExtensions === "function" ? newExtensions(prev) : newExtensions;
@@ -10017,7 +9936,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
10017
9936
  removeInternalErrorHandler
10018
9937
  ]);
10019
9938
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfigurationProvider, {
10020
- agentId: (_props$agent2 = props.agent) !== null && _props$agent2 !== void 0 ? _props$agent2 : "default",
9939
+ agentId: props.agent ?? "default",
10021
9940
  threadId,
10022
9941
  hasExplicitThreadId: isThreadIdExplicit,
10023
9942
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotContext.Provider, {
@@ -10046,8 +9965,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
10046
9965
  await new Promise((resolve, reject) => {
10047
9966
  (0, react_dom.flushSync)(async () => {
10048
9967
  try {
10049
- var _action$handler;
10050
- result = await ((_action$handler = action.handler) === null || _action$handler === void 0 ? void 0 : _action$handler.call(action, args));
9968
+ result = await action.handler?.(args);
10051
9969
  resolve();
10052
9970
  } catch (error) {
10053
9971
  reject(error);