@copilotkit/react-core 1.5.15-next.3 → 1.5.15-next.4

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 (131) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/{chunk-DZCTHC4G.mjs → chunk-5SGZKEPX.mjs} +3 -3
  3. package/dist/chunk-6PNZ77RB.mjs +66 -0
  4. package/dist/chunk-6PNZ77RB.mjs.map +1 -0
  5. package/dist/{chunk-7QGQVBD7.mjs → chunk-7HWSAEOY.mjs} +2 -2
  6. package/dist/{chunk-YJT6IYNV.mjs → chunk-AL3MOOKF.mjs} +2 -2
  7. package/dist/{chunk-67W2A4DM.mjs → chunk-DEPX7JPX.mjs} +10 -6
  8. package/dist/chunk-DEPX7JPX.mjs.map +1 -0
  9. package/dist/{chunk-KGCYVAIN.mjs → chunk-FMROB4TE.mjs} +49 -10
  10. package/dist/chunk-FMROB4TE.mjs.map +1 -0
  11. package/dist/{chunk-PMHLIIAI.mjs → chunk-GANI4ZZM.mjs} +3 -3
  12. package/dist/{chunk-VEQGQAGN.mjs → chunk-H2OR7FUU.mjs} +2 -2
  13. package/dist/chunk-IGLITGLC.mjs +1 -0
  14. package/dist/{chunk-V74U56PX.mjs → chunk-IHWTLSHY.mjs} +2 -2
  15. package/dist/{chunk-TJTOQRGB.mjs → chunk-IU7OLWWW.mjs} +26 -6
  16. package/dist/chunk-IU7OLWWW.mjs.map +1 -0
  17. package/dist/{chunk-GPWNMXSU.mjs → chunk-WU53OU3E.mjs} +2 -2
  18. package/dist/{chunk-S5MSFDGS.mjs → chunk-XOHLZIZK.mjs} +2 -2
  19. package/dist/chunk-ZAU4EMBM.mjs +48 -0
  20. package/dist/chunk-ZAU4EMBM.mjs.map +1 -0
  21. package/dist/{chunk-RKYHRYN3.mjs → chunk-ZM56S3LJ.mjs} +5 -2
  22. package/dist/chunk-ZM56S3LJ.mjs.map +1 -0
  23. package/dist/components/copilot-provider/copilot-messages.js +4 -1
  24. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  25. package/dist/components/copilot-provider/copilot-messages.mjs +2 -2
  26. package/dist/components/copilot-provider/copilotkit-props.d.ts +1 -0
  27. package/dist/components/copilot-provider/copilotkit.d.ts +1 -0
  28. package/dist/components/copilot-provider/copilotkit.js +25 -2
  29. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  30. package/dist/components/copilot-provider/copilotkit.mjs +3 -3
  31. package/dist/components/copilot-provider/index.d.ts +1 -0
  32. package/dist/components/copilot-provider/index.js +25 -2
  33. package/dist/components/copilot-provider/index.js.map +1 -1
  34. package/dist/components/copilot-provider/index.mjs +3 -3
  35. package/dist/components/index.d.ts +1 -0
  36. package/dist/components/index.js +25 -2
  37. package/dist/components/index.js.map +1 -1
  38. package/dist/components/index.mjs +3 -3
  39. package/dist/context/copilot-context.d.ts +5 -1
  40. package/dist/context/copilot-context.js +4 -1
  41. package/dist/context/copilot-context.js.map +1 -1
  42. package/dist/context/copilot-context.mjs +1 -1
  43. package/dist/context/index.d.ts +1 -0
  44. package/dist/context/index.js +4 -1
  45. package/dist/context/index.js.map +1 -1
  46. package/dist/context/index.mjs +1 -1
  47. package/dist/hooks/index.d.ts +3 -0
  48. package/dist/hooks/index.js +150 -13
  49. package/dist/hooks/index.js.map +1 -1
  50. package/dist/hooks/index.mjs +20 -12
  51. package/dist/hooks/use-chat.d.ts +4 -1
  52. package/dist/hooks/use-chat.js +45 -7
  53. package/dist/hooks/use-chat.js.map +1 -1
  54. package/dist/hooks/use-chat.mjs +1 -1
  55. package/dist/hooks/use-coagent-state-render.js +4 -1
  56. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  57. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  58. package/dist/hooks/use-coagent.d.ts +1 -0
  59. package/dist/hooks/use-coagent.js +58 -13
  60. package/dist/hooks/use-coagent.js.map +1 -1
  61. package/dist/hooks/use-coagent.mjs +6 -6
  62. package/dist/hooks/use-copilot-action.js +4 -1
  63. package/dist/hooks/use-copilot-action.js.map +1 -1
  64. package/dist/hooks/use-copilot-action.mjs +2 -2
  65. package/dist/hooks/use-copilot-authenticated-action.js +4 -1
  66. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  67. package/dist/hooks/use-copilot-authenticated-action.mjs +3 -3
  68. package/dist/hooks/use-copilot-chat.d.ts +2 -1
  69. package/dist/hooks/use-copilot-chat.js +58 -13
  70. package/dist/hooks/use-copilot-chat.js.map +1 -1
  71. package/dist/hooks/use-copilot-chat.mjs +5 -5
  72. package/dist/hooks/use-copilot-readable.js +4 -1
  73. package/dist/hooks/use-copilot-readable.js.map +1 -1
  74. package/dist/hooks/use-copilot-readable.mjs +2 -2
  75. package/dist/hooks/use-langgraph-interrupt-render.d.ts +5 -0
  76. package/dist/hooks/use-langgraph-interrupt-render.js +184 -0
  77. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -0
  78. package/dist/hooks/use-langgraph-interrupt-render.mjs +11 -0
  79. package/dist/hooks/use-langgraph-interrupt-render.mjs.map +1 -0
  80. package/dist/hooks/use-langgraph-interrupt.d.ts +7 -0
  81. package/dist/hooks/use-langgraph-interrupt.js +1050 -0
  82. package/dist/hooks/use-langgraph-interrupt.js.map +1 -0
  83. package/dist/hooks/use-langgraph-interrupt.mjs +25 -0
  84. package/dist/hooks/use-langgraph-interrupt.mjs.map +1 -0
  85. package/dist/hooks/use-make-copilot-document-readable.js +4 -1
  86. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  87. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  88. package/dist/index.d.ts +3 -0
  89. package/dist/index.js +178 -21
  90. package/dist/index.js.map +1 -1
  91. package/dist/index.mjs +21 -13
  92. package/dist/lib/copilot-task.d.ts +1 -0
  93. package/dist/lib/copilot-task.js.map +1 -1
  94. package/dist/lib/copilot-task.mjs +4 -4
  95. package/dist/lib/index.d.ts +1 -0
  96. package/dist/lib/index.js.map +1 -1
  97. package/dist/lib/index.mjs +4 -4
  98. package/dist/types/interrupt-action.d.ts +35 -0
  99. package/dist/types/interrupt-action.js +19 -0
  100. package/dist/types/interrupt-action.js.map +1 -0
  101. package/dist/types/interrupt-action.mjs +1 -0
  102. package/dist/types/interrupt-action.mjs.map +1 -0
  103. package/dist/utils/extract.d.ts +1 -0
  104. package/dist/utils/extract.js.map +1 -1
  105. package/dist/utils/extract.mjs +3 -3
  106. package/dist/utils/index.d.ts +1 -0
  107. package/dist/utils/index.js.map +1 -1
  108. package/dist/utils/index.mjs +3 -3
  109. package/package.json +3 -3
  110. package/src/components/copilot-provider/copilotkit.tsx +25 -0
  111. package/src/context/copilot-context.tsx +12 -3
  112. package/src/hooks/index.ts +2 -0
  113. package/src/hooks/use-chat.ts +52 -1
  114. package/src/hooks/use-copilot-chat.ts +4 -0
  115. package/src/hooks/use-langgraph-interrupt-render.ts +63 -0
  116. package/src/hooks/use-langgraph-interrupt.ts +62 -0
  117. package/src/types/interrupt-action.ts +35 -0
  118. package/dist/chunk-67W2A4DM.mjs.map +0 -1
  119. package/dist/chunk-KGCYVAIN.mjs.map +0 -1
  120. package/dist/chunk-NR2BTA6Z.mjs +0 -1
  121. package/dist/chunk-RKYHRYN3.mjs.map +0 -1
  122. package/dist/chunk-TJTOQRGB.mjs.map +0 -1
  123. /package/dist/{chunk-DZCTHC4G.mjs.map → chunk-5SGZKEPX.mjs.map} +0 -0
  124. /package/dist/{chunk-7QGQVBD7.mjs.map → chunk-7HWSAEOY.mjs.map} +0 -0
  125. /package/dist/{chunk-YJT6IYNV.mjs.map → chunk-AL3MOOKF.mjs.map} +0 -0
  126. /package/dist/{chunk-PMHLIIAI.mjs.map → chunk-GANI4ZZM.mjs.map} +0 -0
  127. /package/dist/{chunk-VEQGQAGN.mjs.map → chunk-H2OR7FUU.mjs.map} +0 -0
  128. /package/dist/{chunk-NR2BTA6Z.mjs.map → chunk-IGLITGLC.mjs.map} +0 -0
  129. /package/dist/{chunk-V74U56PX.mjs.map → chunk-IHWTLSHY.mjs.map} +0 -0
  130. /package/dist/{chunk-GPWNMXSU.mjs.map → chunk-WU53OU3E.mjs.map} +0 -0
  131. /package/dist/{chunk-S5MSFDGS.mjs.map → chunk-XOHLZIZK.mjs.map} +0 -0
@@ -0,0 +1,1050 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __objRest = (source, exclude) => {
26
+ var target = {};
27
+ for (var prop in source)
28
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
+ target[prop] = source[prop];
30
+ if (source != null && __getOwnPropSymbols)
31
+ for (var prop of __getOwnPropSymbols(source)) {
32
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
+ target[prop] = source[prop];
34
+ }
35
+ return target;
36
+ };
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, { get: all[name], enumerable: true });
40
+ };
41
+ var __copyProps = (to, from, except, desc) => {
42
+ if (from && typeof from === "object" || typeof from === "function") {
43
+ for (let key of __getOwnPropNames(from))
44
+ if (!__hasOwnProp.call(to, key) && key !== except)
45
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
+ }
47
+ return to;
48
+ };
49
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
+ // If the importer is in node compatibility mode or this is not an ESM
51
+ // file that has been converted to a CommonJS file using a Babel-
52
+ // compatible transform (i.e. "__esModule" has not been set), then set
53
+ // "default" to the CommonJS "module.exports" for node compatibility.
54
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
+ mod
56
+ ));
57
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
+ var __async = (__this, __arguments, generator) => {
59
+ return new Promise((resolve, reject) => {
60
+ var fulfilled = (value) => {
61
+ try {
62
+ step(generator.next(value));
63
+ } catch (e) {
64
+ reject(e);
65
+ }
66
+ };
67
+ var rejected = (value) => {
68
+ try {
69
+ step(generator.throw(value));
70
+ } catch (e) {
71
+ reject(e);
72
+ }
73
+ };
74
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
75
+ step((generator = generator.apply(__this, __arguments)).next());
76
+ });
77
+ };
78
+
79
+ // src/hooks/use-langgraph-interrupt.ts
80
+ var use_langgraph_interrupt_exports = {};
81
+ __export(use_langgraph_interrupt_exports, {
82
+ useLangGraphInterrupt: () => useLangGraphInterrupt
83
+ });
84
+ module.exports = __toCommonJS(use_langgraph_interrupt_exports);
85
+ var import_react9 = require("react");
86
+
87
+ // src/context/copilot-context.tsx
88
+ var import_react = __toESM(require("react"));
89
+ var emptyCopilotContext = {
90
+ actions: {},
91
+ setAction: () => {
92
+ },
93
+ removeAction: () => {
94
+ },
95
+ coAgentStateRenders: {},
96
+ setCoAgentStateRender: () => {
97
+ },
98
+ removeCoAgentStateRender: () => {
99
+ },
100
+ chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
101
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
102
+ addContext: () => "",
103
+ removeContext: () => {
104
+ },
105
+ getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
106
+ })),
107
+ isLoading: false,
108
+ setIsLoading: () => returnAndThrowInDebug(false),
109
+ chatInstructions: "",
110
+ setChatInstructions: () => returnAndThrowInDebug(""),
111
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
112
+ addDocumentContext: () => returnAndThrowInDebug(""),
113
+ removeDocumentContext: () => {
114
+ },
115
+ runtimeClient: {},
116
+ copilotApiConfig: new class {
117
+ get chatApiEndpoint() {
118
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
119
+ }
120
+ get headers() {
121
+ return {};
122
+ }
123
+ get body() {
124
+ return {};
125
+ }
126
+ }(),
127
+ chatSuggestionConfiguration: {},
128
+ addChatSuggestionConfiguration: () => {
129
+ },
130
+ removeChatSuggestionConfiguration: () => {
131
+ },
132
+ showDevConsole: "auto",
133
+ coagentStates: {},
134
+ setCoagentStates: () => {
135
+ },
136
+ coagentStatesRef: { current: {} },
137
+ setCoagentStatesWithRef: () => {
138
+ },
139
+ agentSession: null,
140
+ setAgentSession: () => {
141
+ },
142
+ forwardedParameters: {},
143
+ agentLock: null,
144
+ threadId: "",
145
+ setThreadId: () => {
146
+ },
147
+ runId: null,
148
+ setRunId: () => {
149
+ },
150
+ chatAbortControllerRef: { current: null },
151
+ availableAgents: [],
152
+ extensions: {},
153
+ setExtensions: () => {
154
+ },
155
+ langGraphInterruptAction: null,
156
+ setLangGraphInterruptAction: () => null,
157
+ removeLangGraphInterruptAction: () => null
158
+ };
159
+ var CopilotContext = import_react.default.createContext(emptyCopilotContext);
160
+ function useCopilotContext() {
161
+ const context = import_react.default.useContext(CopilotContext);
162
+ if (context === emptyCopilotContext) {
163
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
164
+ }
165
+ return context;
166
+ }
167
+ function returnAndThrowInDebug(_value) {
168
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
169
+ }
170
+
171
+ // src/hooks/use-copilot-chat.ts
172
+ var import_react8 = require("react");
173
+ var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
174
+
175
+ // src/hooks/use-chat.ts
176
+ var import_react5 = require("react");
177
+ var import_shared2 = require("@copilotkit/shared");
178
+ var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
179
+
180
+ // src/types/frontend-action.ts
181
+ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
182
+ var import_shared = require("@copilotkit/shared");
183
+ function processActionsForRuntimeRequest(actions) {
184
+ const filteredActions = actions.filter(
185
+ (action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*"
186
+ ).map((action) => {
187
+ let available = import_runtime_client_gql.ActionInputAvailability.Enabled;
188
+ if (action.disabled) {
189
+ available = import_runtime_client_gql.ActionInputAvailability.Disabled;
190
+ } else if (action.available === "disabled") {
191
+ available = import_runtime_client_gql.ActionInputAvailability.Disabled;
192
+ } else if (action.available === "remote") {
193
+ available = import_runtime_client_gql.ActionInputAvailability.Remote;
194
+ }
195
+ return {
196
+ name: action.name,
197
+ description: action.description || "",
198
+ jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
199
+ available
200
+ };
201
+ });
202
+ return filteredActions;
203
+ }
204
+
205
+ // src/hooks/use-copilot-runtime-client.ts
206
+ var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
207
+
208
+ // src/components/toast/toast-provider.tsx
209
+ var import_react3 = require("react");
210
+
211
+ // src/components/error-boundary/error-utils.tsx
212
+ var import_react2 = require("react");
213
+
214
+ // src/components/toast/exclamation-mark-icon.tsx
215
+ var import_jsx_runtime = require("react/jsx-runtime");
216
+ var ExclamationMarkIcon = ({
217
+ className,
218
+ style
219
+ }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
220
+ "svg",
221
+ {
222
+ xmlns: "http://www.w3.org/2000/svg",
223
+ width: "24",
224
+ height: "24",
225
+ viewBox: "0 0 24 24",
226
+ fill: "none",
227
+ stroke: "currentColor",
228
+ strokeWidth: "2",
229
+ strokeLinecap: "round",
230
+ strokeLinejoin: "round",
231
+ className: `lucide lucide-circle-alert ${className ? className : ""}`,
232
+ style,
233
+ children: [
234
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("circle", { cx: "12", cy: "12", r: "10" }),
235
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("line", { x1: "12", x2: "12", y1: "8", y2: "12" }),
236
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("line", { x1: "12", x2: "12.01", y1: "16", y2: "16" })
237
+ ]
238
+ }
239
+ );
240
+
241
+ // src/components/error-boundary/error-utils.tsx
242
+ var import_react_markdown = __toESM(require("react-markdown"));
243
+ var import_jsx_runtime2 = require("react/jsx-runtime");
244
+ function ErrorToast({ errors }) {
245
+ const errorsToRender = errors.map((error, idx) => {
246
+ var _a, _b, _c;
247
+ const originalError = "extensions" in error ? (_a = error.extensions) == null ? void 0 : _a.originalError : {};
248
+ const message = (_b = originalError == null ? void 0 : originalError.message) != null ? _b : error.message;
249
+ const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
250
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
251
+ "div",
252
+ {
253
+ style: {
254
+ marginTop: idx === 0 ? 0 : 10,
255
+ marginBottom: 14
256
+ },
257
+ children: [
258
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
259
+ code && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
260
+ "div",
261
+ {
262
+ style: {
263
+ fontWeight: "600",
264
+ marginBottom: 4
265
+ },
266
+ children: [
267
+ "Copilot Cloud Error:",
268
+ " ",
269
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
270
+ ]
271
+ }
272
+ ),
273
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_markdown.default, { children: message })
274
+ ]
275
+ },
276
+ idx
277
+ );
278
+ });
279
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
280
+ "div",
281
+ {
282
+ style: {
283
+ fontSize: "13px",
284
+ maxWidth: "600px"
285
+ },
286
+ children: [
287
+ errorsToRender,
288
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
289
+ ]
290
+ }
291
+ );
292
+ }
293
+ function useErrorToast() {
294
+ const { addToast } = useToast();
295
+ return (0, import_react2.useCallback)(
296
+ (error) => {
297
+ const errorId = error.map((err) => {
298
+ var _a, _b;
299
+ const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
300
+ const stack = err.stack || "";
301
+ return btoa(message + stack).slice(0, 32);
302
+ }).join("|");
303
+ addToast({
304
+ type: "error",
305
+ id: errorId,
306
+ // Toast libraries typically dedupe by id
307
+ message: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ErrorToast, { errors: error })
308
+ });
309
+ },
310
+ [addToast]
311
+ );
312
+ }
313
+ function useAsyncCallback(callback, deps) {
314
+ const addErrorToast = useErrorToast();
315
+ return (0, import_react2.useCallback)((...args) => __async(this, null, function* () {
316
+ try {
317
+ return yield callback(...args);
318
+ } catch (error) {
319
+ console.error("Error in async callback:", error);
320
+ addErrorToast([error]);
321
+ throw error;
322
+ }
323
+ }), deps);
324
+ }
325
+
326
+ // src/components/toast/toast-provider.tsx
327
+ var import_jsx_runtime3 = require("react/jsx-runtime");
328
+ var ToastContext = (0, import_react3.createContext)(void 0);
329
+ function useToast() {
330
+ const context = (0, import_react3.useContext)(ToastContext);
331
+ if (!context) {
332
+ throw new Error("useToast must be used within a ToastProvider");
333
+ }
334
+ return context;
335
+ }
336
+
337
+ // src/hooks/use-copilot-runtime-client.ts
338
+ var import_react4 = require("react");
339
+ var useCopilotRuntimeClient = (options) => {
340
+ const { addGraphQLErrorsToast } = useToast();
341
+ const addErrorToast = useErrorToast();
342
+ const runtimeClient = (0, import_react4.useMemo)(() => {
343
+ return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, options), {
344
+ handleGQLErrors: (error) => {
345
+ if (error.graphQLErrors.length) {
346
+ addGraphQLErrorsToast(error.graphQLErrors);
347
+ } else {
348
+ addErrorToast([error]);
349
+ }
350
+ }
351
+ }));
352
+ }, [options, addGraphQLErrorsToast]);
353
+ return runtimeClient;
354
+ };
355
+
356
+ // src/hooks/use-chat.ts
357
+ var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
358
+ function useChat(options) {
359
+ const {
360
+ messages,
361
+ setMessages,
362
+ makeSystemMessageCallback,
363
+ copilotConfig,
364
+ setIsLoading,
365
+ initialMessages,
366
+ isLoading,
367
+ actions,
368
+ onFunctionCall,
369
+ onCoAgentStateRender,
370
+ setCoagentStatesWithRef,
371
+ coagentStatesRef,
372
+ agentSession,
373
+ setAgentSession,
374
+ threadId,
375
+ setThreadId,
376
+ runId,
377
+ setRunId,
378
+ chatAbortControllerRef,
379
+ agentLock,
380
+ extensions,
381
+ setExtensions,
382
+ langGraphInterruptAction,
383
+ setLangGraphInterruptAction
384
+ } = options;
385
+ const runChatCompletionRef = (0, import_react5.useRef)();
386
+ const addErrorToast = useErrorToast();
387
+ const agentSessionRef = (0, import_react5.useRef)(agentSession);
388
+ agentSessionRef.current = agentSession;
389
+ const runIdRef = (0, import_react5.useRef)(runId);
390
+ runIdRef.current = runId;
391
+ const extensionsRef = (0, import_react5.useRef)(extensions);
392
+ extensionsRef.current = extensions;
393
+ const publicApiKey = copilotConfig.publicApiKey;
394
+ const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared2.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
395
+ const runtimeClient = useCopilotRuntimeClient({
396
+ url: copilotConfig.chatApiEndpoint,
397
+ publicApiKey: copilotConfig.publicApiKey,
398
+ headers,
399
+ credentials: copilotConfig.credentials
400
+ });
401
+ const runChatCompletion = useAsyncCallback(
402
+ (previousMessages) => __async(this, null, function* () {
403
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
404
+ setIsLoading(true);
405
+ let newMessages = [
406
+ new import_runtime_client_gql3.TextMessage({
407
+ content: "",
408
+ role: import_runtime_client_gql3.Role.Assistant
409
+ })
410
+ ];
411
+ chatAbortControllerRef.current = new AbortController();
412
+ setMessages([...previousMessages, ...newMessages]);
413
+ const systemMessage = makeSystemMessageCallback();
414
+ const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
415
+ const isAgentRun = agentSessionRef.current !== null;
416
+ const stream = runtimeClient.asStream(
417
+ runtimeClient.generateCopilotResponse({
418
+ data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
419
+ frontend: {
420
+ actions: processActionsForRuntimeRequest(actions),
421
+ url: window.location.href
422
+ },
423
+ threadId,
424
+ runId: runIdRef.current,
425
+ extensions: extensionsRef.current,
426
+ metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event]),
427
+ messages: (0, import_runtime_client_gql3.convertMessagesToGqlInput)((0, import_runtime_client_gql3.filterAgentStateMessages)(messagesWithContext))
428
+ }, copilotConfig.cloud ? {
429
+ cloud: __spreadValues({}, ((_c = (_b = (_a = copilotConfig.cloud.guardrails) == null ? void 0 : _a.input) == null ? void 0 : _b.restrictToTopic) == null ? void 0 : _c.enabled) ? {
430
+ guardrails: {
431
+ inputValidationRules: {
432
+ allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
433
+ denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
434
+ }
435
+ }
436
+ } : {})
437
+ } : {}), {
438
+ metadata: {
439
+ requestType: import_runtime_client_gql3.CopilotRequestType.Chat
440
+ }
441
+ }), agentSessionRef.current ? {
442
+ agentSession: agentSessionRef.current
443
+ } : {}), {
444
+ agentStates: Object.values(coagentStatesRef.current).map((state) => ({
445
+ agentName: state.name,
446
+ state: JSON.stringify(state.state)
447
+ })),
448
+ forwardedParameters: options.forwardedParameters || {}
449
+ }),
450
+ properties: copilotConfig.properties,
451
+ signal: (_d = chatAbortControllerRef.current) == null ? void 0 : _d.signal
452
+ })
453
+ );
454
+ const guardrailsEnabled = ((_g = (_f = (_e = copilotConfig.cloud) == null ? void 0 : _e.guardrails) == null ? void 0 : _f.input) == null ? void 0 : _g.restrictToTopic.enabled) || false;
455
+ const reader = stream.getReader();
456
+ let executedCoAgentStateRenders = [];
457
+ let followUp = void 0;
458
+ let messages2 = [];
459
+ let syncedMessages = [];
460
+ try {
461
+ while (true) {
462
+ let done, value;
463
+ try {
464
+ const readResult = yield reader.read();
465
+ done = readResult.done;
466
+ value = readResult.value;
467
+ } catch (readError) {
468
+ break;
469
+ }
470
+ if (done) {
471
+ if (chatAbortControllerRef.current.signal.aborted) {
472
+ return [];
473
+ }
474
+ break;
475
+ }
476
+ if (!(value == null ? void 0 : value.generateCopilotResponse)) {
477
+ continue;
478
+ }
479
+ runIdRef.current = value.generateCopilotResponse.runId || null;
480
+ extensionsRef.current = import_runtime_client_gql3.CopilotRuntimeClient.removeGraphQLTypename(
481
+ value.generateCopilotResponse.extensions || {}
482
+ );
483
+ setRunId(runIdRef.current);
484
+ setExtensions(extensionsRef.current);
485
+ messages2 = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
486
+ (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(value.generateCopilotResponse.messages)
487
+ );
488
+ ((_i = (_h = value.generateCopilotResponse) == null ? void 0 : _h.metaEvents) != null ? _i : []).forEach((ev) => {
489
+ if (ev.name === "LangGraphInterruptEvent") {
490
+ setLangGraphInterruptAction({
491
+ event: (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev)
492
+ });
493
+ }
494
+ });
495
+ if (messages2.length === 0) {
496
+ continue;
497
+ }
498
+ newMessages = [];
499
+ if (((_j = value.generateCopilotResponse.status) == null ? void 0 : _j.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
500
+ newMessages = [
501
+ new import_runtime_client_gql3.TextMessage({
502
+ role: import_runtime_client_gql3.MessageRole.Assistant,
503
+ content: ((_k = value.generateCopilotResponse.status.details) == null ? void 0 : _k.guardrailsReason) || ""
504
+ })
505
+ ];
506
+ setMessages([...previousMessages, ...newMessages]);
507
+ break;
508
+ } else {
509
+ newMessages = [...messages2];
510
+ for (const message of messages2) {
511
+ if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
512
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
513
+ break;
514
+ }
515
+ yield onCoAgentStateRender({
516
+ name: message.agentName,
517
+ nodeName: message.nodeName,
518
+ state: message.state
519
+ });
520
+ executedCoAgentStateRenders.push(message.id);
521
+ }
522
+ }
523
+ const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
524
+ if (lastAgentStateMessage) {
525
+ if (lastAgentStateMessage.state.messages && lastAgentStateMessage.state.messages.length > 0) {
526
+ syncedMessages = (0, import_runtime_client_gql3.loadMessagesFromJsonRepresentation)(
527
+ lastAgentStateMessage.state.messages
528
+ );
529
+ }
530
+ setCoagentStatesWithRef((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
531
+ [lastAgentStateMessage.agentName]: {
532
+ name: lastAgentStateMessage.agentName,
533
+ state: lastAgentStateMessage.state,
534
+ running: lastAgentStateMessage.running,
535
+ active: lastAgentStateMessage.active,
536
+ threadId: lastAgentStateMessage.threadId,
537
+ nodeName: lastAgentStateMessage.nodeName,
538
+ runId: lastAgentStateMessage.runId
539
+ }
540
+ }));
541
+ if (lastAgentStateMessage.running) {
542
+ setAgentSession({
543
+ threadId: lastAgentStateMessage.threadId,
544
+ agentName: lastAgentStateMessage.agentName,
545
+ nodeName: lastAgentStateMessage.nodeName
546
+ });
547
+ } else {
548
+ if (agentLock) {
549
+ setAgentSession({
550
+ threadId: (0, import_shared2.randomId)(),
551
+ agentName: agentLock,
552
+ nodeName: void 0
553
+ });
554
+ } else {
555
+ setAgentSession(null);
556
+ }
557
+ }
558
+ }
559
+ }
560
+ if (newMessages.length > 0) {
561
+ setMessages([...previousMessages, ...newMessages]);
562
+ }
563
+ }
564
+ const finalMessages = constructFinalMessages(syncedMessages, previousMessages, newMessages);
565
+ let didExecuteAction = false;
566
+ if (onFunctionCall) {
567
+ const lastMessages = [];
568
+ for (let i = finalMessages.length - 1; i >= 0; i--) {
569
+ const message = finalMessages[i];
570
+ if (message.isActionExecutionMessage() && message.status.code !== import_runtime_client_gql3.MessageStatusCode.Pending) {
571
+ lastMessages.unshift(message);
572
+ } else {
573
+ break;
574
+ }
575
+ }
576
+ for (const message of lastMessages) {
577
+ setMessages(finalMessages);
578
+ const action = actions.find((action2) => action2.name === message.name);
579
+ if (action) {
580
+ followUp = action.followUp;
581
+ let result;
582
+ let error = null;
583
+ try {
584
+ result = yield Promise.race([
585
+ onFunctionCall({
586
+ messages: previousMessages,
587
+ name: message.name,
588
+ args: message.arguments
589
+ }),
590
+ new Promise(
591
+ (resolve) => {
592
+ var _a2;
593
+ return (_a2 = chatAbortControllerRef.current) == null ? void 0 : _a2.signal.addEventListener(
594
+ "abort",
595
+ () => resolve("Operation was aborted by the user")
596
+ );
597
+ }
598
+ ),
599
+ // if the user stopped generation, we also abort consecutive actions
600
+ new Promise((resolve) => {
601
+ var _a2;
602
+ if ((_a2 = chatAbortControllerRef.current) == null ? void 0 : _a2.signal.aborted) {
603
+ resolve("Operation was aborted by the user");
604
+ }
605
+ })
606
+ ]);
607
+ } catch (e) {
608
+ error = e;
609
+ addErrorToast([error]);
610
+ result = `Failed to execute action ${message.name}. ${error.message}`;
611
+ console.error(`Failed to execute action ${message.name}: ${error}`);
612
+ }
613
+ didExecuteAction = true;
614
+ const messageIndex = finalMessages.findIndex((msg) => msg.id === message.id);
615
+ finalMessages.splice(
616
+ messageIndex + 1,
617
+ 0,
618
+ new import_runtime_client_gql3.ResultMessage({
619
+ id: "result-" + message.id,
620
+ result: import_runtime_client_gql3.ResultMessage.encodeResult(
621
+ error ? {
622
+ content: result,
623
+ error: JSON.parse(
624
+ JSON.stringify(error, Object.getOwnPropertyNames(error))
625
+ )
626
+ } : result
627
+ ),
628
+ actionExecutionId: message.id,
629
+ actionName: message.name
630
+ })
631
+ );
632
+ }
633
+ }
634
+ setMessages(finalMessages);
635
+ }
636
+ if (
637
+ // if followUp is not explicitly false
638
+ followUp !== false && // and we executed an action
639
+ (didExecuteAction || // the last message is a server side result
640
+ !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
641
+ !((_l = chatAbortControllerRef.current) == null ? void 0 : _l.signal.aborted)
642
+ ) {
643
+ yield new Promise((resolve) => setTimeout(resolve, 10));
644
+ return yield runChatCompletionRef.current(finalMessages);
645
+ } else if ((_m = chatAbortControllerRef.current) == null ? void 0 : _m.signal.aborted) {
646
+ const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {
647
+ if (message.isActionExecutionMessage()) {
648
+ return finalMessages.find(
649
+ (msg, resultIndex) => msg.isResultMessage() && msg.actionExecutionId === message.id && resultIndex === actionExecutionIndex + 1
650
+ );
651
+ }
652
+ return true;
653
+ });
654
+ const repairedMessageIds = repairedMessages.map((message) => message.id);
655
+ setMessages(repairedMessages);
656
+ if ((_n = agentSessionRef.current) == null ? void 0 : _n.nodeName) {
657
+ setAgentSession({
658
+ threadId: agentSessionRef.current.threadId,
659
+ agentName: agentSessionRef.current.agentName,
660
+ nodeName: "__end__"
661
+ });
662
+ }
663
+ return newMessages.filter((message) => repairedMessageIds.includes(message.id));
664
+ } else {
665
+ return newMessages.slice();
666
+ }
667
+ } finally {
668
+ setIsLoading(false);
669
+ }
670
+ }),
671
+ [
672
+ messages,
673
+ setMessages,
674
+ makeSystemMessageCallback,
675
+ copilotConfig,
676
+ setIsLoading,
677
+ initialMessages,
678
+ isLoading,
679
+ actions,
680
+ onFunctionCall,
681
+ onCoAgentStateRender,
682
+ setCoagentStatesWithRef,
683
+ coagentStatesRef,
684
+ agentSession,
685
+ setAgentSession
686
+ ]
687
+ );
688
+ runChatCompletionRef.current = runChatCompletion;
689
+ const runChatCompletionAndHandleFunctionCall = useAsyncCallback(
690
+ (messages2) => __async(this, null, function* () {
691
+ yield runChatCompletionRef.current(messages2);
692
+ }),
693
+ [messages]
694
+ );
695
+ const composeAndFlushMetaEventsInput = (0, import_react5.useCallback)(
696
+ (metaEvents) => {
697
+ return metaEvents.reduce((acc, event) => {
698
+ if (!event)
699
+ return acc;
700
+ switch (event.name) {
701
+ case import_runtime_client_gql4.MetaEventName.LangGraphInterruptEvent:
702
+ if (event.response) {
703
+ setLangGraphInterruptAction(null);
704
+ return [
705
+ ...acc,
706
+ {
707
+ type: event.type,
708
+ name: event.name,
709
+ value: event.value,
710
+ response: event.response
711
+ }
712
+ ];
713
+ }
714
+ return acc;
715
+ default:
716
+ return acc;
717
+ }
718
+ }, []);
719
+ },
720
+ [setLangGraphInterruptAction]
721
+ );
722
+ const append = useAsyncCallback(
723
+ (message, options2) => __async(this, null, function* () {
724
+ var _a;
725
+ if (isLoading) {
726
+ return;
727
+ }
728
+ const newMessages = [...messages, message];
729
+ setMessages(newMessages);
730
+ const followUp = (_a = options2 == null ? void 0 : options2.followUp) != null ? _a : true;
731
+ if (followUp) {
732
+ return runChatCompletionAndHandleFunctionCall(newMessages);
733
+ }
734
+ }),
735
+ [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
736
+ );
737
+ const reload = useAsyncCallback(() => __async(this, null, function* () {
738
+ if (isLoading || messages.length === 0) {
739
+ return;
740
+ }
741
+ let newMessages = [...messages];
742
+ const lastMessage = messages[messages.length - 1];
743
+ if (lastMessage.isTextMessage() && lastMessage.role === "assistant") {
744
+ newMessages = newMessages.slice(0, -1);
745
+ }
746
+ setMessages(newMessages);
747
+ return runChatCompletionAndHandleFunctionCall(newMessages);
748
+ }), [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);
749
+ const stop = () => {
750
+ var _a;
751
+ (_a = chatAbortControllerRef.current) == null ? void 0 : _a.abort("Stop was called");
752
+ };
753
+ return {
754
+ append,
755
+ reload,
756
+ stop,
757
+ runChatCompletion: () => runChatCompletionRef.current(messages)
758
+ };
759
+ }
760
+ function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
761
+ const finalMessages = syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];
762
+ if (syncedMessages.length > 0) {
763
+ const messagesWithAgentState = [...previousMessages, ...newMessages];
764
+ let previousMessageId = void 0;
765
+ for (const message of messagesWithAgentState) {
766
+ if (message.isAgentStateMessage()) {
767
+ const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);
768
+ if (index !== -1) {
769
+ finalMessages.splice(index + 1, 0, message);
770
+ }
771
+ }
772
+ previousMessageId = message.id;
773
+ }
774
+ }
775
+ return finalMessages;
776
+ }
777
+
778
+ // src/components/copilot-provider/copilotkit.tsx
779
+ var import_react7 = require("react");
780
+ var import_react_dom = require("react-dom");
781
+ var import_shared3 = require("@copilotkit/shared");
782
+
783
+ // src/context/copilot-messages-context.tsx
784
+ var import_react6 = __toESM(require("react"));
785
+ var emptyCopilotContext2 = {
786
+ messages: [],
787
+ setMessages: () => []
788
+ };
789
+ var CopilotMessagesContext = import_react6.default.createContext(emptyCopilotContext2);
790
+ function useCopilotMessagesContext() {
791
+ const context = import_react6.default.useContext(CopilotMessagesContext);
792
+ if (context === emptyCopilotContext2) {
793
+ throw new Error(
794
+ "A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`"
795
+ );
796
+ }
797
+ return context;
798
+ }
799
+
800
+ // src/components/copilot-provider/copilotkit.tsx
801
+ var import_jsx_runtime4 = require("react/jsx-runtime");
802
+ var defaultCopilotContextCategories = ["global"];
803
+
804
+ // src/hooks/use-copilot-chat.ts
805
+ function useCopilotChat(_a = {}) {
806
+ var _b = _a, {
807
+ makeSystemMessage
808
+ } = _b, options = __objRest(_b, [
809
+ "makeSystemMessage"
810
+ ]);
811
+ const {
812
+ getContextString,
813
+ getFunctionCallHandler,
814
+ copilotApiConfig,
815
+ isLoading,
816
+ setIsLoading,
817
+ chatInstructions,
818
+ actions,
819
+ coagentStatesRef,
820
+ setCoagentStatesWithRef,
821
+ coAgentStateRenders,
822
+ agentSession,
823
+ setAgentSession,
824
+ forwardedParameters,
825
+ agentLock,
826
+ threadId,
827
+ setThreadId,
828
+ runId,
829
+ setRunId,
830
+ chatAbortControllerRef,
831
+ extensions,
832
+ setExtensions,
833
+ langGraphInterruptAction,
834
+ setLangGraphInterruptAction
835
+ } = useCopilotContext();
836
+ const { messages, setMessages } = useCopilotMessagesContext();
837
+ const latestGetContextString = useUpdatedRef(getContextString);
838
+ const deleteMessage = (0, import_react8.useCallback)(
839
+ (messageId) => {
840
+ setMessages((prev) => prev.filter((message) => message.id !== messageId));
841
+ },
842
+ [setMessages]
843
+ );
844
+ const makeSystemMessageCallback = (0, import_react8.useCallback)(() => {
845
+ const systemMessageMaker = makeSystemMessage || defaultSystemMessage;
846
+ const contextString = latestGetContextString.current([], defaultCopilotContextCategories);
847
+ return new import_runtime_client_gql5.TextMessage({
848
+ content: systemMessageMaker(contextString, chatInstructions),
849
+ role: import_runtime_client_gql5.Role.System
850
+ });
851
+ }, [getContextString, makeSystemMessage, chatInstructions]);
852
+ const onCoAgentStateRender = useAsyncCallback(
853
+ (args) => __async(this, null, function* () {
854
+ var _a2;
855
+ const { name, nodeName, state } = args;
856
+ let action = Object.values(coAgentStateRenders).find(
857
+ (action2) => action2.name === name && action2.nodeName === nodeName
858
+ );
859
+ if (!action) {
860
+ action = Object.values(coAgentStateRenders).find(
861
+ (action2) => action2.name === name && !action2.nodeName
862
+ );
863
+ }
864
+ if (action) {
865
+ yield (_a2 = action.handler) == null ? void 0 : _a2.call(action, { state, nodeName });
866
+ }
867
+ }),
868
+ [coAgentStateRenders]
869
+ );
870
+ const { append, reload, stop, runChatCompletion } = useChat(__spreadProps(__spreadValues({}, options), {
871
+ actions: Object.values(actions),
872
+ copilotConfig: copilotApiConfig,
873
+ initialMessages: options.initialMessages || [],
874
+ onFunctionCall: getFunctionCallHandler(),
875
+ onCoAgentStateRender,
876
+ messages,
877
+ setMessages,
878
+ makeSystemMessageCallback,
879
+ isLoading,
880
+ setIsLoading,
881
+ coagentStatesRef,
882
+ setCoagentStatesWithRef,
883
+ agentSession,
884
+ setAgentSession,
885
+ forwardedParameters,
886
+ threadId,
887
+ setThreadId,
888
+ runId,
889
+ setRunId,
890
+ chatAbortControllerRef,
891
+ agentLock,
892
+ extensions,
893
+ setExtensions,
894
+ langGraphInterruptAction,
895
+ setLangGraphInterruptAction
896
+ }));
897
+ const latestAppend = useUpdatedRef(append);
898
+ const latestAppendFunc = useAsyncCallback(
899
+ (message, options2) => __async(this, null, function* () {
900
+ return yield latestAppend.current(message, options2);
901
+ }),
902
+ [latestAppend]
903
+ );
904
+ const latestReload = useUpdatedRef(reload);
905
+ const latestReloadFunc = useAsyncCallback(() => __async(this, null, function* () {
906
+ return yield latestReload.current();
907
+ }), [latestReload]);
908
+ const latestStop = useUpdatedRef(stop);
909
+ const latestStopFunc = (0, import_react8.useCallback)(() => {
910
+ return latestStop.current();
911
+ }, [latestStop]);
912
+ const latestDelete = useUpdatedRef(deleteMessage);
913
+ const latestDeleteFunc = (0, import_react8.useCallback)(
914
+ (messageId) => {
915
+ return latestDelete.current(messageId);
916
+ },
917
+ [latestDelete]
918
+ );
919
+ const latestSetMessages = useUpdatedRef(setMessages);
920
+ const latestSetMessagesFunc = (0, import_react8.useCallback)(
921
+ (messages2) => {
922
+ return latestSetMessages.current(messages2);
923
+ },
924
+ [latestSetMessages]
925
+ );
926
+ const latestRunChatCompletion = useUpdatedRef(runChatCompletion);
927
+ const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () {
928
+ return yield latestRunChatCompletion.current();
929
+ }), [latestRunChatCompletion]);
930
+ const reset = (0, import_react8.useCallback)(() => {
931
+ latestStopFunc();
932
+ setMessages([]);
933
+ setRunId(null);
934
+ setCoagentStatesWithRef({});
935
+ let initialAgentSession = null;
936
+ if (agentLock) {
937
+ initialAgentSession = {
938
+ agentName: agentLock
939
+ };
940
+ }
941
+ setAgentSession(initialAgentSession);
942
+ }, [
943
+ latestStopFunc,
944
+ setMessages,
945
+ setThreadId,
946
+ setCoagentStatesWithRef,
947
+ setAgentSession,
948
+ agentLock
949
+ ]);
950
+ const latestReset = useUpdatedRef(reset);
951
+ const latestResetFunc = (0, import_react8.useCallback)(() => {
952
+ return latestReset.current();
953
+ }, [latestReset]);
954
+ return {
955
+ visibleMessages: messages,
956
+ appendMessage: latestAppendFunc,
957
+ setMessages: latestSetMessagesFunc,
958
+ reloadMessages: latestReloadFunc,
959
+ stopGeneration: latestStopFunc,
960
+ reset: latestResetFunc,
961
+ deleteMessage: latestDeleteFunc,
962
+ runChatCompletion: latestRunChatCompletionFunc,
963
+ isLoading
964
+ };
965
+ }
966
+ function useUpdatedRef(value) {
967
+ const ref = (0, import_react8.useRef)(value);
968
+ (0, import_react8.useEffect)(() => {
969
+ ref.current = value;
970
+ }, [value]);
971
+ return ref;
972
+ }
973
+ function defaultSystemMessage(contextString, additionalInstructions) {
974
+ return `
975
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
976
+
977
+ Help the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.
978
+ Always be polite and respectful, and prefer brevity over verbosity.
979
+
980
+ The user has provided you with the following context:
981
+ \`\`\`
982
+ ${contextString}
983
+ \`\`\`
984
+
985
+ They have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.
986
+
987
+ Please assist them as best you can.
988
+
989
+ You can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.
990
+
991
+ If you would like to call a function, call it without saying anything else.
992
+ In case of a function error:
993
+ - If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.
994
+ - If the error's source is unclear or seems unrelated to your input, do not attempt further retries.
995
+ ` + (additionalInstructions ? `
996
+
997
+ ${additionalInstructions}` : "");
998
+ }
999
+
1000
+ // src/hooks/use-langgraph-interrupt.ts
1001
+ var import_shared4 = require("@copilotkit/shared");
1002
+ function useLangGraphInterrupt(action, dependencies) {
1003
+ var _a;
1004
+ const { setLangGraphInterruptAction, removeLangGraphInterruptAction, langGraphInterruptAction } = (0, import_react9.useContext)(CopilotContext);
1005
+ const { runChatCompletion } = useCopilotChat();
1006
+ const { addToast } = useToast();
1007
+ const actionId = (0, import_shared4.dataToUUID)(JSON.stringify(action), "lgAction");
1008
+ const hasAction = (0, import_react9.useMemo)(
1009
+ () => Boolean(langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id),
1010
+ [langGraphInterruptAction]
1011
+ );
1012
+ const isCurrentAction = (0, import_react9.useMemo)(
1013
+ () => (langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id) && (langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id) === actionId,
1014
+ [langGraphInterruptAction]
1015
+ );
1016
+ (0, import_react9.useEffect)(() => {
1017
+ var _a2;
1018
+ if (hasAction && isCurrentAction && ((_a2 = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event) == null ? void 0 : _a2.response)) {
1019
+ runChatCompletion();
1020
+ }
1021
+ }, [(_a = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event) == null ? void 0 : _a.response, runChatCompletion, hasAction, isCurrentAction]);
1022
+ (0, import_react9.useEffect)(() => {
1023
+ var _a2;
1024
+ if (!action)
1025
+ return;
1026
+ if (hasAction && !isCurrentAction && !((_a2 = action.conditions) == null ? void 0 : _a2.length)) {
1027
+ addToast({
1028
+ type: "warning",
1029
+ message: "An action is already registered for the interrupt event"
1030
+ });
1031
+ return;
1032
+ }
1033
+ if (hasAction && isCurrentAction) {
1034
+ return;
1035
+ }
1036
+ setLangGraphInterruptAction(__spreadProps(__spreadValues({}, action), { id: actionId }));
1037
+ }, [
1038
+ action,
1039
+ hasAction,
1040
+ isCurrentAction,
1041
+ setLangGraphInterruptAction,
1042
+ removeLangGraphInterruptAction,
1043
+ ...dependencies || []
1044
+ ]);
1045
+ }
1046
+ // Annotate the CommonJS export names for ESM import in node:
1047
+ 0 && (module.exports = {
1048
+ useLangGraphInterrupt
1049
+ });
1050
+ //# sourceMappingURL=use-langgraph-interrupt.js.map