@copilotkit/react-core 1.4.8-next.2 → 1.4.8

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.
Files changed (134) hide show
  1. package/CHANGELOG.md +8 -13
  2. package/dist/{chunk-DIX6ISOB.mjs → chunk-6EMLM6WX.mjs} +20 -19
  3. package/dist/chunk-6EMLM6WX.mjs.map +1 -0
  4. package/dist/{chunk-ODN4H66E.mjs → chunk-7LRDVJH5.mjs} +6 -2
  5. package/dist/chunk-7LRDVJH5.mjs.map +1 -0
  6. package/dist/{chunk-XXCJFOLY.mjs → chunk-AG7FH7OD.mjs} +2 -2
  7. package/dist/{chunk-XYFTGCMS.mjs → chunk-FSC4A3JN.mjs} +18 -14
  8. package/dist/chunk-FSC4A3JN.mjs.map +1 -0
  9. package/dist/{chunk-E3HHCHMQ.mjs → chunk-IFTHM7LF.mjs} +7 -10
  10. package/dist/chunk-IFTHM7LF.mjs.map +1 -0
  11. package/dist/{chunk-V6CEKRZA.mjs → chunk-IVYL7JRC.mjs} +12 -11
  12. package/dist/chunk-IVYL7JRC.mjs.map +1 -0
  13. package/dist/chunk-NTLCOVE5.mjs +321 -0
  14. package/dist/chunk-NTLCOVE5.mjs.map +1 -0
  15. package/dist/chunk-QCUP6HLK.mjs +37 -0
  16. package/dist/chunk-QCUP6HLK.mjs.map +1 -0
  17. package/dist/{chunk-2KCEHGSI.mjs → chunk-SFPANIOY.mjs} +99 -49
  18. package/dist/chunk-SFPANIOY.mjs.map +1 -0
  19. package/dist/{chunk-CBMCK7UC.mjs → chunk-UOVONDR6.mjs} +2 -2
  20. package/dist/{chunk-XSORW54K.mjs → chunk-X6ZF5WAX.mjs} +2 -2
  21. package/dist/{chunk-4P56GAFP.mjs → chunk-XQFVXX6R.mjs} +2 -3
  22. package/dist/chunk-XQFVXX6R.mjs.map +1 -0
  23. package/dist/{chunk-ETCKRNXQ.mjs → chunk-YUY5ZAST.mjs} +7 -4
  24. package/dist/chunk-YUY5ZAST.mjs.map +1 -0
  25. package/dist/components/copilot-provider/copilot-messages.d.ts +0 -1
  26. package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -5
  27. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  28. package/dist/components/copilot-provider/copilotkit.d.ts +0 -1
  29. package/dist/components/copilot-provider/copilotkit.js +158 -95
  30. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  31. package/dist/components/copilot-provider/copilotkit.mjs +5 -4
  32. package/dist/components/copilot-provider/index.d.ts +0 -1
  33. package/dist/components/copilot-provider/index.js +158 -95
  34. package/dist/components/copilot-provider/index.js.map +1 -1
  35. package/dist/components/copilot-provider/index.mjs +5 -4
  36. package/dist/components/error-boundary/error-boundary.d.ts +22 -0
  37. package/dist/components/error-boundary/error-boundary.js +183 -0
  38. package/dist/components/error-boundary/error-boundary.js.map +1 -0
  39. package/dist/components/error-boundary/error-boundary.mjs +12 -0
  40. package/dist/components/error-boundary/error-boundary.mjs.map +1 -0
  41. package/dist/components/error-boundary/error-utils.d.ts +11 -0
  42. package/dist/components/error-boundary/error-utils.js +177 -0
  43. package/dist/components/error-boundary/error-utils.js.map +1 -0
  44. package/dist/components/error-boundary/error-utils.mjs +13 -0
  45. package/dist/components/error-boundary/error-utils.mjs.map +1 -0
  46. package/dist/components/index.d.ts +0 -1
  47. package/dist/components/index.js +158 -95
  48. package/dist/components/index.js.map +1 -1
  49. package/dist/components/index.mjs +5 -4
  50. package/dist/components/toast/toast-provider.d.ts +2 -1
  51. package/dist/components/toast/toast-provider.js +76 -62
  52. package/dist/components/toast/toast-provider.js.map +1 -1
  53. package/dist/components/toast/toast-provider.mjs +1 -1
  54. package/dist/context/copilot-context.d.ts +1 -5
  55. package/dist/context/copilot-context.js +1 -2
  56. package/dist/context/copilot-context.js.map +1 -1
  57. package/dist/context/copilot-context.mjs +1 -1
  58. package/dist/context/index.js +1 -2
  59. package/dist/context/index.js.map +1 -1
  60. package/dist/context/index.mjs +1 -1
  61. package/dist/hooks/index.js +401 -260
  62. package/dist/hooks/index.js.map +1 -1
  63. package/dist/hooks/index.mjs +19 -18
  64. package/dist/hooks/use-chat.d.ts +1 -2
  65. package/dist/hooks/use-chat.js +343 -200
  66. package/dist/hooks/use-chat.js.map +1 -1
  67. package/dist/hooks/use-chat.mjs +3 -3
  68. package/dist/hooks/use-coagent-state-render.js +1 -2
  69. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  70. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  71. package/dist/hooks/use-coagent.js +381 -240
  72. package/dist/hooks/use-coagent.js.map +1 -1
  73. package/dist/hooks/use-coagent.mjs +9 -8
  74. package/dist/hooks/use-copilot-action.js +133 -9
  75. package/dist/hooks/use-copilot-action.js.map +1 -1
  76. package/dist/hooks/use-copilot-action.mjs +4 -2
  77. package/dist/hooks/use-copilot-chat.js +370 -230
  78. package/dist/hooks/use-copilot-chat.js.map +1 -1
  79. package/dist/hooks/use-copilot-chat.mjs +8 -7
  80. package/dist/hooks/use-copilot-readable.js +1 -2
  81. package/dist/hooks/use-copilot-readable.js.map +1 -1
  82. package/dist/hooks/use-copilot-readable.mjs +2 -2
  83. package/dist/hooks/use-copilot-runtime-client.js +110 -4
  84. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  85. package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
  86. package/dist/hooks/use-make-copilot-document-readable.js +1 -2
  87. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  88. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  89. package/dist/index.d.ts +1 -1
  90. package/dist/index.js +450 -353
  91. package/dist/index.js.map +1 -1
  92. package/dist/index.mjs +20 -19
  93. package/dist/lib/copilot-task.d.ts +1 -6
  94. package/dist/lib/copilot-task.js +4 -22
  95. package/dist/lib/copilot-task.js.map +1 -1
  96. package/dist/lib/copilot-task.mjs +6 -5
  97. package/dist/lib/index.d.ts +1 -1
  98. package/dist/lib/index.js +4 -22
  99. package/dist/lib/index.js.map +1 -1
  100. package/dist/lib/index.mjs +6 -5
  101. package/dist/utils/extract.d.ts +2 -3
  102. package/dist/utils/extract.js +3 -21
  103. package/dist/utils/extract.js.map +1 -1
  104. package/dist/utils/extract.mjs +5 -4
  105. package/dist/utils/index.js +3 -21
  106. package/dist/utils/index.js.map +1 -1
  107. package/dist/utils/index.mjs +5 -4
  108. package/package.json +3 -3
  109. package/src/components/copilot-provider/copilotkit-props.tsx +0 -6
  110. package/src/components/copilot-provider/copilotkit.tsx +4 -2
  111. package/src/components/error-boundary/error-boundary.tsx +42 -0
  112. package/src/components/error-boundary/error-utils.tsx +95 -0
  113. package/src/components/toast/toast-provider.tsx +10 -49
  114. package/src/context/copilot-context.tsx +1 -8
  115. package/src/hooks/use-chat.ts +286 -266
  116. package/src/hooks/use-coagent.ts +14 -11
  117. package/src/hooks/use-copilot-action.ts +3 -2
  118. package/src/hooks/use-copilot-chat.ts +9 -10
  119. package/src/hooks/use-copilot-runtime-client.ts +4 -0
  120. package/src/lib/copilot-task.ts +2 -10
  121. package/src/utils/extract.ts +0 -4
  122. package/dist/chunk-2KCEHGSI.mjs.map +0 -1
  123. package/dist/chunk-4P56GAFP.mjs.map +0 -1
  124. package/dist/chunk-DIX6ISOB.mjs.map +0 -1
  125. package/dist/chunk-E3HHCHMQ.mjs.map +0 -1
  126. package/dist/chunk-ETCKRNXQ.mjs.map +0 -1
  127. package/dist/chunk-ODN4H66E.mjs.map +0 -1
  128. package/dist/chunk-PG5XEJVS.mjs +0 -295
  129. package/dist/chunk-PG5XEJVS.mjs.map +0 -1
  130. package/dist/chunk-V6CEKRZA.mjs.map +0 -1
  131. package/dist/chunk-XYFTGCMS.mjs.map +0 -1
  132. /package/dist/{chunk-XXCJFOLY.mjs.map → chunk-AG7FH7OD.mjs.map} +0 -0
  133. /package/dist/{chunk-CBMCK7UC.mjs.map → chunk-UOVONDR6.mjs.map} +0 -0
  134. /package/dist/{chunk-XSORW54K.mjs.map → chunk-X6ZF5WAX.mjs.map} +0 -0
package/dist/index.js CHANGED
@@ -101,7 +101,7 @@ __export(src_exports, {
101
101
  module.exports = __toCommonJS(src_exports);
102
102
 
103
103
  // src/components/copilot-provider/copilotkit.tsx
104
- var import_react8 = require("react");
104
+ var import_react10 = require("react");
105
105
 
106
106
  // src/context/copilot-context.tsx
107
107
  var import_react = __toESM(require("react"));
@@ -157,8 +157,7 @@ var emptyCopilotContext = {
157
157
  },
158
158
  agentSession: null,
159
159
  setAgentSession: () => {
160
- },
161
- forwardedParameters: {}
160
+ }
162
161
  };
163
162
  var CopilotContext = import_react.default.createContext(emptyCopilotContext);
164
163
  function useCopilotContext() {
@@ -412,6 +411,9 @@ function CopilotMessages(_a) {
412
411
  }
413
412
 
414
413
  // src/components/toast/toast-provider.tsx
414
+ var import_react7 = require("react");
415
+
416
+ // src/components/error-boundary/error-utils.tsx
415
417
  var import_react6 = require("react");
416
418
 
417
419
  // src/components/toast/exclamation-mark-icon.tsx
@@ -441,11 +443,94 @@ var ExclamationMarkIcon = ({
441
443
  }
442
444
  );
443
445
 
444
- // src/components/toast/toast-provider.tsx
446
+ // src/components/error-boundary/error-utils.tsx
445
447
  var import_jsx_runtime3 = require("react/jsx-runtime");
446
- var ToastContext = (0, import_react6.createContext)(void 0);
448
+ function ErrorToast({ errors }) {
449
+ const errorsToRender = errors.map((error, idx) => {
450
+ var _a, _b, _c;
451
+ const message = "extensions" in error ? (_b = (_a = error.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message : error.message;
452
+ const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
453
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
454
+ "div",
455
+ {
456
+ style: {
457
+ marginTop: idx === 0 ? 0 : 10,
458
+ marginBottom: 14
459
+ },
460
+ children: [
461
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
462
+ code && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
463
+ "div",
464
+ {
465
+ style: {
466
+ fontWeight: "600",
467
+ marginBottom: 4
468
+ },
469
+ children: [
470
+ "Copilot Cloud Error:",
471
+ " ",
472
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
473
+ ]
474
+ }
475
+ ),
476
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { children: message })
477
+ ]
478
+ },
479
+ idx
480
+ );
481
+ });
482
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
483
+ "div",
484
+ {
485
+ style: {
486
+ fontSize: "13px",
487
+ maxWidth: "600px"
488
+ },
489
+ children: [
490
+ errorsToRender,
491
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
492
+ ]
493
+ }
494
+ );
495
+ }
496
+ function useErrorToast() {
497
+ const { addToast } = useToast();
498
+ return (0, import_react6.useCallback)(
499
+ (error) => {
500
+ const errorId = error.map((err) => {
501
+ var _a, _b;
502
+ const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
503
+ const stack = err.stack || "";
504
+ return btoa(message + stack).slice(0, 32);
505
+ }).join("|");
506
+ addToast({
507
+ type: "error",
508
+ id: errorId,
509
+ // Toast libraries typically dedupe by id
510
+ message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors: error })
511
+ });
512
+ },
513
+ [addToast]
514
+ );
515
+ }
516
+ function useAsyncCallback(callback, deps) {
517
+ const addErrorToast = useErrorToast();
518
+ return (0, import_react6.useCallback)((...args) => __async(this, null, function* () {
519
+ try {
520
+ return yield callback(...args);
521
+ } catch (error) {
522
+ console.error("Error in async callback:", error);
523
+ addErrorToast([error]);
524
+ throw error;
525
+ }
526
+ }), deps);
527
+ }
528
+
529
+ // src/components/toast/toast-provider.tsx
530
+ var import_jsx_runtime4 = require("react/jsx-runtime");
531
+ var ToastContext = (0, import_react7.createContext)(void 0);
447
532
  function useToast() {
448
- const context = (0, import_react6.useContext)(ToastContext);
533
+ const context = (0, import_react7.useContext)(ToastContext);
449
534
  if (!context) {
450
535
  throw new Error("useToast must be used within a ToastProvider");
451
536
  }
@@ -455,68 +540,28 @@ function ToastProvider({
455
540
  enabled,
456
541
  children
457
542
  }) {
458
- const [toasts, setToasts] = (0, import_react6.useState)([]);
459
- const addToast = (0, import_react6.useCallback)((toast) => {
460
- const id = Math.random().toString(36).substring(2, 9);
461
- setToasts((currentToasts) => [...currentToasts, __spreadProps(__spreadValues({}, toast), { id })]);
543
+ const [toasts, setToasts] = (0, import_react7.useState)([]);
544
+ const addToast = (0, import_react7.useCallback)((toast) => {
545
+ var _a;
546
+ const id = (_a = toast.id) != null ? _a : Math.random().toString(36).substring(2, 9);
547
+ setToasts((currentToasts) => {
548
+ if (currentToasts.find((toast2) => toast2.id === id))
549
+ return currentToasts;
550
+ return [...currentToasts, __spreadProps(__spreadValues({}, toast), { id })];
551
+ });
462
552
  if (toast.duration) {
463
553
  setTimeout(() => {
464
554
  removeToast(id);
465
555
  }, toast.duration);
466
556
  }
467
557
  }, []);
468
- const addGraphQLErrorsToast = (0, import_react6.useCallback)((errors) => {
469
- const errorsToRender = errors.map((error, idx) => {
470
- var _a;
471
- const message = error.message;
472
- const code = (_a = error.extensions) == null ? void 0 : _a.code;
473
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
474
- "div",
475
- {
476
- style: {
477
- marginTop: idx === 0 ? 0 : 10,
478
- marginBottom: 14
479
- },
480
- children: [
481
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
482
- code && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
483
- "div",
484
- {
485
- style: {
486
- fontWeight: "600",
487
- marginBottom: 4
488
- },
489
- children: [
490
- "Copilot Cloud Error:",
491
- " ",
492
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
493
- ]
494
- }
495
- ),
496
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { children: message })
497
- ]
498
- },
499
- idx
500
- );
501
- });
558
+ const addGraphQLErrorsToast = (0, import_react7.useCallback)((errors) => {
502
559
  addToast({
503
560
  type: "error",
504
- message: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
505
- "div",
506
- {
507
- style: {
508
- fontSize: "13px",
509
- maxWidth: "600px"
510
- },
511
- children: [
512
- errorsToRender,
513
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This is a Copilot Cloud error, and it only displays during local development." })
514
- ]
515
- }
516
- )
561
+ message: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ErrorToast, { errors })
517
562
  });
518
563
  }, []);
519
- const removeToast = (0, import_react6.useCallback)((id) => {
564
+ const removeToast = (0, import_react7.useCallback)((id) => {
520
565
  setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));
521
566
  }, []);
522
567
  const value = {
@@ -526,8 +571,8 @@ function ToastProvider({
526
571
  removeToast,
527
572
  enabled
528
573
  };
529
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(ToastContext.Provider, { value, children: [
530
- /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
574
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(ToastContext.Provider, { value, children: [
575
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
531
576
  "div",
532
577
  {
533
578
  style: {
@@ -541,7 +586,7 @@ function ToastProvider({
541
586
  gap: "0.5rem"
542
587
  },
543
588
  children: [
544
- toasts.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { textAlign: "right" }, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
589
+ toasts.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { textAlign: "right" }, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
545
590
  "button",
546
591
  {
547
592
  onClick: () => setToasts([]),
@@ -556,7 +601,7 @@ function ToastProvider({
556
601
  children: "Close All"
557
602
  }
558
603
  ) }),
559
- toasts.map((toast) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
604
+ toasts.map((toast) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
560
605
  Toast,
561
606
  {
562
607
  message: toast.message,
@@ -582,7 +627,7 @@ function Toast({
582
627
  warning: "#eab308",
583
628
  error: "#ef4444"
584
629
  };
585
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
630
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
586
631
  "div",
587
632
  {
588
633
  style: {
@@ -595,8 +640,8 @@ function Toast({
595
640
  minWidth: "200px"
596
641
  },
597
642
  children: [
598
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { children: message }),
599
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
643
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: message }),
644
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
600
645
  "button",
601
646
  {
602
647
  onClick: onClose,
@@ -621,14 +666,17 @@ function Toast({
621
666
 
622
667
  // src/hooks/use-copilot-runtime-client.ts
623
668
  var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
624
- var import_react7 = require("react");
669
+ var import_react8 = require("react");
625
670
  var useCopilotRuntimeClient = (options) => {
626
671
  const { addGraphQLErrorsToast } = useToast();
627
- const runtimeClient = (0, import_react7.useMemo)(() => {
672
+ const addErrorToast = useErrorToast();
673
+ const runtimeClient = (0, import_react8.useMemo)(() => {
628
674
  return new import_runtime_client_gql.CopilotRuntimeClient(__spreadProps(__spreadValues({}, options), {
629
675
  handleGQLErrors: (error) => {
630
676
  if (error.graphQLErrors.length) {
631
677
  addGraphQLErrorsToast(error.graphQLErrors);
678
+ } else {
679
+ addErrorToast([error]);
632
680
  }
633
681
  }
634
682
  }));
@@ -649,8 +697,7 @@ function extract(_0) {
649
697
  data,
650
698
  abortSignal,
651
699
  stream,
652
- requestType = import_runtime_client_gql2.CopilotRequestType.Task,
653
- forwardedParameters
700
+ requestType = import_runtime_client_gql2.CopilotRequestType.Task
654
701
  }) {
655
702
  var _a, _b;
656
703
  const { messages } = context;
@@ -697,10 +744,10 @@ function extract(_0) {
697
744
  metadata: {
698
745
  requestType
699
746
  },
700
- forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), {
747
+ forwardedParameters: {
701
748
  toolChoice: "function",
702
749
  toolChoiceFunctionName: action.name
703
- })
750
+ }
704
751
  },
705
752
  properties: context.copilotApiConfig.properties,
706
753
  signal: abortSignal
@@ -784,13 +831,41 @@ function getHostname() {
784
831
  return "";
785
832
  }
786
833
 
834
+ // src/components/error-boundary/error-boundary.tsx
835
+ var import_react9 = __toESM(require("react"));
836
+ var import_jsx_runtime5 = require("react/jsx-runtime");
837
+ var CopilotErrorBoundary = class extends import_react9.default.Component {
838
+ constructor(props) {
839
+ super(props);
840
+ this.state = { hasError: false };
841
+ }
842
+ static getDerivedStateFromError(error) {
843
+ return { hasError: true, error };
844
+ }
845
+ componentDidCatch(error, errorInfo) {
846
+ console.error("CopilotKit Error:", error, errorInfo);
847
+ }
848
+ render() {
849
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(ErrorToast2, { error: this.state.error, children: this.props.children });
850
+ }
851
+ };
852
+ function ErrorToast2({ error, children }) {
853
+ const addErrorToast = useErrorToast();
854
+ (0, import_react9.useEffect)(() => {
855
+ if (error) {
856
+ addErrorToast([error]);
857
+ }
858
+ }, [error, addErrorToast]);
859
+ return children;
860
+ }
861
+
787
862
  // src/components/copilot-provider/copilotkit.tsx
788
- var import_jsx_runtime4 = require("react/jsx-runtime");
863
+ var import_jsx_runtime6 = require("react/jsx-runtime");
789
864
  function CopilotKit(_a) {
790
865
  var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
791
866
  const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole;
792
867
  const enabled = shouldShowDevConsole(showDevConsole);
793
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ToastProvider, { enabled, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children })) });
868
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ToastProvider, { enabled, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(CopilotErrorBoundary, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children })) }) });
794
869
  }
795
870
  function CopilotKitInternal(_a) {
796
871
  var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
@@ -800,49 +875,49 @@ function CopilotKitInternal(_a) {
800
875
  );
801
876
  }
802
877
  const chatApiEndpoint = props.runtimeUrl || import_shared4.COPILOT_CLOUD_CHAT_URL;
803
- const [actions, setActions] = (0, import_react8.useState)({});
804
- const [coAgentStateRenders, setCoAgentStateRenders] = (0, import_react8.useState)({});
805
- const chatComponentsCache = (0, import_react8.useRef)({
878
+ const [actions, setActions] = (0, import_react10.useState)({});
879
+ const [coAgentStateRenders, setCoAgentStateRenders] = (0, import_react10.useState)({});
880
+ const chatComponentsCache = (0, import_react10.useRef)({
806
881
  actions: {},
807
882
  coAgentStateRenders: {}
808
883
  });
809
884
  const { addElement, removeElement, printTree } = use_tree_default();
810
- const [isLoading, setIsLoading] = (0, import_react8.useState)(false);
811
- const [chatInstructions, setChatInstructions] = (0, import_react8.useState)("");
885
+ const [isLoading, setIsLoading] = (0, import_react10.useState)(false);
886
+ const [chatInstructions, setChatInstructions] = (0, import_react10.useState)("");
812
887
  const {
813
888
  addElement: addDocument,
814
889
  removeElement: removeDocument,
815
890
  allElements: allDocuments
816
891
  } = use_flat_category_store_default();
817
- const setAction = (0, import_react8.useCallback)((id, action) => {
892
+ const setAction = (0, import_react10.useCallback)((id, action) => {
818
893
  setActions((prevPoints) => {
819
894
  return __spreadProps(__spreadValues({}, prevPoints), {
820
895
  [id]: action
821
896
  });
822
897
  });
823
898
  }, []);
824
- const removeAction = (0, import_react8.useCallback)((id) => {
899
+ const removeAction = (0, import_react10.useCallback)((id) => {
825
900
  setActions((prevPoints) => {
826
901
  const newPoints = __spreadValues({}, prevPoints);
827
902
  delete newPoints[id];
828
903
  return newPoints;
829
904
  });
830
905
  }, []);
831
- const setCoAgentStateRender = (0, import_react8.useCallback)((id, stateRender) => {
906
+ const setCoAgentStateRender = (0, import_react10.useCallback)((id, stateRender) => {
832
907
  setCoAgentStateRenders((prevPoints) => {
833
908
  return __spreadProps(__spreadValues({}, prevPoints), {
834
909
  [id]: stateRender
835
910
  });
836
911
  });
837
912
  }, []);
838
- const removeCoAgentStateRender = (0, import_react8.useCallback)((id) => {
913
+ const removeCoAgentStateRender = (0, import_react10.useCallback)((id) => {
839
914
  setCoAgentStateRenders((prevPoints) => {
840
915
  const newPoints = __spreadValues({}, prevPoints);
841
916
  delete newPoints[id];
842
917
  return newPoints;
843
918
  });
844
919
  }, []);
845
- const getContextString = (0, import_react8.useCallback)(
920
+ const getContextString = (0, import_react10.useCallback)(
846
921
  (documents, categories) => {
847
922
  const documentsString = documents.map((document) => {
848
923
  return `${document.name} (${document.sourceApplication}):
@@ -855,37 +930,37 @@ ${nonDocumentStrings}`;
855
930
  },
856
931
  [printTree]
857
932
  );
858
- const addContext = (0, import_react8.useCallback)(
933
+ const addContext = (0, import_react10.useCallback)(
859
934
  (context, parentId, categories = defaultCopilotContextCategories) => {
860
935
  return addElement(context, categories, parentId);
861
936
  },
862
937
  [addElement]
863
938
  );
864
- const removeContext = (0, import_react8.useCallback)(
939
+ const removeContext = (0, import_react10.useCallback)(
865
940
  (id) => {
866
941
  removeElement(id);
867
942
  },
868
943
  [removeElement]
869
944
  );
870
- const getFunctionCallHandler = (0, import_react8.useCallback)(
945
+ const getFunctionCallHandler = (0, import_react10.useCallback)(
871
946
  (customEntryPoints) => {
872
947
  return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
873
948
  },
874
949
  [actions]
875
950
  );
876
- const getDocumentsContext = (0, import_react8.useCallback)(
951
+ const getDocumentsContext = (0, import_react10.useCallback)(
877
952
  (categories) => {
878
953
  return allDocuments(categories);
879
954
  },
880
955
  [allDocuments]
881
956
  );
882
- const addDocumentContext = (0, import_react8.useCallback)(
957
+ const addDocumentContext = (0, import_react10.useCallback)(
883
958
  (documentPointer, categories = defaultCopilotContextCategories) => {
884
959
  return addDocument(documentPointer, categories);
885
960
  },
886
961
  [addDocument]
887
962
  );
888
- const removeDocumentContext = (0, import_react8.useCallback)(
963
+ const removeDocumentContext = (0, import_react10.useCallback)(
889
964
  (documentId) => {
890
965
  removeDocument(documentId);
891
966
  },
@@ -898,7 +973,7 @@ ${nonDocumentStrings}`;
898
973
  );
899
974
  }
900
975
  }
901
- const copilotApiConfig = (0, import_react8.useMemo)(() => {
976
+ const copilotApiConfig = (0, import_react10.useMemo)(() => {
902
977
  var _a2, _b2;
903
978
  let cloud = void 0;
904
979
  if (props.publicApiKey) {
@@ -940,7 +1015,7 @@ ${nonDocumentStrings}`;
940
1015
  headers,
941
1016
  credentials: copilotApiConfig.credentials
942
1017
  });
943
- const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, import_react8.useState)({});
1018
+ const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, import_react10.useState)({});
944
1019
  const addChatSuggestionConfiguration = (id, suggestion) => {
945
1020
  setChatSuggestionConfiguration((prev) => __spreadProps(__spreadValues({}, prev), { [id]: suggestion }));
946
1021
  };
@@ -950,9 +1025,9 @@ ${nonDocumentStrings}`;
950
1025
  return rest;
951
1026
  });
952
1027
  };
953
- const [coagentStates, setCoagentStates] = (0, import_react8.useState)({});
954
- const coagentStatesRef = (0, import_react8.useRef)({});
955
- const setCoagentStatesWithRef = (0, import_react8.useCallback)(
1028
+ const [coagentStates, setCoagentStates] = (0, import_react10.useState)({});
1029
+ const coagentStatesRef = (0, import_react10.useRef)({});
1030
+ const setCoagentStatesWithRef = (0, import_react10.useCallback)(
956
1031
  (value) => {
957
1032
  const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value;
958
1033
  coagentStatesRef.current = newValue;
@@ -968,9 +1043,9 @@ ${nonDocumentStrings}`;
968
1043
  agentName: props.agent
969
1044
  };
970
1045
  }
971
- const [agentSession, setAgentSession] = (0, import_react8.useState)(initialAgentSession);
1046
+ const [agentSession, setAgentSession] = (0, import_react10.useState)(initialAgentSession);
972
1047
  const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole;
973
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1048
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
974
1049
  CopilotContext.Provider,
975
1050
  {
976
1051
  value: {
@@ -1003,10 +1078,9 @@ ${nonDocumentStrings}`;
1003
1078
  setCoagentStatesWithRef,
1004
1079
  agentSession,
1005
1080
  setAgentSession,
1006
- runtimeClient,
1007
- forwardedParameters: props.forwardedParameters || {}
1081
+ runtimeClient
1008
1082
  },
1009
- children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CopilotMessages, { children })
1083
+ children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(CopilotMessages, { children })
1010
1084
  }
1011
1085
  );
1012
1086
  }
@@ -1038,11 +1112,11 @@ function entryPointsToFunctionCallHandler(actions) {
1038
1112
  }
1039
1113
 
1040
1114
  // src/hooks/use-copilot-chat.ts
1041
- var import_react10 = require("react");
1115
+ var import_react12 = require("react");
1042
1116
  var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
1043
1117
 
1044
1118
  // src/hooks/use-chat.ts
1045
- var import_react9 = require("react");
1119
+ var import_react11 = require("react");
1046
1120
  var import_shared5 = require("@copilotkit/shared");
1047
1121
  var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
1048
1122
  function useChat(options) {
@@ -1062,12 +1136,12 @@ function useChat(options) {
1062
1136
  agentSession,
1063
1137
  setAgentSession
1064
1138
  } = options;
1065
- const abortControllerRef = (0, import_react9.useRef)();
1066
- const threadIdRef = (0, import_react9.useRef)(null);
1067
- const runIdRef = (0, import_react9.useRef)(null);
1139
+ const abortControllerRef = (0, import_react11.useRef)();
1140
+ const threadIdRef = (0, import_react11.useRef)(null);
1141
+ const runIdRef = (0, import_react11.useRef)(null);
1068
1142
  const { addGraphQLErrorsToast } = useToast();
1069
- const runChatCompletionRef = (0, import_react9.useRef)();
1070
- const agentSessionRef = (0, import_react9.useRef)(agentSession);
1143
+ const runChatCompletionRef = (0, import_react11.useRef)();
1144
+ const agentSessionRef = (0, import_react11.useRef)(agentSession);
1071
1145
  agentSessionRef.current = agentSession;
1072
1146
  const publicApiKey = copilotConfig.publicApiKey;
1073
1147
  const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared5.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
@@ -1077,211 +1151,236 @@ function useChat(options) {
1077
1151
  headers,
1078
1152
  credentials: copilotConfig.credentials
1079
1153
  });
1080
- const runChatCompletion = (previousMessages) => __async(this, null, function* () {
1081
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1082
- setIsLoading(true);
1083
- let newMessages = [
1084
- new import_runtime_client_gql4.TextMessage({
1085
- content: "",
1086
- role: import_runtime_client_gql4.Role.Assistant
1087
- })
1088
- ];
1089
- const abortController = new AbortController();
1090
- abortControllerRef.current = abortController;
1091
- setMessages([...previousMessages, ...newMessages]);
1092
- const systemMessage = makeSystemMessageCallback();
1093
- const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
1094
- const stream = runtimeClient.asStream(
1095
- runtimeClient.generateCopilotResponse({
1096
- data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
1097
- frontend: {
1098
- actions: actions.filter(
1099
- (action) => action.available !== import_runtime_client_gql4.ActionInputAvailability.Disabled || !action.disabled
1100
- ).map((action) => {
1101
- let available = import_runtime_client_gql4.ActionInputAvailability.Enabled;
1102
- if (action.disabled) {
1103
- available = import_runtime_client_gql4.ActionInputAvailability.Disabled;
1104
- } else if (action.available === "disabled") {
1105
- available = import_runtime_client_gql4.ActionInputAvailability.Disabled;
1106
- } else if (action.available === "remote") {
1107
- available = import_runtime_client_gql4.ActionInputAvailability.Remote;
1108
- }
1109
- return {
1110
- name: action.name,
1111
- description: action.description || "",
1112
- jsonSchema: JSON.stringify((0, import_shared5.actionParametersToJsonSchema)(action.parameters || [])),
1113
- available
1114
- };
1115
- }),
1116
- url: window.location.href
1117
- },
1118
- threadId: threadIdRef.current,
1119
- runId: runIdRef.current,
1120
- messages: (0, import_runtime_client_gql4.convertMessagesToGqlInput)((0, import_runtime_client_gql4.filterAgentStateMessages)(messagesWithContext))
1121
- }, copilotConfig.cloud ? {
1122
- cloud: __spreadValues({}, ((_c = (_b = (_a = copilotConfig.cloud.guardrails) == null ? void 0 : _a.input) == null ? void 0 : _b.restrictToTopic) == null ? void 0 : _c.enabled) ? {
1123
- guardrails: {
1124
- inputValidationRules: {
1125
- allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
1126
- denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
1154
+ const runChatCompletion = useAsyncCallback(
1155
+ (previousMessages) => __async(this, null, function* () {
1156
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1157
+ setIsLoading(true);
1158
+ let newMessages = [
1159
+ new import_runtime_client_gql4.TextMessage({
1160
+ content: "",
1161
+ role: import_runtime_client_gql4.Role.Assistant
1162
+ })
1163
+ ];
1164
+ const abortController = new AbortController();
1165
+ abortControllerRef.current = abortController;
1166
+ setMessages([...previousMessages, ...newMessages]);
1167
+ const systemMessage = makeSystemMessageCallback();
1168
+ const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
1169
+ const stream = runtimeClient.asStream(
1170
+ runtimeClient.generateCopilotResponse({
1171
+ data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
1172
+ frontend: {
1173
+ actions: actions.filter(
1174
+ (action) => action.available !== import_runtime_client_gql4.ActionInputAvailability.Disabled || !action.disabled
1175
+ ).map((action) => {
1176
+ let available = import_runtime_client_gql4.ActionInputAvailability.Enabled;
1177
+ if (action.disabled) {
1178
+ available = import_runtime_client_gql4.ActionInputAvailability.Disabled;
1179
+ } else if (action.available === "disabled") {
1180
+ available = import_runtime_client_gql4.ActionInputAvailability.Disabled;
1181
+ } else if (action.available === "remote") {
1182
+ available = import_runtime_client_gql4.ActionInputAvailability.Remote;
1183
+ }
1184
+ return {
1185
+ name: action.name,
1186
+ description: action.description || "",
1187
+ jsonSchema: JSON.stringify(
1188
+ (0, import_shared5.actionParametersToJsonSchema)(action.parameters || [])
1189
+ ),
1190
+ available
1191
+ };
1192
+ }),
1193
+ url: window.location.href
1194
+ },
1195
+ threadId: threadIdRef.current,
1196
+ runId: runIdRef.current,
1197
+ messages: (0, import_runtime_client_gql4.convertMessagesToGqlInput)((0, import_runtime_client_gql4.filterAgentStateMessages)(messagesWithContext))
1198
+ }, copilotConfig.cloud ? {
1199
+ cloud: __spreadValues({}, ((_c = (_b = (_a = copilotConfig.cloud.guardrails) == null ? void 0 : _a.input) == null ? void 0 : _b.restrictToTopic) == null ? void 0 : _c.enabled) ? {
1200
+ guardrails: {
1201
+ inputValidationRules: {
1202
+ allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
1203
+ denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
1204
+ }
1127
1205
  }
1206
+ } : {})
1207
+ } : {}), {
1208
+ metadata: {
1209
+ requestType: import_runtime_client_gql4.CopilotRequestType.Chat
1128
1210
  }
1129
- } : {})
1130
- } : {}), {
1131
- metadata: {
1132
- requestType: import_runtime_client_gql4.CopilotRequestType.Chat
1211
+ }), agentSessionRef.current ? {
1212
+ agentSession: agentSessionRef.current
1213
+ } : {}), {
1214
+ agentStates: Object.values(coagentStatesRef.current).map((state) => ({
1215
+ agentName: state.name,
1216
+ state: JSON.stringify(state.state)
1217
+ }))
1218
+ }),
1219
+ properties: copilotConfig.properties,
1220
+ signal: (_d = abortControllerRef.current) == null ? void 0 : _d.signal
1221
+ })
1222
+ );
1223
+ const guardrailsEnabled = ((_g = (_f = (_e = copilotConfig.cloud) == null ? void 0 : _e.guardrails) == null ? void 0 : _f.input) == null ? void 0 : _g.restrictToTopic.enabled) || false;
1224
+ const reader = stream.getReader();
1225
+ let actionResults = {};
1226
+ let executedCoAgentStateRenders = [];
1227
+ let followUp = void 0;
1228
+ try {
1229
+ while (true) {
1230
+ let done, value;
1231
+ try {
1232
+ const readResult = yield reader.read();
1233
+ done = readResult.done;
1234
+ value = readResult.value;
1235
+ } catch (readError) {
1236
+ break;
1133
1237
  }
1134
- }), agentSessionRef.current ? {
1135
- agentSession: agentSessionRef.current
1136
- } : {}), {
1137
- agentStates: Object.values(coagentStatesRef.current).map((state) => ({
1138
- agentName: state.name,
1139
- state: JSON.stringify(state.state)
1140
- })),
1141
- forwardedParameters: options.forwardedParameters || {}
1142
- }),
1143
- properties: copilotConfig.properties,
1144
- signal: (_d = abortControllerRef.current) == null ? void 0 : _d.signal
1145
- })
1146
- );
1147
- const guardrailsEnabled = ((_g = (_f = (_e = copilotConfig.cloud) == null ? void 0 : _e.guardrails) == null ? void 0 : _f.input) == null ? void 0 : _g.restrictToTopic.enabled) || false;
1148
- const reader = stream.getReader();
1149
- let actionResults = {};
1150
- let executedCoAgentStateRenders = [];
1151
- let followUp = void 0;
1152
- try {
1153
- while (true) {
1154
- let done, value;
1155
- try {
1156
- const readResult = yield reader.read();
1157
- done = readResult.done;
1158
- value = readResult.value;
1159
- } catch (readError) {
1160
- break;
1161
- }
1162
- if (done) {
1163
- break;
1164
- }
1165
- if (!(value == null ? void 0 : value.generateCopilotResponse)) {
1166
- continue;
1167
- }
1168
- threadIdRef.current = value.generateCopilotResponse.threadId || null;
1169
- runIdRef.current = value.generateCopilotResponse.runId || null;
1170
- const messages2 = (0, import_runtime_client_gql4.convertGqlOutputToMessages)(
1171
- (0, import_runtime_client_gql4.filterAdjacentAgentStateMessages)(value.generateCopilotResponse.messages)
1172
- );
1173
- if (messages2.length === 0) {
1174
- continue;
1175
- }
1176
- newMessages = [];
1177
- if (((_h = value.generateCopilotResponse.status) == null ? void 0 : _h.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
1178
- newMessages = [
1179
- new import_runtime_client_gql4.TextMessage({
1180
- role: import_runtime_client_gql4.MessageRole.Assistant,
1181
- content: ((_i = value.generateCopilotResponse.status.details) == null ? void 0 : _i.guardrailsReason) || ""
1182
- })
1183
- ];
1184
- } else {
1185
- for (const message of messages2) {
1186
- newMessages.push(message);
1187
- if (message.isActionExecutionMessage() && message.status.code !== import_runtime_client_gql4.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
1188
- if (!(message.id in actionResults)) {
1238
+ if (done) {
1239
+ break;
1240
+ }
1241
+ if (!(value == null ? void 0 : value.generateCopilotResponse)) {
1242
+ continue;
1243
+ }
1244
+ threadIdRef.current = value.generateCopilotResponse.threadId || null;
1245
+ runIdRef.current = value.generateCopilotResponse.runId || null;
1246
+ const messages2 = (0, import_runtime_client_gql4.convertGqlOutputToMessages)(
1247
+ (0, import_runtime_client_gql4.filterAdjacentAgentStateMessages)(value.generateCopilotResponse.messages)
1248
+ );
1249
+ if (messages2.length === 0) {
1250
+ continue;
1251
+ }
1252
+ newMessages = [];
1253
+ if (((_h = value.generateCopilotResponse.status) == null ? void 0 : _h.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
1254
+ newMessages = [
1255
+ new import_runtime_client_gql4.TextMessage({
1256
+ role: import_runtime_client_gql4.MessageRole.Assistant,
1257
+ content: ((_i = value.generateCopilotResponse.status.details) == null ? void 0 : _i.guardrailsReason) || ""
1258
+ })
1259
+ ];
1260
+ } else {
1261
+ for (const message of messages2) {
1262
+ newMessages.push(message);
1263
+ if (message.isActionExecutionMessage() && message.status.code !== import_runtime_client_gql4.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
1264
+ if (!(message.id in actionResults)) {
1265
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
1266
+ break;
1267
+ }
1268
+ try {
1269
+ setMessages([...previousMessages, ...newMessages]);
1270
+ const action = actions.find((action2) => action2.name === message.name);
1271
+ if (action) {
1272
+ followUp = action.followUp;
1273
+ }
1274
+ const result = yield onFunctionCall({
1275
+ messages: previousMessages,
1276
+ name: message.name,
1277
+ args: message.arguments
1278
+ });
1279
+ actionResults[message.id] = result;
1280
+ } catch (e) {
1281
+ actionResults[message.id] = `Failed to execute action ${message.name}`;
1282
+ console.error(`Failed to execute action ${message.name}: ${e}`);
1283
+ }
1284
+ }
1285
+ newMessages.push(
1286
+ new import_runtime_client_gql4.ResultMessage({
1287
+ result: import_runtime_client_gql4.ResultMessage.encodeResult(actionResults[message.id]),
1288
+ actionExecutionId: message.id,
1289
+ actionName: message.name
1290
+ })
1291
+ );
1292
+ }
1293
+ if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
1189
1294
  if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
1190
1295
  break;
1191
1296
  }
1192
- try {
1193
- setMessages([...previousMessages, ...newMessages]);
1194
- const action = actions.find((action2) => action2.name === message.name);
1195
- if (action) {
1196
- followUp = action.followUp;
1197
- }
1198
- const result = yield onFunctionCall({
1199
- messages: previousMessages,
1200
- name: message.name,
1201
- args: message.arguments
1202
- });
1203
- actionResults[message.id] = result;
1204
- } catch (e) {
1205
- actionResults[message.id] = `Failed to execute action ${message.name}`;
1206
- console.error(`Failed to execute action ${message.name}: ${e}`);
1207
- }
1297
+ yield onCoAgentStateRender({
1298
+ name: message.agentName,
1299
+ nodeName: message.nodeName,
1300
+ state: message.state
1301
+ });
1302
+ executedCoAgentStateRenders.push(message.id);
1208
1303
  }
1209
- newMessages.push(
1210
- new import_runtime_client_gql4.ResultMessage({
1211
- result: import_runtime_client_gql4.ResultMessage.encodeResult(actionResults[message.id]),
1212
- actionExecutionId: message.id,
1213
- actionName: message.name
1214
- })
1215
- );
1216
1304
  }
1217
- if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
1218
- if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
1219
- break;
1305
+ const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
1306
+ if (lastAgentStateMessage) {
1307
+ setCoagentStatesWithRef((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
1308
+ [lastAgentStateMessage.agentName]: {
1309
+ name: lastAgentStateMessage.agentName,
1310
+ state: lastAgentStateMessage.state,
1311
+ running: lastAgentStateMessage.running,
1312
+ active: lastAgentStateMessage.active,
1313
+ threadId: lastAgentStateMessage.threadId,
1314
+ nodeName: lastAgentStateMessage.nodeName,
1315
+ runId: lastAgentStateMessage.runId
1316
+ }
1317
+ }));
1318
+ if (lastAgentStateMessage.running) {
1319
+ setAgentSession({
1320
+ threadId: lastAgentStateMessage.threadId,
1321
+ agentName: lastAgentStateMessage.agentName,
1322
+ nodeName: lastAgentStateMessage.nodeName
1323
+ });
1324
+ } else {
1325
+ setAgentSession(null);
1220
1326
  }
1221
- yield onCoAgentStateRender({
1222
- name: message.agentName,
1223
- nodeName: message.nodeName,
1224
- state: message.state
1225
- });
1226
- executedCoAgentStateRenders.push(message.id);
1227
1327
  }
1228
1328
  }
1229
- const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
1230
- if (lastAgentStateMessage) {
1231
- setCoagentStatesWithRef((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
1232
- [lastAgentStateMessage.agentName]: {
1233
- name: lastAgentStateMessage.agentName,
1234
- state: lastAgentStateMessage.state,
1235
- running: lastAgentStateMessage.running,
1236
- active: lastAgentStateMessage.active,
1237
- threadId: lastAgentStateMessage.threadId,
1238
- nodeName: lastAgentStateMessage.nodeName,
1239
- runId: lastAgentStateMessage.runId
1240
- }
1241
- }));
1242
- if (lastAgentStateMessage.running) {
1243
- setAgentSession({
1244
- threadId: lastAgentStateMessage.threadId,
1245
- agentName: lastAgentStateMessage.agentName,
1246
- nodeName: lastAgentStateMessage.nodeName
1247
- });
1248
- } else {
1249
- setAgentSession(null);
1250
- }
1329
+ if (newMessages.length > 0) {
1330
+ setMessages([...previousMessages, ...newMessages]);
1251
1331
  }
1252
1332
  }
1253
- if (newMessages.length > 0) {
1254
- setMessages([...previousMessages, ...newMessages]);
1333
+ if (
1334
+ // if followUp is not explicitly false
1335
+ followUp !== false && // if we have client side results
1336
+ (Object.values(actionResults).length || // or the last message we received is a result
1337
+ newMessages.length && newMessages[newMessages.length - 1].isResultMessage())
1338
+ ) {
1339
+ yield new Promise((resolve) => setTimeout(resolve, 10));
1340
+ return yield runChatCompletionRef.current([...previousMessages, ...newMessages]);
1341
+ } else {
1342
+ return newMessages.slice();
1255
1343
  }
1344
+ } finally {
1345
+ setIsLoading(false);
1256
1346
  }
1257
- if (
1258
- // if followUp is not explicitly false
1259
- followUp !== false && // if we have client side results
1260
- (Object.values(actionResults).length || // or the last message we received is a result
1261
- newMessages.length && newMessages[newMessages.length - 1].isResultMessage())
1262
- ) {
1263
- yield new Promise((resolve) => setTimeout(resolve, 10));
1264
- return yield runChatCompletionRef.current([...previousMessages, ...newMessages]);
1265
- } else {
1266
- return newMessages.slice();
1267
- }
1268
- } finally {
1269
- setIsLoading(false);
1270
- }
1271
- });
1347
+ }),
1348
+ [
1349
+ messages,
1350
+ setMessages,
1351
+ makeSystemMessageCallback,
1352
+ copilotConfig,
1353
+ setIsLoading,
1354
+ initialMessages,
1355
+ isLoading,
1356
+ actions,
1357
+ onFunctionCall,
1358
+ onCoAgentStateRender,
1359
+ setCoagentStatesWithRef,
1360
+ coagentStatesRef,
1361
+ agentSession,
1362
+ setAgentSession
1363
+ ]
1364
+ );
1272
1365
  runChatCompletionRef.current = runChatCompletion;
1273
- const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
1274
- yield runChatCompletionRef.current(messages2);
1275
- });
1276
- const append = (message) => __async(this, null, function* () {
1277
- if (isLoading) {
1278
- return;
1279
- }
1280
- const newMessages = [...messages, message];
1281
- setMessages(newMessages);
1282
- return runChatCompletionAndHandleFunctionCall(newMessages);
1283
- });
1284
- const reload = () => __async(this, null, function* () {
1366
+ const runChatCompletionAndHandleFunctionCall = useAsyncCallback(
1367
+ (messages2) => __async(this, null, function* () {
1368
+ yield runChatCompletionRef.current(messages2);
1369
+ }),
1370
+ [messages]
1371
+ );
1372
+ const append = useAsyncCallback(
1373
+ (message) => __async(this, null, function* () {
1374
+ if (isLoading) {
1375
+ return;
1376
+ }
1377
+ const newMessages = [...messages, message];
1378
+ setMessages(newMessages);
1379
+ return runChatCompletionAndHandleFunctionCall(newMessages);
1380
+ }),
1381
+ [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
1382
+ );
1383
+ const reload = useAsyncCallback(() => __async(this, null, function* () {
1285
1384
  if (isLoading || messages.length === 0) {
1286
1385
  return;
1287
1386
  }
@@ -1292,7 +1391,7 @@ function useChat(options) {
1292
1391
  }
1293
1392
  setMessages(newMessages);
1294
1393
  return runChatCompletionAndHandleFunctionCall(newMessages);
1295
- });
1394
+ }), [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);
1296
1395
  const stop = () => {
1297
1396
  var _a;
1298
1397
  (_a = abortControllerRef.current) == null ? void 0 : _a.abort();
@@ -1324,18 +1423,17 @@ function useCopilotChat(_a = {}) {
1324
1423
  setCoagentStatesWithRef,
1325
1424
  coAgentStateRenders,
1326
1425
  agentSession,
1327
- setAgentSession,
1328
- forwardedParameters
1426
+ setAgentSession
1329
1427
  } = useCopilotContext();
1330
1428
  const { messages, setMessages } = useCopilotMessagesContext();
1331
1429
  const latestGetContextString = useUpdatedRef(getContextString);
1332
- const deleteMessage = (0, import_react10.useCallback)(
1430
+ const deleteMessage = (0, import_react12.useCallback)(
1333
1431
  (messageId) => {
1334
1432
  setMessages((prev) => prev.filter((message) => message.id !== messageId));
1335
1433
  },
1336
1434
  [setMessages]
1337
1435
  );
1338
- const makeSystemMessageCallback = (0, import_react10.useCallback)(() => {
1436
+ const makeSystemMessageCallback = (0, import_react12.useCallback)(() => {
1339
1437
  const systemMessageMaker = makeSystemMessage2 || defaultSystemMessage;
1340
1438
  const contextString = latestGetContextString.current([], defaultCopilotContextCategories);
1341
1439
  return new import_runtime_client_gql5.TextMessage({
@@ -1343,7 +1441,7 @@ function useCopilotChat(_a = {}) {
1343
1441
  role: import_runtime_client_gql5.Role.System
1344
1442
  });
1345
1443
  }, [getContextString, makeSystemMessage2, chatInstructions]);
1346
- const onCoAgentStateRender = (0, import_react10.useCallback)(
1444
+ const onCoAgentStateRender = useAsyncCallback(
1347
1445
  (args) => __async(this, null, function* () {
1348
1446
  var _a2;
1349
1447
  const { name, nodeName, state } = args;
@@ -1375,42 +1473,41 @@ function useCopilotChat(_a = {}) {
1375
1473
  coagentStatesRef,
1376
1474
  setCoagentStatesWithRef,
1377
1475
  agentSession,
1378
- setAgentSession,
1379
- forwardedParameters
1476
+ setAgentSession
1380
1477
  }));
1381
1478
  const latestAppend = useUpdatedRef(append);
1382
- const latestAppendFunc = (0, import_react10.useCallback)(
1383
- (message) => {
1384
- return latestAppend.current(message);
1385
- },
1479
+ const latestAppendFunc = useAsyncCallback(
1480
+ (message) => __async(this, null, function* () {
1481
+ return yield latestAppend.current(message);
1482
+ }),
1386
1483
  [latestAppend]
1387
1484
  );
1388
1485
  const latestReload = useUpdatedRef(reload);
1389
- const latestReloadFunc = (0, import_react10.useCallback)(() => {
1390
- return latestReload.current();
1391
- }, [latestReload]);
1486
+ const latestReloadFunc = useAsyncCallback(() => __async(this, null, function* () {
1487
+ return yield latestReload.current();
1488
+ }), [latestReload]);
1392
1489
  const latestStop = useUpdatedRef(stop);
1393
- const latestStopFunc = (0, import_react10.useCallback)(() => {
1490
+ const latestStopFunc = (0, import_react12.useCallback)(() => {
1394
1491
  return latestStop.current();
1395
1492
  }, [latestStop]);
1396
1493
  const latestDelete = useUpdatedRef(deleteMessage);
1397
- const latestDeleteFunc = (0, import_react10.useCallback)(
1494
+ const latestDeleteFunc = (0, import_react12.useCallback)(
1398
1495
  (messageId) => {
1399
1496
  return latestDelete.current(messageId);
1400
1497
  },
1401
1498
  [latestDelete]
1402
1499
  );
1403
1500
  const latestSetMessages = useUpdatedRef(setMessages);
1404
- const latestSetMessagesFunc = (0, import_react10.useCallback)(
1501
+ const latestSetMessagesFunc = (0, import_react12.useCallback)(
1405
1502
  (messages2) => {
1406
1503
  return latestSetMessages.current(messages2);
1407
1504
  },
1408
1505
  [latestSetMessages]
1409
1506
  );
1410
1507
  const latestRunChatCompletion = useUpdatedRef(runChatCompletion);
1411
- const latestRunChatCompletionFunc = (0, import_react10.useCallback)(() => {
1412
- return latestRunChatCompletion.current();
1413
- }, [latestRunChatCompletion]);
1508
+ const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () {
1509
+ return yield latestRunChatCompletion.current();
1510
+ }), [latestRunChatCompletion]);
1414
1511
  return {
1415
1512
  visibleMessages: messages,
1416
1513
  appendMessage: latestAppendFunc,
@@ -1423,8 +1520,8 @@ function useCopilotChat(_a = {}) {
1423
1520
  };
1424
1521
  }
1425
1522
  function useUpdatedRef(value) {
1426
- const ref = (0, import_react10.useRef)(value);
1427
- (0, import_react10.useEffect)(() => {
1523
+ const ref = (0, import_react12.useRef)(value);
1524
+ (0, import_react12.useEffect)(() => {
1428
1525
  ref.current = value;
1429
1526
  }, [value]);
1430
1527
  return ref;
@@ -1455,17 +1552,17 @@ ${additionalInstructions}` : "");
1455
1552
 
1456
1553
  // src/hooks/use-copilot-action.ts
1457
1554
  var import_shared6 = require("@copilotkit/shared");
1458
- var import_react11 = require("react");
1555
+ var import_react13 = require("react");
1459
1556
  function useCopilotAction(action, dependencies) {
1460
1557
  const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
1461
- const idRef = (0, import_react11.useRef)((0, import_shared6.randomId)());
1462
- const renderAndWaitRef = (0, import_react11.useRef)(null);
1558
+ const idRef = (0, import_react13.useRef)((0, import_shared6.randomId)());
1559
+ const renderAndWaitRef = (0, import_react13.useRef)(null);
1463
1560
  action = __spreadValues({}, action);
1464
1561
  if (action.renderAndWait || action.renderAndWaitForResponse) {
1465
1562
  const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;
1466
1563
  action.renderAndWait = void 0;
1467
1564
  action.renderAndWaitForResponse = void 0;
1468
- action.handler = () => __async(this, null, function* () {
1565
+ action.handler = useAsyncCallback(() => __async(this, null, function* () {
1469
1566
  let resolve;
1470
1567
  let reject;
1471
1568
  const promise = new Promise((resolvePromise, rejectPromise) => {
@@ -1474,7 +1571,7 @@ function useCopilotAction(action, dependencies) {
1474
1571
  });
1475
1572
  renderAndWaitRef.current = { promise, resolve, reject };
1476
1573
  return yield promise;
1477
- });
1574
+ }), []);
1478
1575
  action.render = (props) => {
1479
1576
  const waitProps = {
1480
1577
  status: props.status,
@@ -1494,7 +1591,7 @@ function useCopilotAction(action, dependencies) {
1494
1591
  return renderAndWait(waitProps);
1495
1592
  }
1496
1593
  }
1497
- return (0, import_react11.createElement)(import_react11.Fragment);
1594
+ return (0, import_react13.createElement)(import_react13.Fragment);
1498
1595
  };
1499
1596
  }
1500
1597
  if (dependencies === void 0) {
@@ -1507,7 +1604,7 @@ function useCopilotAction(action, dependencies) {
1507
1604
  }
1508
1605
  }
1509
1606
  }
1510
- (0, import_react11.useEffect)(() => {
1607
+ (0, import_react13.useEffect)(() => {
1511
1608
  setAction(idRef.current, action);
1512
1609
  if (chatComponentsCache.current !== null && action.render !== void 0) {
1513
1610
  chatComponentsCache.current.actions[action.name] = action.render;
@@ -1533,7 +1630,7 @@ function useCopilotAction(action, dependencies) {
1533
1630
  }
1534
1631
 
1535
1632
  // src/hooks/use-coagent-state-render.ts
1536
- var import_react12 = require("react");
1633
+ var import_react14 = require("react");
1537
1634
  var import_shared7 = require("@copilotkit/shared");
1538
1635
  function useCoAgentStateRender(action, dependencies) {
1539
1636
  const {
@@ -1541,8 +1638,8 @@ function useCoAgentStateRender(action, dependencies) {
1541
1638
  removeCoAgentStateRender,
1542
1639
  coAgentStateRenders,
1543
1640
  chatComponentsCache
1544
- } = (0, import_react12.useContext)(CopilotContext);
1545
- const idRef = (0, import_react12.useRef)((0, import_shared7.randomId)());
1641
+ } = (0, import_react14.useContext)(CopilotContext);
1642
+ const idRef = (0, import_react14.useRef)((0, import_shared7.randomId)());
1546
1643
  const key = `${action.name}-${action.nodeName || "global"}`;
1547
1644
  if (dependencies === void 0) {
1548
1645
  if (coAgentStateRenders[idRef.current]) {
@@ -1554,7 +1651,7 @@ function useCoAgentStateRender(action, dependencies) {
1554
1651
  }
1555
1652
  }
1556
1653
  }
1557
- (0, import_react12.useEffect)(() => {
1654
+ (0, import_react14.useEffect)(() => {
1558
1655
  setCoAgentStateRender(idRef.current, action);
1559
1656
  if (chatComponentsCache.current !== null && action.render !== void 0) {
1560
1657
  chatComponentsCache.current.coAgentStateRenders[key] = action.render;
@@ -1574,11 +1671,11 @@ function useCoAgentStateRender(action, dependencies) {
1574
1671
  }
1575
1672
 
1576
1673
  // src/hooks/use-make-copilot-document-readable.ts
1577
- var import_react13 = require("react");
1674
+ var import_react15 = require("react");
1578
1675
  function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
1579
1676
  const { addDocumentContext, removeDocumentContext } = useCopilotContext();
1580
- const idRef = (0, import_react13.useRef)();
1581
- (0, import_react13.useEffect)(() => {
1677
+ const idRef = (0, import_react15.useRef)();
1678
+ (0, import_react15.useEffect)(() => {
1582
1679
  const id = addDocumentContext(document, categories);
1583
1680
  idRef.current = id;
1584
1681
  return () => {
@@ -1589,16 +1686,16 @@ function useMakeCopilotDocumentReadable(document, categories, dependencies = [])
1589
1686
  }
1590
1687
 
1591
1688
  // src/hooks/use-copilot-readable.ts
1592
- var import_react14 = require("react");
1689
+ var import_react16 = require("react");
1593
1690
  function convertToJSON(description, value) {
1594
1691
  return `${description}: ${typeof value === "string" ? value : JSON.stringify(value)}`;
1595
1692
  }
1596
1693
  function useCopilotReadable({ description, value, parentId, categories, convert }, dependencies) {
1597
1694
  const { addContext, removeContext } = useCopilotContext();
1598
- const idRef = (0, import_react14.useRef)();
1695
+ const idRef = (0, import_react16.useRef)();
1599
1696
  convert = convert || convertToJSON;
1600
1697
  const information = convert(description, value);
1601
- (0, import_react14.useEffect)(() => {
1698
+ (0, import_react16.useEffect)(() => {
1602
1699
  const id = addContext(information, parentId, categories);
1603
1700
  idRef.current = id;
1604
1701
  return () => {
@@ -1609,7 +1706,7 @@ function useCopilotReadable({ description, value, parentId, categories, convert
1609
1706
  }
1610
1707
 
1611
1708
  // src/hooks/use-coagent.ts
1612
- var import_react15 = require("react");
1709
+ var import_react17 = require("react");
1613
1710
  function useCoAgent(options) {
1614
1711
  const isExternalStateManagement = (options2) => {
1615
1712
  return "state" in options2 && "setState" in options2;
@@ -1649,28 +1746,29 @@ function useCoAgent(options) {
1649
1746
  };
1650
1747
  const coagentState = getCoagentState(coagentStates, name);
1651
1748
  const state = isExternalStateManagement(options) ? options.state : coagentState.state;
1652
- (0, import_react15.useEffect)(() => {
1749
+ (0, import_react17.useEffect)(() => {
1653
1750
  if (isExternalStateManagement(options)) {
1654
1751
  setState(options.state);
1655
1752
  } else if (coagentStates[name] === void 0) {
1656
1753
  setState(options.initialState === void 0 ? {} : options.initialState);
1657
1754
  }
1658
1755
  }, [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]);
1756
+ const runAgentCallback = useAsyncCallback(
1757
+ (hint) => __async(this, null, function* () {
1758
+ yield runAgent(name, context, appendMessage, runChatCompletion, hint);
1759
+ }),
1760
+ [name, context, appendMessage, runChatCompletion]
1761
+ );
1659
1762
  return {
1660
1763
  name,
1661
1764
  nodeName: coagentState.nodeName,
1662
- state,
1663
- setState,
1765
+ threadId: coagentState.threadId,
1664
1766
  running: coagentState.running,
1665
- start: () => {
1666
- startAgent(name, context);
1667
- },
1668
- stop: () => {
1669
- stopAgent(name, context);
1670
- },
1671
- run: (hint) => {
1672
- return runAgent(name, context, appendMessage, runChatCompletion, hint);
1673
- }
1767
+ state: coagentState.state,
1768
+ setState: isExternalStateManagement(options) ? options.setState : setState,
1769
+ start: () => startAgent(name, context),
1770
+ stop: () => stopAgent(name, context),
1771
+ run: runAgentCallback
1674
1772
  };
1675
1773
  }
1676
1774
  function startAgent(name, context) {
@@ -1726,7 +1824,6 @@ var CopilotTask = class {
1726
1824
  this.actions = config.actions || [];
1727
1825
  this.includeCopilotReadable = config.includeCopilotReadable !== false;
1728
1826
  this.includeCopilotActions = config.includeCopilotActions !== false;
1729
- this.forwardedParameters = config.forwardedParameters;
1730
1827
  }
1731
1828
  /**
1732
1829
  * Run the task.
@@ -1735,7 +1832,7 @@ var CopilotTask = class {
1735
1832
  */
1736
1833
  run(context, data) {
1737
1834
  return __async(this, null, function* () {
1738
- var _a, _b, _c;
1835
+ var _a, _b;
1739
1836
  const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
1740
1837
  for (const fn of this.actions) {
1741
1838
  actions[fn.name] = fn;
@@ -1772,15 +1869,15 @@ var CopilotTask = class {
1772
1869
  metadata: {
1773
1870
  requestType: import_runtime_client_gql6.CopilotRequestType.Task
1774
1871
  },
1775
- forwardedParameters: __spreadProps(__spreadValues({}, (_a = this.forwardedParameters) != null ? _a : {}), {
1872
+ forwardedParameters: {
1776
1873
  toolChoice: "required"
1777
- })
1874
+ }
1778
1875
  },
1779
1876
  properties: context.copilotApiConfig.properties
1780
1877
  }).toPromise();
1781
1878
  const functionCallHandler = context.getFunctionCallHandler(actions);
1782
1879
  const functionCalls = (0, import_runtime_client_gql6.convertGqlOutputToMessages)(
1783
- ((_c = (_b = response.data) == null ? void 0 : _b.generateCopilotResponse) == null ? void 0 : _c.messages) || []
1880
+ ((_b = (_a = response.data) == null ? void 0 : _a.generateCopilotResponse) == null ? void 0 : _b.messages) || []
1784
1881
  ).filter((m) => m.isActionExecutionMessage());
1785
1882
  for (const functionCall of functionCalls) {
1786
1883
  yield functionCallHandler({