@copilotkit/react-core 1.50.0-beta.0 → 1.50.0-beta.10
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.
- package/CHANGELOG.md +93 -0
- package/dist/{chunk-UJBV5GAG.mjs → chunk-3775VM7Y.mjs} +32 -65
- package/dist/chunk-3775VM7Y.mjs.map +1 -0
- package/dist/{chunk-3GURHDG7.mjs → chunk-4HRUQH6U.mjs} +3 -3
- package/dist/{chunk-7BYHZLPL.mjs → chunk-4RRMC7L2.mjs} +4 -4
- package/dist/chunk-4RRMC7L2.mjs.map +1 -0
- package/dist/{chunk-D3QSYDJR.mjs → chunk-7IBF6RBW.mjs} +2 -2
- package/dist/{chunk-GMI4KO4X.mjs → chunk-7SHWECGN.mjs} +2 -2
- package/dist/{chunk-OVYFRPSN.mjs → chunk-ABWT4DRT.mjs} +2 -2
- package/dist/{chunk-WVLHXIFP.mjs → chunk-AFNWX62Q.mjs} +2 -2
- package/dist/{chunk-WVLHXIFP.mjs.map → chunk-AFNWX62Q.mjs.map} +1 -1
- package/dist/{chunk-JRT5BJF3.mjs → chunk-B5ELMVT7.mjs} +2 -2
- package/dist/{chunk-TXI72QHK.mjs → chunk-EG56H77V.mjs} +2 -2
- package/dist/{chunk-DCHSCK62.mjs → chunk-FYMZKPOL.mjs} +36 -42
- package/dist/chunk-FYMZKPOL.mjs.map +1 -0
- package/dist/{chunk-FBD24VEH.mjs → chunk-HE22TZMF.mjs} +2 -2
- package/dist/{chunk-FBD24VEH.mjs.map → chunk-HE22TZMF.mjs.map} +1 -1
- package/dist/chunk-I76HKHPJ.mjs +32 -0
- package/dist/chunk-I76HKHPJ.mjs.map +1 -0
- package/dist/{chunk-LHKZJ2ND.mjs → chunk-PMWUKW3Z.mjs} +3 -3
- package/dist/{chunk-NROJOTQP.mjs → chunk-QNUAXSDP.mjs} +9 -6
- package/dist/chunk-QNUAXSDP.mjs.map +1 -0
- package/dist/{chunk-NG26QEGF.mjs → chunk-T2VBHAAP.mjs} +9 -3
- package/dist/chunk-T2VBHAAP.mjs.map +1 -0
- package/dist/{chunk-QU6NONOD.mjs → chunk-U2ZRVVKT.mjs} +2 -2
- package/dist/{chunk-R4MR43UQ.mjs → chunk-VV56AVPB.mjs} +33 -9
- package/dist/chunk-VV56AVPB.mjs.map +1 -0
- package/dist/{chunk-5X5DJRQQ.mjs → chunk-WF65O6HX.mjs} +2 -7
- package/dist/chunk-WF65O6HX.mjs.map +1 -0
- package/dist/chunk-XDFVCQD3.mjs +27 -0
- package/dist/chunk-XDFVCQD3.mjs.map +1 -0
- package/dist/{chunk-WMJVBMUX.mjs → chunk-YCG6SNAU.mjs} +2 -2
- package/dist/{chunk-3R423LZT.mjs → chunk-YJGPIN3R.mjs} +3 -3
- package/dist/{chunk-BR5YEYZJ.mjs → chunk-YTQHRJUA.mjs} +2 -2
- package/dist/chunk-Z6JV2LRY.mjs +37 -0
- package/dist/chunk-Z6JV2LRY.mjs.map +1 -0
- package/dist/{chunk-24SCZAB4.mjs → chunk-ZYTXB6HH.mjs} +22 -14
- package/dist/chunk-ZYTXB6HH.mjs.map +1 -0
- package/dist/components/CopilotListeners.js +13 -146
- package/dist/components/CopilotListeners.js.map +1 -1
- package/dist/components/CopilotListeners.mjs +1 -6
- package/dist/components/copilot-provider/copilot-messages.js +1 -1
- package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
- package/dist/components/copilot-provider/copilot-messages.mjs +2 -2
- package/dist/components/copilot-provider/copilotkit-props.d.ts +1 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +1 -1
- package/dist/components/copilot-provider/copilotkit.js +35 -40
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +9 -9
- package/dist/components/copilot-provider/index.d.ts +1 -1
- package/dist/components/copilot-provider/index.js +35 -40
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +9 -9
- package/dist/components/dev-console/console-trigger.js +1 -1
- package/dist/components/dev-console/console-trigger.js.map +1 -1
- package/dist/components/dev-console/console-trigger.mjs +3 -3
- package/dist/components/dev-console/developer-console-modal.js +1 -1
- package/dist/components/dev-console/developer-console-modal.js.map +1 -1
- package/dist/components/dev-console/developer-console-modal.mjs +2 -2
- package/dist/components/index.d.ts +1 -1
- package/dist/components/index.js +35 -40
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +9 -9
- package/dist/context/copilot-context.d.ts +1 -1
- package/dist/context/copilot-context.js +1 -1
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/index.d.ts +1 -1
- package/dist/context/index.js +1 -1
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/{copilot-context-1cd70a3f.d.ts → copilot-context-ec77e921.d.ts} +3 -3
- package/dist/hooks/index.d.ts +2 -2
- package/dist/hooks/index.js +254 -219
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +24 -23
- package/dist/hooks/use-agent-nodename.d.ts +3 -0
- package/dist/hooks/use-agent-nodename.js +56 -0
- package/dist/hooks/use-agent-nodename.js.map +1 -0
- package/dist/hooks/use-agent-nodename.mjs +8 -0
- package/dist/hooks/use-coagent-state-render-bridge.js +8 -5
- package/dist/hooks/use-coagent-state-render-bridge.js.map +1 -1
- package/dist/hooks/use-coagent-state-render-bridge.mjs +2 -2
- package/dist/hooks/use-coagent-state-render.js +1 -1
- package/dist/hooks/use-coagent-state-render.js.map +1 -1
- package/dist/hooks/use-coagent-state-render.mjs +2 -2
- package/dist/hooks/use-coagent.js +58 -21
- package/dist/hooks/use-coagent.js.map +1 -1
- package/dist/hooks/use-coagent.mjs +2 -1
- package/dist/hooks/use-copilot-action.js +5 -1
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -2
- package/dist/hooks/use-copilot-additional-instructions.js +1 -1
- package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
- package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
- package/dist/hooks/use-copilot-authenticated-action.js +6 -2
- package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
- package/dist/hooks/use-copilot-authenticated-action.mjs +4 -4
- package/dist/hooks/use-copilot-chat-headless_c.js +128 -140
- package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
- package/dist/hooks/use-copilot-chat-headless_c.mjs +6 -6
- package/dist/hooks/{use-configure-chat-suggestions.d.ts → use-copilot-chat-suggestions.d.ts} +2 -3
- package/dist/hooks/use-copilot-chat-suggestions.js +60 -0
- package/dist/hooks/use-copilot-chat-suggestions.js.map +1 -0
- package/dist/hooks/use-copilot-chat-suggestions.mjs +8 -0
- package/dist/hooks/use-copilot-chat-suggestions.mjs.map +1 -0
- package/dist/hooks/use-copilot-chat.js +126 -138
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +6 -6
- package/dist/hooks/use-copilot-chat_internal.d.ts +18 -1
- package/dist/hooks/use-copilot-chat_internal.js +126 -138
- package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
- package/dist/hooks/use-copilot-chat_internal.mjs +5 -5
- package/dist/hooks/use-copilot-readable.d.ts +1 -1
- package/dist/hooks/use-copilot-readable.js +29 -5
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +1 -1
- package/dist/hooks/use-default-tool.js +5 -1
- package/dist/hooks/use-default-tool.js.map +1 -1
- package/dist/hooks/use-default-tool.mjs +3 -3
- package/dist/hooks/use-frontend-tool.js +5 -1
- package/dist/hooks/use-frontend-tool.js.map +1 -1
- package/dist/hooks/use-frontend-tool.mjs +1 -1
- package/dist/hooks/use-langgraph-interrupt-render.js +77 -13
- package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt-render.mjs +3 -2
- package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
- package/dist/hooks/use-langgraph-interrupt.js +3 -3
- package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt.mjs +2 -2
- package/dist/hooks/use-make-copilot-document-readable.js +1 -1
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +273 -246
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +34 -33
- package/dist/lib/copilot-task.d.ts +1 -1
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +10 -10
- package/dist/lib/index.d.ts +1 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +10 -10
- package/dist/types/index.d.ts +1 -1
- package/dist/types/interrupt-action.d.ts +1 -1
- package/dist/types/interrupt-action.js.map +1 -1
- package/dist/utils/index.mjs +3 -3
- package/dist/v2/index.css +4 -0
- package/dist/v2/index.css.map +1 -0
- package/dist/v2/index.js.map +1 -1
- package/dist/v2/index.mjs +2 -0
- package/dist/v2/index.mjs.map +1 -1
- package/jest.config.js +12 -0
- package/package.json +27 -24
- package/src/components/CopilotListeners.tsx +1 -2
- package/src/components/copilot-provider/copilot-messages.tsx +0 -41
- package/src/components/copilot-provider/copilotkit.tsx +31 -31
- package/src/context/copilot-context.tsx +2 -2
- package/src/hooks/__tests__/use-coagent-config.test.ts +189 -129
- package/src/hooks/index.ts +2 -2
- package/src/hooks/use-agent-nodename.ts +30 -0
- package/src/hooks/use-coagent-state-render-bridge.tsx +22 -22
- package/src/hooks/use-coagent.ts +22 -13
- package/src/hooks/use-copilot-chat-suggestions.tsx +124 -0
- package/src/hooks/use-copilot-chat_internal.ts +78 -78
- package/src/hooks/use-copilot-readable.ts +30 -12
- package/src/hooks/use-frontend-tool.ts +10 -2
- package/src/hooks/use-langgraph-interrupt-render.ts +25 -7
- package/src/hooks/use-langgraph-interrupt.ts +2 -3
- package/src/types/interrupt-action.ts +2 -5
- package/src/v2/index.ts +2 -0
- package/tsup.config.ts +1 -1
- package/dist/chunk-24SCZAB4.mjs.map +0 -1
- package/dist/chunk-5X5DJRQQ.mjs.map +0 -1
- package/dist/chunk-7BYHZLPL.mjs.map +0 -1
- package/dist/chunk-CB7CRBDG.mjs +0 -48
- package/dist/chunk-CB7CRBDG.mjs.map +0 -1
- package/dist/chunk-DCHSCK62.mjs.map +0 -1
- package/dist/chunk-IUSKVYUI.mjs +0 -13
- package/dist/chunk-IUSKVYUI.mjs.map +0 -1
- package/dist/chunk-NG26QEGF.mjs.map +0 -1
- package/dist/chunk-NROJOTQP.mjs.map +0 -1
- package/dist/chunk-R4MR43UQ.mjs.map +0 -1
- package/dist/chunk-UJBV5GAG.mjs.map +0 -1
- package/dist/hooks/use-configure-chat-suggestions.js +0 -210
- package/dist/hooks/use-configure-chat-suggestions.js.map +0 -1
- package/dist/hooks/use-configure-chat-suggestions.mjs +0 -13
- package/src/hooks/use-configure-chat-suggestions.tsx +0 -85
- /package/dist/{chunk-3GURHDG7.mjs.map → chunk-4HRUQH6U.mjs.map} +0 -0
- /package/dist/{chunk-D3QSYDJR.mjs.map → chunk-7IBF6RBW.mjs.map} +0 -0
- /package/dist/{chunk-GMI4KO4X.mjs.map → chunk-7SHWECGN.mjs.map} +0 -0
- /package/dist/{chunk-OVYFRPSN.mjs.map → chunk-ABWT4DRT.mjs.map} +0 -0
- /package/dist/{chunk-JRT5BJF3.mjs.map → chunk-B5ELMVT7.mjs.map} +0 -0
- /package/dist/{chunk-TXI72QHK.mjs.map → chunk-EG56H77V.mjs.map} +0 -0
- /package/dist/{chunk-LHKZJ2ND.mjs.map → chunk-PMWUKW3Z.mjs.map} +0 -0
- /package/dist/{chunk-QU6NONOD.mjs.map → chunk-U2ZRVVKT.mjs.map} +0 -0
- /package/dist/{chunk-WMJVBMUX.mjs.map → chunk-YCG6SNAU.mjs.map} +0 -0
- /package/dist/{chunk-3R423LZT.mjs.map → chunk-YJGPIN3R.mjs.map} +0 -0
- /package/dist/{chunk-BR5YEYZJ.mjs.map → chunk-YTQHRJUA.mjs.map} +0 -0
- /package/dist/hooks/{use-configure-chat-suggestions.mjs.map → use-agent-nodename.mjs.map} +0 -0
- /package/src/v2/{styles.css → index.css} +0 -0
|
@@ -4,29 +4,29 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
CopilotMessages,
|
|
6
6
|
MessagesTapProvider
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-HE22TZMF.mjs";
|
|
8
8
|
import {
|
|
9
9
|
ConsoleTrigger
|
|
10
|
-
} from "./chunk-
|
|
11
|
-
import {
|
|
12
|
-
shouldShowDevConsole
|
|
13
|
-
} from "./chunk-ICIK2BSB.mjs";
|
|
10
|
+
} from "./chunk-PMWUKW3Z.mjs";
|
|
14
11
|
import {
|
|
15
12
|
use_tree_default
|
|
16
13
|
} from "./chunk-RKTVJRK7.mjs";
|
|
14
|
+
import {
|
|
15
|
+
shouldShowDevConsole
|
|
16
|
+
} from "./chunk-ICIK2BSB.mjs";
|
|
17
17
|
import {
|
|
18
18
|
use_flat_category_store_default
|
|
19
19
|
} from "./chunk-YYN33GSG.mjs";
|
|
20
20
|
import {
|
|
21
21
|
CoAgentStateRenderBridge
|
|
22
|
-
} from "./chunk-
|
|
23
|
-
import {
|
|
24
|
-
CopilotListeners
|
|
25
|
-
} from "./chunk-5X5DJRQQ.mjs";
|
|
22
|
+
} from "./chunk-QNUAXSDP.mjs";
|
|
26
23
|
import {
|
|
27
24
|
ThreadsProvider,
|
|
28
25
|
useThreads
|
|
29
26
|
} from "./chunk-F555TVE4.mjs";
|
|
27
|
+
import {
|
|
28
|
+
CopilotListeners
|
|
29
|
+
} from "./chunk-WF65O6HX.mjs";
|
|
30
30
|
import {
|
|
31
31
|
ToastProvider
|
|
32
32
|
} from "./chunk-EFL5OBKN.mjs";
|
|
@@ -39,7 +39,7 @@ import {
|
|
|
39
39
|
} from "./chunk-FDOMAPJY.mjs";
|
|
40
40
|
import {
|
|
41
41
|
CopilotContext
|
|
42
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-AFNWX62Q.mjs";
|
|
43
43
|
import {
|
|
44
44
|
__async,
|
|
45
45
|
__objRest,
|
|
@@ -65,15 +65,7 @@ function CopilotKit(_a) {
|
|
|
65
65
|
const enabled = shouldShowDevConsole(props.showDevConsole);
|
|
66
66
|
const publicApiKey = props.publicApiKey || props.publicLicenseKey;
|
|
67
67
|
const renderArr = useMemo(() => [{ render: CoAgentStateRenderBridge }], []);
|
|
68
|
-
return /* @__PURE__ */ jsx(ToastProvider, { enabled, children: /* @__PURE__ */ jsx(CopilotErrorBoundary, { publicApiKey, showUsageBanner: enabled, children: /* @__PURE__ */ jsx(ThreadsProvider, { threadId: props.threadId, children: /* @__PURE__ */ jsx(
|
|
69
|
-
CopilotKitProvider,
|
|
70
|
-
{
|
|
71
|
-
runtimeUrl: props.runtimeUrl,
|
|
72
|
-
renderCustomMessages: renderArr,
|
|
73
|
-
useSingleEndpoint: true,
|
|
74
|
-
children: /* @__PURE__ */ jsx(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children }))
|
|
75
|
-
}
|
|
76
|
-
) }) }) });
|
|
68
|
+
return /* @__PURE__ */ jsx(ToastProvider, { enabled, children: /* @__PURE__ */ jsx(CopilotErrorBoundary, { publicApiKey, showUsageBanner: enabled, children: /* @__PURE__ */ jsx(ThreadsProvider, { threadId: props.threadId, children: /* @__PURE__ */ jsx(CopilotKitProvider, __spreadProps(__spreadValues({}, props), { renderCustomMessages: renderArr, useSingleEndpoint: true, children: /* @__PURE__ */ jsx(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children })) })) }) }) });
|
|
77
69
|
}
|
|
78
70
|
function CopilotKitInternal(cpkProps) {
|
|
79
71
|
var _b;
|
|
@@ -311,20 +303,17 @@ ${nonDocumentStrings}`;
|
|
|
311
303
|
const chatAbortControllerRef = useRef(null);
|
|
312
304
|
const showDevConsole = shouldShowDevConsole(props.showDevConsole);
|
|
313
305
|
const [interruptActions, _setInterruptActions] = useState({});
|
|
314
|
-
const setInterruptAction = useCallback(
|
|
315
|
-
(
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
[action.id]: __spreadValues(__spreadValues({}, (_a2 = prev[action.id]) != null ? _a2 : {}), action)
|
|
323
|
-
});
|
|
306
|
+
const setInterruptAction = useCallback((action) => {
|
|
307
|
+
_setInterruptActions((prev) => {
|
|
308
|
+
var _a2;
|
|
309
|
+
if (action == null || !action.id) {
|
|
310
|
+
return prev;
|
|
311
|
+
}
|
|
312
|
+
return __spreadProps(__spreadValues({}, prev), {
|
|
313
|
+
[action.id]: __spreadValues(__spreadValues({}, (_a2 = prev[action.id]) != null ? _a2 : {}), action)
|
|
324
314
|
});
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
);
|
|
315
|
+
});
|
|
316
|
+
}, []);
|
|
328
317
|
const removeInterruptAction = useCallback((actionId) => {
|
|
329
318
|
_setInterruptActions((prev) => {
|
|
330
319
|
const _a2 = prev, { [actionId]: _ } = _a2, rest = __objRest(_a2, [__restKey(actionId)]);
|
|
@@ -340,14 +329,19 @@ ${nonDocumentStrings}`;
|
|
|
340
329
|
});
|
|
341
330
|
});
|
|
342
331
|
}, []);
|
|
343
|
-
const
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
332
|
+
const resolveInterruptEvent = useCallback(
|
|
333
|
+
(threadId2, eventId, response) => {
|
|
334
|
+
setInterruptEventQueue((prev) => {
|
|
335
|
+
const threadQueue = prev[threadId2] || [];
|
|
336
|
+
return __spreadProps(__spreadValues({}, prev), {
|
|
337
|
+
[threadId2]: threadQueue.map(
|
|
338
|
+
(queuedEvent) => queuedEvent.eventId === eventId ? __spreadProps(__spreadValues({}, queuedEvent), { event: __spreadProps(__spreadValues({}, queuedEvent.event), { response }) }) : queuedEvent
|
|
339
|
+
)
|
|
340
|
+
});
|
|
348
341
|
});
|
|
349
|
-
}
|
|
350
|
-
|
|
342
|
+
},
|
|
343
|
+
[]
|
|
344
|
+
);
|
|
351
345
|
const memoizedChildren = useMemo(() => children, [children]);
|
|
352
346
|
const [bannerError, setBannerError] = useState(null);
|
|
353
347
|
const agentLock = useMemo(() => {
|
|
@@ -410,7 +404,7 @@ ${nonDocumentStrings}`;
|
|
|
410
404
|
return /* @__PURE__ */ jsx(
|
|
411
405
|
CopilotChatConfigurationProvider,
|
|
412
406
|
{
|
|
413
|
-
agentId: (_b =
|
|
407
|
+
agentId: (_b = props.agent) != null ? _b : "default",
|
|
414
408
|
threadId,
|
|
415
409
|
children: /* @__PURE__ */ jsxs(
|
|
416
410
|
CopilotContext.Provider,
|
|
@@ -465,7 +459,7 @@ ${nonDocumentStrings}`;
|
|
|
465
459
|
removeInterruptAction,
|
|
466
460
|
interruptEventQueue,
|
|
467
461
|
addInterruptEvent,
|
|
468
|
-
|
|
462
|
+
resolveInterruptEvent,
|
|
469
463
|
bannerError,
|
|
470
464
|
setBannerError,
|
|
471
465
|
onError: handleErrors,
|
|
@@ -546,4 +540,4 @@ export {
|
|
|
546
540
|
CopilotKitInternal,
|
|
547
541
|
defaultCopilotContextCategories
|
|
548
542
|
};
|
|
549
|
-
//# sourceMappingURL=chunk-
|
|
543
|
+
//# sourceMappingURL=chunk-FYMZKPOL.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, SetStateAction } from \"react\";\nimport { CopilotChatConfigurationProvider, CopilotKitProvider } from \"@copilotkitnext/react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n CopilotKitError,\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetterArgs,\n QueuedInterruptEvent,\n} from \"../../types/interrupt-action\";\nimport { ConsoleTrigger } from \"../dev-console/console-trigger\";\nimport { CoAgentStateRendersProvider } from \"../../context/coagent-state-renders-context\";\nimport { CoAgentStateRenderBridge } from \"../../hooks/use-coagent-state-render-bridge\";\nimport { ThreadsProvider, useThreads } from \"../../context/threads-context\";\nimport { CopilotListeners } from \"../CopilotListeners\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n const renderArr = useMemo(() => [{ render: CoAgentStateRenderBridge }], []);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={publicApiKey} showUsageBanner={enabled}>\n <ThreadsProvider threadId={props.threadId}>\n <CopilotKitProvider {...props} renderCustomMessages={renderArr} useSingleEndpoint={true}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotKitProvider>\n </ThreadsProvider>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n\n // State for registered actions from useCopilotAction\n const [registeredActionConfigs, setRegisteredActionConfigs] = useState<\n Map<string, { type: string; action: any; component: any }>\n >(new Map());\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n // Compute all the functions and properties that we need to pass\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const [internalErrorHandlers, _setInternalErrorHandler] = useState<\n Record<string, CopilotErrorHandler>\n >({});\n const setInternalErrorHandler = useCallback((handler: Record<string, CopilotErrorHandler>) => {\n _setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({\n ...prev,\n ...handler,\n }));\n }, []);\n const removeInternalErrorHandler = useCallback((key: string) => {\n _setInternalErrorHandler((prev) => {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n });\n }, []);\n\n // Keep latest values in refs\n const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);\n useEffect(() => {\n onErrorRef.current = props.onError;\n }, [props.onError]);\n\n const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});\n useEffect(() => {\n internalHandlersRef.current = internalErrorHandlers;\n }, [internalErrorHandlers]);\n\n const handleErrors = useCallback(\n async (error: CopilotErrorEvent) => {\n if (copilotApiConfig.publicApiKey && onErrorRef.current) {\n try {\n await onErrorRef.current(error);\n } catch (e) {\n console.error(\"Error in public onError handler:\", e);\n }\n }\n const handlers = Object.values(internalHandlersRef.current);\n await Promise.all(\n handlers.map((h) =>\n Promise.resolve(h(error)).catch((e) =>\n console.error(\"Error in internal error handler:\", e),\n ),\n ),\n );\n },\n [copilotApiConfig.publicApiKey],\n );\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const { threadId, setThreadId: setInternalThreadId } = useThreads();\n\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = shouldShowDevConsole(props.showDevConsole);\n\n const [interruptActions, _setInterruptActions] = useState<\n Record<string, LangGraphInterruptRender>\n >({});\n const setInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setInterruptActions((prev) => {\n if (action == null || !action.id) {\n // Cannot set action without id\n return prev;\n }\n return {\n ...prev,\n [action.id]: { ...(prev[action.id] ?? {}), ...action } as LangGraphInterruptRender,\n };\n });\n }, []);\n const removeInterruptAction = useCallback((actionId: string): void => {\n _setInterruptActions((prev) => {\n const { [actionId]: _, ...rest } = prev;\n return rest;\n });\n }, []);\n\n const [interruptEventQueue, setInterruptEventQueue] = useState<\n Record<string, QueuedInterruptEvent[]>\n >({});\n\n const addInterruptEvent = useCallback((queuedEvent: QueuedInterruptEvent) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[queuedEvent.threadId] || [];\n return {\n ...prev,\n [queuedEvent.threadId]: [...threadQueue, queuedEvent],\n };\n });\n }, []);\n\n const resolveInterruptEvent = useCallback(\n (threadId: string, eventId: string, response: string) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[threadId] || [];\n return {\n ...prev,\n [threadId]: threadQueue.map((queuedEvent) =>\n queuedEvent.eventId === eventId\n ? { ...queuedEvent, event: { ...queuedEvent.event, response } }\n : queuedEvent,\n ),\n };\n });\n },\n [],\n );\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n const handleSetRegisteredActions = useCallback((actionConfig: any): string => {\n const key = actionConfig.action.name || randomUUID();\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.set(key, actionConfig);\n return newMap;\n });\n return key;\n }, []);\n\n const handleRemoveRegisteredAction = useCallback((actionKey: string) => {\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.delete(actionKey);\n return newMap;\n });\n }, []);\n\n // Component to render all registered actions\n const RegisteredActionsRenderer = useMemo(() => {\n return () => (\n <>\n {Array.from(registeredActionConfigs.entries()).map(([key, config]) => {\n const Component = config.component;\n return <Component key={key} action={config.action} />;\n })}\n </>\n );\n }, [registeredActionConfigs]);\n\n return (\n <CopilotChatConfigurationProvider\n // labels={labels}\n // isModalDefaultOpen={isModalDefaultOpen}\n agentId={props.agent ?? \"default\"}\n threadId={threadId}\n >\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n setRegisteredActions: handleSetRegisteredActions,\n removeRegisteredAction: handleRemoveRegisteredAction,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n interruptActions,\n setInterruptAction,\n removeInterruptAction,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n bannerError,\n setBannerError,\n onError: handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n }}\n >\n <CopilotListeners />\n <CoAgentStateRendersProvider>\n <MessagesTapProvider>\n <CopilotMessages>\n {memoizedChildren}\n {showDevConsole && <ConsoleTrigger />}\n <RegisteredActionsRenderer />\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </CoAgentStateRendersProvider>\n </CopilotContext.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAS,aAAa,WAAW,SAAS,QAAQ,gBAAgC;AAClF,SAAS,kCAAkC,0BAA0B;AAUrE,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAmCK,SAkbN,UAlbM,KAigBA,YAjgBA;AAbL,SAAS,WAAW,IAAyC;AAAzC,eAAE,WA7D7B,IA6D2B,IAAe,kBAAf,IAAe,CAAb;AAC3B,QAAM,UAAU,qBAAqB,MAAM,cAAc;AAGzD,QAAM,eAAe,MAAM,gBAAgB,MAAM;AAEjD,QAAM,YAAY,QAAQ,MAAM,CAAC,EAAE,QAAQ,yBAAyB,CAAC,GAAG,CAAC,CAAC;AAE1E,SACE,oBAAC,iBAAc,SACb,8BAAC,wBAAqB,cAA4B,iBAAiB,SACjE,8BAAC,mBAAgB,UAAU,MAAM,UAC/B,8BAAC,qDAAuB,QAAvB,EAA8B,sBAAsB,WAAW,mBAAmB,MACjF,8BAAC,qDAAuB,QAAvB,EAA+B,WAAS,IAC3C,GACF,GACF,GACF;AAEJ;AAEO,SAAS,mBAAmB,UAA2B;AAlF9D;AAmFE,QAA+B,eAAvB,WAnFV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IAAIA;AAAA,IACvC;AAEA,UAAM,SAAS,sBAAsB,IAAI;AACzC,QAAI,SAAc;AAClB,QAAI,QAAQ;AACV,YAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,kBAAU,MAAY;AA5mB9B;AA6mBU,cAAI;AACF,qBAAS,OAAM,YAAO,YAAP,gCAAiB;AAChC,oBAAQ;AAAA,UACV,SAAS,OAAP;AACA,mBAAO,KAAK;AAAA,UACd;AAAA,QACF,EAAC;AAAA,MACH,CAAC;AACD,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAAA,IACxD;AACA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,kBAAkB,aAA6B;AACtD,SAAO,YACJ,QAAQ,OAAO,EAAE,EACjB,MAAM,GAAG,EACT,IAAI,CAAC,SAAS,KAAK,OAAO,CAAC,EAAE,YAAY,IAAI,KAAK,MAAM,CAAC,EAAE,YAAY,CAAC,EACxE,KAAK,GAAG;AACb;AAEA,SAAS,cAAc,OAAsC;AAC3D,QAAM,gBAAgB,OAAO,KAAK,KAAK,EAAE,OAAO,CAAC,QAAQ,IAAI,SAAS,IAAI,CAAC;AAG3E,QAAM,YAAY,MAAM,gBAAgB,MAAM;AAE9C,MAAI,CAAC,MAAM,cAAc,CAAC,WAAW;AACnC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,MAAI,cAAc,SAAS,KAAK,CAAC,WAAW;AAC1C,UAAM,IAAI;AAAA,MACR,sFAAsF,cACnF,IAAI,iBAAiB,EACrB,KAAK,IAAI;AAAA,IACd;AAAA,EACF;AACF;","names":["_a","_b","headers","threadId","action"]}
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-EFL5OBKN.mjs";
|
|
7
7
|
import {
|
|
8
8
|
useCopilotContext
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-AFNWX62Q.mjs";
|
|
10
10
|
import {
|
|
11
11
|
CopilotMessagesContext
|
|
12
12
|
} from "./chunk-DMLQZG75.mjs";
|
|
@@ -183,4 +183,4 @@ export {
|
|
|
183
183
|
MessagesTapProvider,
|
|
184
184
|
CopilotMessages
|
|
185
185
|
};
|
|
186
|
-
//# sourceMappingURL=chunk-
|
|
186
|
+
//# sourceMappingURL=chunk-HE22TZMF.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/components/copilot-provider/copilot-messages.tsx"],"sourcesContent":["/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport {\n ReactNode,\n useEffect,\n useState,\n useRef,\n useCallback,\n useMemo,\n createContext,\n useContext,\n} from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport {\n loadMessagesFromJsonRepresentation,\n Message,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useCopilotContext } from \"../../context/copilot-context\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { shouldShowDevConsole } from \"../../utils/dev-console\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\nimport { Suggestion } from \"@copilotkitnext/core\";\n\n// Helper to determine if error should show as banner based on visibility and legacy patterns\nfunction shouldShowAsBanner(gqlError: GraphQLError): boolean {\n const extensions = gqlError.extensions;\n if (!extensions) return false;\n\n // Priority 1: Check error code for discovery errors (these should always be banners)\n const code = extensions.code as CopilotKitErrorCode;\n if (\n code === CopilotKitErrorCode.AGENT_NOT_FOUND ||\n code === CopilotKitErrorCode.API_NOT_FOUND ||\n code === CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND ||\n code === CopilotKitErrorCode.CONFIGURATION_ERROR ||\n code === CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR ||\n code === CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR\n ) {\n return true;\n }\n\n // Priority 2: Check banner visibility\n if (extensions.visibility === ErrorVisibility.BANNER) {\n return true;\n }\n\n // Priority 3: Check for critical errors that should be banners regardless of formal classification\n const errorMessage = gqlError.message.toLowerCase();\n if (\n errorMessage.includes(\"api key\") ||\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"unauthorized\") ||\n errorMessage.includes(\"authentication\") ||\n errorMessage.includes(\"incorrect api key\")\n ) {\n return true;\n }\n\n // Priority 4: Legacy stack trace detection for discovery errors\n const originalError = extensions.originalError as any;\n if (originalError?.stack) {\n return (\n originalError.stack.includes(\"CopilotApiDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")\n );\n }\n\n return false;\n}\n\n/**\n * MessagesTap is used to mitigate performance issues when we only need\n * a snapshot of the messages, not a continuously updating stream of messages.\n */\n\nexport type MessagesTap = {\n getMessagesFromTap: () => Message[];\n updateTapMessages: (messages: Message[]) => void;\n};\n\nconst MessagesTapContext = createContext<MessagesTap | null>(null);\n\nexport function useMessagesTap() {\n const tap = useContext(MessagesTapContext);\n if (!tap) throw new Error(\"useMessagesTap must be used inside <MessagesTapProvider>\");\n return tap;\n}\n\nexport function MessagesTapProvider({ children }: { children: React.ReactNode }) {\n const messagesRef = useRef<Message[]>([]);\n\n const tapRef = useRef<MessagesTap>({\n getMessagesFromTap: () => messagesRef.current,\n updateTapMessages: (messages: Message[]) => {\n messagesRef.current = messages;\n },\n });\n\n return (\n <MessagesTapContext.Provider value={tapRef.current}>{children}</MessagesTapContext.Provider>\n );\n}\n\n/**\n * CopilotKit messages context.\n */\n\nexport function CopilotMessages({ children }: { children: ReactNode }) {\n const [messages, setMessages] = useState<Message[]>([]);\n const lastLoadedThreadId = useRef<string>(undefined!);\n const lastLoadedAgentName = useRef<string>(undefined!);\n const lastLoadedMessages = useRef<string>(undefined!);\n\n const { updateTapMessages } = useMessagesTap();\n\n const { threadId, agentSession, showDevConsole, onError, copilotApiConfig } = useCopilotContext();\n const { setBannerError } = useToast();\n\n // Helper function to trace UI errors (similar to useCopilotRuntimeClient)\n const traceUIError = useCallback(\n async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !copilotApiConfig.publicApiKey) return;\n\n try {\n const traceEvent = {\n type: \"error\" as const,\n timestamp: Date.now(),\n context: {\n source: \"ui\" as const,\n request: {\n operation: \"loadAgentState\",\n url: copilotApiConfig.chatApiEndpoint,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(traceEvent);\n } catch (traceError) {\n console.error(\"Error in CopilotMessages onError handler:\", traceError);\n }\n },\n [onError, copilotApiConfig.publicApiKey, copilotApiConfig.chatApiEndpoint],\n );\n\n const createStructuredError = (gqlError: GraphQLError): CopilotKitError | null => {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n\n // Priority: Check stack trace for discovery errors first\n if (originalError?.stack) {\n if (originalError.stack.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message: originalError.message });\n }\n if (originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });\n }\n if (originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n }\n\n // Fallback: Use the formal error code if available\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n return null;\n };\n\n const handleGraphQLErrors = useCallback(\n (error: any) => {\n if (error.graphQLErrors?.length) {\n const graphQLErrors = error.graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole);\n\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", gqlError.message);\n return;\n }\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All other errors (including DEV_ONLY) show as banners for consistency\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the structured error\n traceUIError(ckError, gqlError);\n } else {\n // Fallback: create a generic error for unstructured GraphQL errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n [setBannerError, showDevConsole, traceUIError],\n );\n\n // useEffect(() => {\n // if (!threadId || threadId === lastLoadedThreadId.current) return;\n // if (\n // threadId === lastLoadedThreadId.current &&\n // agentSession?.agentName === lastLoadedAgentName.current\n // ) {\n // return;\n // }\n //\n // const fetchMessages = async () => {\n // if (!agentSession?.agentName) return;\n //\n // const result = await runtimeClient.loadAgentState({\n // threadId,\n // agentName: agentSession?.agentName,\n // });\n //\n // // Check for GraphQL errors and manually trigger error handling\n // if (result.error) {\n // // Update refs to prevent infinite retries of the same failed request\n // lastLoadedThreadId.current = threadId;\n // lastLoadedAgentName.current = agentSession?.agentName;\n // handleGraphQLErrors(result.error);\n // return; // Don't try to process the data if there's an error\n // }\n //\n // const newMessages = result.data?.loadAgentState?.messages;\n // if (newMessages === lastLoadedMessages.current) return;\n //\n // if (result.data?.loadAgentState) {\n // lastLoadedMessages.current = newMessages;\n // lastLoadedThreadId.current = threadId;\n // lastLoadedAgentName.current = agentSession?.agentName;\n //\n // const messages = loadMessagesFromJsonRepresentation(JSON.parse(newMessages || \"[]\"));\n // setMessages(messages);\n // }\n // };\n // void fetchMessages();\n // }, [threadId, agentSession?.agentName]);\n\n useEffect(() => {\n updateTapMessages(messages);\n }, [messages, updateTapMessages]);\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [suggestions, setSuggestions] = useState<Suggestion[]>([]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n suggestions,\n setSuggestions,\n }}\n >\n {memoizedChildren}\n </CopilotMessagesContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAIA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAgFH;AAnBJ,IAAM,qBAAqB,cAAkC,IAAI;AAE1D,SAAS,iBAAiB;AAC/B,QAAM,MAAM,WAAW,kBAAkB;AACzC,MAAI,CAAC;AAAK,UAAM,IAAI,MAAM,0DAA0D;AACpF,SAAO;AACT;AAEO,SAAS,oBAAoB,EAAE,SAAS,GAAkC;AAC/E,QAAM,cAAc,OAAkB,CAAC,CAAC;AAExC,QAAM,SAAS,OAAoB;AAAA,IACjC,oBAAoB,MAAM,YAAY;AAAA,IACtC,mBAAmB,CAAC,aAAwB;AAC1C,kBAAY,UAAU;AAAA,IACxB;AAAA,EACF,CAAC;AAED,SACE,oBAAC,mBAAmB,UAAnB,EAA4B,OAAO,OAAO,SAAU,UAAS;AAElE;AAMO,SAAS,gBAAgB,EAAE,SAAS,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C,KAAK;AAAA,QACjE,OAAO;AAEL,gBAAM,gBAAgB,IAAI,gBAAgB;AAAA,YACxC,UAAS,+BAAO,YAAW,OAAO,KAAK;AAAA,YACvC,MAAM,oBAAoB;AAAA,UAC5B,CAAC;AACD,yBAAe,aAAa;AAE5B,uBAAa,eAAe,KAAK;AAAA,QACnC;AAAA,MACF;AAAA,IACF;AAAA,IACA,CAAC,gBAAgB,gBAAgB,YAAY;AAAA,EAC/C;AA2CA,YAAU,MAAM;AACd,sBAAkB,QAAQ;AAAA,EAC5B,GAAG,CAAC,UAAU,iBAAiB,CAAC;AAEhC,QAAM,mBAAmB,QAAQ,MAAM,UAAU,CAAC,QAAQ,CAAC;AAC3D,QAAM,CAAC,aAAa,cAAc,IAAI,SAAuB,CAAC,CAAC;AAE/D,SACE;AAAA,IAAC,uBAAuB;AAAA,IAAvB;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/components/copilot-provider/copilot-messages.tsx"],"sourcesContent":["/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport {\n ReactNode,\n useEffect,\n useState,\n useRef,\n useCallback,\n useMemo,\n createContext,\n useContext,\n} from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport {\n loadMessagesFromJsonRepresentation,\n Message,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useCopilotContext } from \"../../context/copilot-context\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { shouldShowDevConsole } from \"../../utils/dev-console\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n} from \"@copilotkit/shared\";\nimport { Suggestion } from \"@copilotkitnext/core\";\n\n// Helper to determine if error should show as banner based on visibility and legacy patterns\nfunction shouldShowAsBanner(gqlError: GraphQLError): boolean {\n const extensions = gqlError.extensions;\n if (!extensions) return false;\n\n // Priority 1: Check error code for discovery errors (these should always be banners)\n const code = extensions.code as CopilotKitErrorCode;\n if (\n code === CopilotKitErrorCode.AGENT_NOT_FOUND ||\n code === CopilotKitErrorCode.API_NOT_FOUND ||\n code === CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND ||\n code === CopilotKitErrorCode.CONFIGURATION_ERROR ||\n code === CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR ||\n code === CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR\n ) {\n return true;\n }\n\n // Priority 2: Check banner visibility\n if (extensions.visibility === ErrorVisibility.BANNER) {\n return true;\n }\n\n // Priority 3: Check for critical errors that should be banners regardless of formal classification\n const errorMessage = gqlError.message.toLowerCase();\n if (\n errorMessage.includes(\"api key\") ||\n errorMessage.includes(\"401\") ||\n errorMessage.includes(\"unauthorized\") ||\n errorMessage.includes(\"authentication\") ||\n errorMessage.includes(\"incorrect api key\")\n ) {\n return true;\n }\n\n // Priority 4: Legacy stack trace detection for discovery errors\n const originalError = extensions.originalError as any;\n if (originalError?.stack) {\n return (\n originalError.stack.includes(\"CopilotApiDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\") ||\n originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")\n );\n }\n\n return false;\n}\n\n/**\n * MessagesTap is used to mitigate performance issues when we only need\n * a snapshot of the messages, not a continuously updating stream of messages.\n */\n\nexport type MessagesTap = {\n getMessagesFromTap: () => Message[];\n updateTapMessages: (messages: Message[]) => void;\n};\n\nconst MessagesTapContext = createContext<MessagesTap | null>(null);\n\nexport function useMessagesTap() {\n const tap = useContext(MessagesTapContext);\n if (!tap) throw new Error(\"useMessagesTap must be used inside <MessagesTapProvider>\");\n return tap;\n}\n\nexport function MessagesTapProvider({ children }: { children: React.ReactNode }) {\n const messagesRef = useRef<Message[]>([]);\n\n const tapRef = useRef<MessagesTap>({\n getMessagesFromTap: () => messagesRef.current,\n updateTapMessages: (messages: Message[]) => {\n messagesRef.current = messages;\n },\n });\n\n return (\n <MessagesTapContext.Provider value={tapRef.current}>{children}</MessagesTapContext.Provider>\n );\n}\n\n/**\n * CopilotKit messages context.\n */\n\nexport function CopilotMessages({ children }: { children: ReactNode }) {\n const [messages, setMessages] = useState<Message[]>([]);\n const lastLoadedThreadId = useRef<string>(undefined!);\n const lastLoadedAgentName = useRef<string>(undefined!);\n const lastLoadedMessages = useRef<string>(undefined!);\n\n const { updateTapMessages } = useMessagesTap();\n\n const { threadId, agentSession, showDevConsole, onError, copilotApiConfig } = useCopilotContext();\n const { setBannerError } = useToast();\n\n // Helper function to trace UI errors (similar to useCopilotRuntimeClient)\n const traceUIError = useCallback(\n async (error: CopilotKitError, originalError?: any) => {\n // Just check if onError and publicApiKey are defined\n if (!onError || !copilotApiConfig.publicApiKey) return;\n\n try {\n const traceEvent = {\n type: \"error\" as const,\n timestamp: Date.now(),\n context: {\n source: \"ui\" as const,\n request: {\n operation: \"loadAgentState\",\n url: copilotApiConfig.chatApiEndpoint,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onError(traceEvent);\n } catch (traceError) {\n console.error(\"Error in CopilotMessages onError handler:\", traceError);\n }\n },\n [onError, copilotApiConfig.publicApiKey, copilotApiConfig.chatApiEndpoint],\n );\n\n const createStructuredError = (gqlError: GraphQLError): CopilotKitError | null => {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n\n // Priority: Check stack trace for discovery errors first\n if (originalError?.stack) {\n if (originalError.stack.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message: originalError.message });\n }\n if (originalError.stack.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });\n }\n if (originalError.stack.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n }\n\n // Fallback: Use the formal error code if available\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n return null;\n };\n\n const handleGraphQLErrors = useCallback(\n (error: any) => {\n if (error.graphQLErrors?.length) {\n const graphQLErrors = error.graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole);\n\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", gqlError.message);\n return;\n }\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n // All other errors (including DEV_ONLY) show as banners for consistency\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the structured error\n traceUIError(ckError, gqlError);\n } else {\n // Fallback: create a generic error for unstructured GraphQL errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n [setBannerError, showDevConsole, traceUIError],\n );\n\n useEffect(() => {\n updateTapMessages(messages);\n }, [messages, updateTapMessages]);\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [suggestions, setSuggestions] = useState<Suggestion[]>([]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n suggestions,\n setSuggestions,\n }}\n >\n {memoizedChildren}\n </CopilotMessagesContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAIA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAgFH;AAnBJ,IAAM,qBAAqB,cAAkC,IAAI;AAE1D,SAAS,iBAAiB;AAC/B,QAAM,MAAM,WAAW,kBAAkB;AACzC,MAAI,CAAC;AAAK,UAAM,IAAI,MAAM,0DAA0D;AACpF,SAAO;AACT;AAEO,SAAS,oBAAoB,EAAE,SAAS,GAAkC;AAC/E,QAAM,cAAc,OAAkB,CAAC,CAAC;AAExC,QAAM,SAAS,OAAoB;AAAA,IACjC,oBAAoB,MAAM,YAAY;AAAA,IACtC,mBAAmB,CAAC,aAAwB;AAC1C,kBAAY,UAAU;AAAA,IACxB;AAAA,EACF,CAAC;AAED,SACE,oBAAC,mBAAmB,UAAnB,EAA4B,OAAO,OAAO,SAAU,UAAS;AAElE;AAMO,SAAS,gBAAgB,EAAE,SAAS,GAA4B;AACrE,QAAM,CAAC,UAAU,WAAW,IAAI,SAAoB,CAAC,CAAC;AACtD,QAAM,qBAAqB,OAAe,MAAU;AACpD,QAAM,sBAAsB,OAAe,MAAU;AACrD,QAAM,qBAAqB,OAAe,MAAU;AAEpD,QAAM,EAAE,kBAAkB,IAAI,eAAe;AAE7C,QAAM,EAAE,UAAU,cAAc,gBAAgB,SAAS,iBAAiB,IAAI,kBAAkB;AAChG,QAAM,EAAE,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A,YAAU,MAAM;AACd,sBAAkB,QAAQ;AAAA,EAC5B,GAAG,CAAC,UAAU,iBAAiB,CAAC;AAEhC,QAAM,mBAAmB,QAAQ,MAAM,UAAU,CAAC,QAAQ,CAAC;AAC3D,QAAM,CAAC,aAAa,cAAc,IAAI,SAAuB,CAAC,CAAC;AAE/D,SACE;AAAA,IAAC,uBAAuB;AAAA,IAAvB;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;","names":[]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// src/hooks/use-agent-nodename.ts
|
|
2
|
+
import { useEffect, useRef } from "react";
|
|
3
|
+
import { useAgent } from "@copilotkitnext/react";
|
|
4
|
+
function useAgentNodeName(agentName) {
|
|
5
|
+
const { agent } = useAgent({ agentId: agentName });
|
|
6
|
+
const nodeNameRef = useRef("start");
|
|
7
|
+
useEffect(() => {
|
|
8
|
+
if (!agent)
|
|
9
|
+
return;
|
|
10
|
+
const subscriber = {
|
|
11
|
+
onStepStartedEvent: ({ event }) => {
|
|
12
|
+
nodeNameRef.current = event.stepName;
|
|
13
|
+
},
|
|
14
|
+
onRunStartedEvent: () => {
|
|
15
|
+
nodeNameRef.current = "start";
|
|
16
|
+
},
|
|
17
|
+
onRunFinishedEvent: () => {
|
|
18
|
+
nodeNameRef.current = "end";
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const subscription = agent.subscribe(subscriber);
|
|
22
|
+
return () => {
|
|
23
|
+
subscription.unsubscribe();
|
|
24
|
+
};
|
|
25
|
+
}, [agent]);
|
|
26
|
+
return nodeNameRef.current;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export {
|
|
30
|
+
useAgentNodeName
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=chunk-I76HKHPJ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-agent-nodename.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgent } from \"@copilotkitnext/react\";\n\nexport function useAgentNodeName(agentName?: string) {\n const { agent } = useAgent({ agentId: agentName });\n const nodeNameRef = useRef<string>(\"start\");\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStepStartedEvent: ({ event }) => {\n nodeNameRef.current = event.stepName;\n },\n onRunStartedEvent: () => {\n nodeNameRef.current = \"start\";\n },\n onRunFinishedEvent: () => {\n nodeNameRef.current = \"end\";\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent]);\n\n return nodeNameRef.current;\n}\n"],"mappings":";AAAA,SAAS,WAAW,cAAc;AAElC,SAAS,gBAAgB;AAElB,SAAS,iBAAiB,WAAoB;AACnD,QAAM,EAAE,MAAM,IAAI,SAAS,EAAE,SAAS,UAAU,CAAC;AACjD,QAAM,cAAc,OAAe,OAAO;AAE1C,YAAU,MAAM;AACd,QAAI,CAAC;AAAO;AACZ,UAAM,aAA8B;AAAA,MAClC,oBAAoB,CAAC,EAAE,MAAM,MAAM;AACjC,oBAAY,UAAU,MAAM;AAAA,MAC9B;AAAA,MACA,mBAAmB,MAAM;AACvB,oBAAY,UAAU;AAAA,MACxB;AAAA,MACA,oBAAoB,MAAM;AACxB,oBAAY,UAAU;AAAA,MACxB;AAAA,IACF;AAEA,UAAM,eAAe,MAAM,UAAU,UAAU;AAC/C,WAAO,MAAM;AACX,mBAAa,YAAY;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO,YAAY;AACrB;","names":[]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
DeveloperConsoleModal
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-YCG6SNAU.mjs";
|
|
4
4
|
import {
|
|
5
5
|
CopilotKitIcon
|
|
6
6
|
} from "./chunk-PIF5KJYI.mjs";
|
|
7
7
|
import {
|
|
8
8
|
useCopilotContext
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-AFNWX62Q.mjs";
|
|
10
10
|
|
|
11
11
|
// src/components/dev-console/console-trigger.tsx
|
|
12
12
|
import { useState, useEffect, useRef } from "react";
|
|
@@ -228,4 +228,4 @@ function ConsoleTrigger({ position = "bottom-right" }) {
|
|
|
228
228
|
export {
|
|
229
229
|
ConsoleTrigger
|
|
230
230
|
};
|
|
231
|
-
//# sourceMappingURL=chunk-
|
|
231
|
+
//# sourceMappingURL=chunk-PMWUKW3Z.mjs.map
|
|
@@ -10,6 +10,8 @@ import { useAgent } from "@copilotkitnext/react";
|
|
|
10
10
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
11
11
|
import { dataToUUID, parseJson } from "@copilotkit/shared";
|
|
12
12
|
function getStateWithoutConstantKeys(state) {
|
|
13
|
+
if (!state)
|
|
14
|
+
return {};
|
|
13
15
|
const _a = state, { messages, tools, copilotkit } = _a, stateWithoutConstantKeys = __objRest(_a, ["messages", "tools", "copilotkit"]);
|
|
14
16
|
return stateWithoutConstantKeys;
|
|
15
17
|
}
|
|
@@ -56,9 +58,6 @@ function useCoagentStateRenderBridge(agentId, props) {
|
|
|
56
58
|
unsubscribe();
|
|
57
59
|
};
|
|
58
60
|
}, [agentId, nodeName]);
|
|
59
|
-
if (messageIndexInRun !== 0) {
|
|
60
|
-
return null;
|
|
61
|
-
}
|
|
62
61
|
const getStateRender = useCallback(
|
|
63
62
|
(messageId) => {
|
|
64
63
|
return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {
|
|
@@ -86,7 +85,7 @@ function useCoagentStateRenderBridge(agentId, props) {
|
|
|
86
85
|
return canRender;
|
|
87
86
|
}
|
|
88
87
|
const renderClaimedByOtherMessage = Object.values(claimsRef.current).find(
|
|
89
|
-
(c) => c.stateRenderId === stateRenderId && dataToUUID(
|
|
88
|
+
(c) => c.stateRenderId === stateRenderId && dataToUUID(getStateWithoutConstantKeys(c.stateSnapshot)) === dataToUUID(getStateWithoutConstantKeys(renderSnapshot))
|
|
90
89
|
);
|
|
91
90
|
if (renderClaimedByOtherMessage) {
|
|
92
91
|
if (renderSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, renderSnapshot)) {
|
|
@@ -103,6 +102,9 @@ function useCoagentStateRenderBridge(agentId, props) {
|
|
|
103
102
|
};
|
|
104
103
|
return useMemo(() => {
|
|
105
104
|
var _a2, _b, _c;
|
|
105
|
+
if (messageIndexInRun !== 0) {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
106
108
|
const [stateRenderId, stateRender] = (_a2 = getStateRender(message.id)) != null ? _a2 : [];
|
|
107
109
|
if (!stateRender || !stateRenderId) {
|
|
108
110
|
return null;
|
|
@@ -149,7 +151,8 @@ function useCoagentStateRenderBridge(agentId, props) {
|
|
|
149
151
|
agent == null ? void 0 : agent.isRunning,
|
|
150
152
|
nodeName,
|
|
151
153
|
effectiveRunId,
|
|
152
|
-
message.id
|
|
154
|
+
message.id,
|
|
155
|
+
messageIndexInRun
|
|
153
156
|
]);
|
|
154
157
|
}
|
|
155
158
|
function CoAgentStateRenderBridge(props) {
|
|
@@ -160,4 +163,4 @@ export {
|
|
|
160
163
|
useCoagentStateRenderBridge,
|
|
161
164
|
CoAgentStateRenderBridge
|
|
162
165
|
};
|
|
163
|
-
//# sourceMappingURL=chunk-
|
|
166
|
+
//# sourceMappingURL=chunk-QNUAXSDP.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-coagent-state-render-bridge.tsx"],"sourcesContent":["import { ReactCustomMessageRendererPosition, useAgent } from \"@copilotkitnext/react\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useCoAgentStateRenders } from \"../context\";\nimport { dataToUUID, parseJson } from \"@copilotkit/shared\";\n\nfunction getStateWithoutConstantKeys(state: any) {\n if (!state) return {};\n const { messages, tools, copilotkit, ...stateWithoutConstantKeys } = state;\n return stateWithoutConstantKeys;\n}\n\n// Function that compares states, without the constant keys\nfunction areStatesEquals(a: any, b: any) {\n if ((a && !b) || (!a && b)) return false;\n const { messages, tools, copilotkit, ...aWithoutConstantKeys } = a;\n const {\n messages: bMessages,\n tools: bTools,\n copilotkit: bCopilotkit,\n ...bWithoutConstantKeys\n } = b;\n\n return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);\n}\n\n/**\n * Bridge hook that connects agent state renders to chat messages.\n *\n * ## Purpose\n * This hook finds matching state render configurations (registered via useCoAgentStateRender)\n * and returns UI to render in chat.\n * It ensures each state render appears bound to a specific message, preventing duplicates while\n * allowing re-binding when the underlying state changes significantly.\n *\n * ## Message-ID-Based Claiming System\n *\n * ### The Problem\n * Multiple bridge component instances render simultaneously (one per message). Without coordination,\n * they would all try to render the same state render, causing duplicates.\n *\n * ### The Solution: Message-ID Claims with State Comparison\n * Each state render is \"claimed\" by exactly one **message ID** (not runId):\n *\n * **Claim Structure**: `claimsRef.current[messageId] = { stateRenderId, runId, stateSnapshot, locked }`\n *\n * **Primary binding is by messageId because**:\n * - runId is not always available immediately (starts as \"pending\")\n * - messageId is the stable identifier throughout the message lifecycle\n * - Claims persist across component remounts via context ref\n *\n * ### Claiming Logic Flow\n *\n * 1. **Message already has a claim**:\n * - Check if the claim matches the current stateRenderId\n * - If yes → render (this message owns this render)\n * - Update runId if it was \"pending\" and now available\n *\n * 2. **State render claimed by another message**:\n * - Compare state snapshots (ignoring constant keys: messages, tools, copilotkit)\n * - If states are identical → block rendering (duplicate)\n * - **If states are different → allow claiming** (new data, new message)\n * - This handles cases where the same render type shows different states in different messages\n *\n * 3. **Unclaimed state render**:\n * - Only allow claiming if runId is \"pending\" (initial render)\n * - If runId is real but no claim exists → block (edge case protection)\n * - Create new claim: `claimsRef.current[messageId] = { stateRenderId, runId }`\n *\n * ### State Snapshot Locking\n *\n * Once a state snapshot is captured and locked for a message:\n * - The UI always renders with the locked snapshot (not live agent.state)\n * - Prevents UI from appearing \"wiped\" during state transitions\n * - Locked when: stateSnapshot prop is available (from message persistence)\n * - Unlocked state: can still update from live agent.state\n *\n * ### Synchronous Claiming (Ref-based)\n *\n * Claims are stored in a context-level ref (not React state):\n * - Multiple bridges render in the same tick\n * - State updates are async - would allow duplicates before update completes\n * - Ref provides immediate, synchronous claim checking\n * - Survives component remounts (stored in context, not component)\n *\n * ## Flow Example\n *\n * ```\n * Time 1: Message A renders, runId=undefined, state={progress: 50%}\n * → effectiveRunId = \"pending\"\n * → Claims: claimsRef[\"msgA\"] = { stateRenderId: \"tasks\", runId: \"pending\", stateSnapshot: {progress: 50%} }\n * → Renders UI with 50% progress\n *\n * Time 2: Message B renders, runId=undefined, same state\n * → Checks: \"tasks\" already claimed by msgA with same state\n * → Returns null (blocked - duplicate)\n *\n * Time 3: Real runId appears (e.g., \"run-123\")\n * → Updates claim: claimsRef[\"msgA\"].runId = \"run-123\"\n * → Message A continues rendering\n *\n * Time 4: Agent processes more, state={progress: 100%}\n * → Message A: locked to 50% (stateSnapshot locked)\n * → Message C renders with state={progress: 100%}\n * → Checks: \"tasks\" claimed by msgA but state is DIFFERENT (50% vs 100%)\n * → Allows new claim: claimsRef[\"msgC\"] = { stateRenderId: \"tasks\", runId: \"run-123\", stateSnapshot: {progress: 100%} }\n * → Both messages render independently with their own snapshots\n * ```\n */\nexport interface CoAgentStateRenderBridgeProps {\n message: any;\n position: ReactCustomMessageRendererPosition;\n runId: string;\n messageIndex: number;\n messageIndexInRun: number;\n numberOfMessagesInRun: number;\n agentId: string;\n stateSnapshot: any;\n}\n\nexport function useCoagentStateRenderBridge(agentId: string, props: CoAgentStateRenderBridgeProps) {\n const { stateSnapshot, messageIndexInRun, message } = props;\n const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();\n const { agent } = useAgent({ agentId });\n const [nodeName, setNodeName] = useState<string | undefined>(undefined);\n\n const runId = props.runId ?? message.runId;\n const effectiveRunId = runId || \"pending\";\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStepStartedEvent: ({ event }) => {\n if (event.stepName !== nodeName) {\n setNodeName(event.stepName);\n }\n },\n onStepFinishedEvent: ({ event }) => {\n if (event.stepName === nodeName) {\n setNodeName(undefined);\n }\n },\n };\n\n const { unsubscribe } = agent.subscribe(subscriber);\n return () => {\n unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agentId, nodeName]);\n\n const getStateRender = useCallback(\n (messageId: string) => {\n return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {\n if (claimsRef.current[messageId]) {\n return stateRenderId === claimsRef.current[messageId].stateRenderId;\n }\n const matchingAgentName = stateRender.name === agentId;\n const matchesNodeContext = stateRender.nodeName ? stateRender.nodeName === nodeName : true;\n return matchingAgentName && matchesNodeContext;\n });\n },\n [coAgentStateRenders, nodeName, agentId],\n );\n\n // Message ID-based claim system - A state render can only be claimed by one message ID\n const handleRenderRequest = ({\n stateRenderId,\n messageId,\n runId,\n stateSnapshot: renderSnapshot,\n }: {\n stateRenderId: string;\n messageId: string;\n runId?: string;\n stateSnapshot?: any;\n }): boolean => {\n // Check if this message has already claimed this state render\n if (claimsRef.current[messageId]) {\n const canRender = claimsRef.current[messageId].stateRenderId === stateRenderId;\n\n // Update runId if it doesn't exist\n if (\n canRender &&\n runId &&\n (!claimsRef.current[messageId].runId || claimsRef.current[messageId].runId === \"pending\")\n ) {\n claimsRef.current[messageId].runId = runId;\n }\n\n return canRender;\n }\n\n // Do not allow render if any other message has claimed this state render\n const renderClaimedByOtherMessage = Object.values(claimsRef.current).find(\n (c) =>\n c.stateRenderId === stateRenderId &&\n dataToUUID(getStateWithoutConstantKeys(c.stateSnapshot)) ===\n dataToUUID(getStateWithoutConstantKeys(renderSnapshot)),\n );\n if (renderClaimedByOtherMessage) {\n // If:\n // - state render already claimed\n // - snapshot exists in the claiming object and is different from current,\n if (\n renderSnapshot &&\n renderClaimedByOtherMessage.stateSnapshot &&\n !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, renderSnapshot)\n ) {\n claimsRef.current[messageId] = { stateRenderId, runId };\n return true;\n }\n return false;\n }\n\n // No existing claim anywhere yet – allow this message to claim even if we already know the runId.\n if (!runId) {\n return false;\n }\n\n claimsRef.current[messageId] = { stateRenderId, runId };\n return true;\n };\n\n return useMemo(() => {\n if (messageIndexInRun !== 0) {\n return null;\n }\n\n const [stateRenderId, stateRender] = getStateRender(message.id) ?? [];\n\n if (!stateRender || !stateRenderId) {\n return null;\n }\n\n // Is there any state we can use?\n const snapshot = stateSnapshot ? parseJson(stateSnapshot, stateSnapshot) : agent?.state;\n\n // Synchronously check/claim - returns true if this message can render\n const canRender = handleRenderRequest({\n stateRenderId,\n messageId: message.id,\n runId: effectiveRunId,\n stateSnapshot: snapshot,\n });\n if (!canRender) {\n return null;\n }\n\n // If we found state, and given that now there's a claim for the current message, let's save it in the claim\n if (snapshot && !claimsRef.current[message.id].locked) {\n if (stateSnapshot) {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n claimsRef.current[message.id].locked = true;\n } else {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n }\n }\n\n if (stateRender.handler) {\n stateRender.handler({\n state: stateSnapshot ? parseJson(stateSnapshot, stateSnapshot) : (agent?.state ?? {}),\n nodeName: nodeName ?? \"\",\n });\n }\n\n if (stateRender.render) {\n const status = agent?.isRunning ? \"inProgress\" : \"complete\";\n\n if (typeof stateRender.render === \"string\") return stateRender.render;\n\n return stateRender.render({\n status,\n // Always use state from claim, to make sure the state does not seem \"wiped\" for a fraction of a second\n state: claimsRef.current[message.id].stateSnapshot ?? {},\n nodeName: nodeName ?? \"\",\n });\n }\n }, [\n getStateRender,\n stateSnapshot,\n agent?.state,\n agent?.isRunning,\n nodeName,\n effectiveRunId,\n message.id,\n messageIndexInRun,\n ]);\n}\n\nexport function CoAgentStateRenderBridge(props: CoAgentStateRenderBridgeProps) {\n return useCoagentStateRenderBridge(props.agentId, props);\n}\n"],"mappings":";;;;;;;;AAAA,SAA6C,gBAAgB;AAC7D,SAAS,aAAa,WAAW,SAAS,gBAAgB;AAG1D,SAAS,YAAY,iBAAiB;AAEtC,SAAS,4BAA4B,OAAY;AAC/C,MAAI,CAAC;AAAO,WAAO,CAAC;AACpB,QAAqE,YAA7D,YAAU,OAAO,WAR3B,IAQuE,IAA7B,qCAA6B,IAA7B,CAAhC,YAAU,SAAO;AACzB,SAAO;AACT;AAGA,SAAS,gBAAgB,GAAQ,GAAQ;AACvC,MAAK,KAAK,CAAC,KAAO,CAAC,KAAK;AAAI,WAAO;AACnC,QAAiE,QAAzD,YAAU,OAAO,WAf3B,IAemE,IAAzB,iCAAyB,IAAzB,CAAhC,YAAU,SAAO;AACzB,QAKI,QAJF;AAAA,cAAU;AAAA,IACV,OAAO;AAAA,IACP,YAAY;AAAA,EAnBhB,IAqBM,IADC,iCACD,IADC;AAAA,IAHH;AAAA,IACA;AAAA,IACA;AAAA;AAIF,SAAO,KAAK,UAAU,oBAAoB,MAAM,KAAK,UAAU,oBAAoB;AACrF;AAgGO,SAAS,4BAA4B,SAAiB,OAAsC;AAxHnG;AAyHE,QAAM,EAAE,eAAe,mBAAmB,QAAQ,IAAI;AACtD,QAAM,EAAE,qBAAqB,UAAU,IAAI,uBAAuB;AAClE,QAAM,EAAE,MAAM,IAAI,SAAS,EAAE,QAAQ,CAAC;AACtC,QAAM,CAAC,UAAU,WAAW,IAAI,SAA6B,MAAS;AAEtE,QAAM,SAAQ,WAAM,UAAN,YAAe,QAAQ;AACrC,QAAM,iBAAiB,SAAS;AAEhC,YAAU,MAAM;AACd,QAAI,CAAC;AAAO;AACZ,UAAM,aAA8B;AAAA,MAClC,oBAAoB,CAAC,EAAE,MAAM,MAAM;AACjC,YAAI,MAAM,aAAa,UAAU;AAC/B,sB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AA,IACH;AAEA,QAAI,YAAY,QAAQ;AACtB,YAAM,UAAS,+BAAO,aAAY,eAAe;AAEjD,UAAI,OAAO,YAAY,WAAW;AAAU,eAAO,YAAY;AAE/D,aAAO,YAAY,OAAO;AAAA,QACxB;AAAA;AAAA,QAEA,QAAO,eAAU,QAAQ,QAAQ,EAAE,EAAE,kBAA9B,YAA+C,CAAC;AAAA,QACvD,UAAU,8BAAY;AAAA,MACxB,CAAC;AAAA,IACH;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,EACF,CAAC;AACH;AAEO,SAAS,yBAAyB,OAAsC;AAC7E,SAAO,4BAA4B,MAAM,SAAS,KAAK;AACzD;","names":["runId","_a"]}
|
|
@@ -7,7 +7,9 @@ import {
|
|
|
7
7
|
import React from "react";
|
|
8
8
|
import { getZodParameters } from "@copilotkit/shared";
|
|
9
9
|
import { parseJson } from "@copilotkit/shared";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
useFrontendTool as useFrontendToolVNext
|
|
12
|
+
} from "@copilotkitnext/react";
|
|
11
13
|
function useFrontendTool(tool, dependencies) {
|
|
12
14
|
const { name, description, parameters, render, followUp } = tool;
|
|
13
15
|
const zodParameters = getZodParameters(parameters);
|
|
@@ -17,7 +19,11 @@ function useFrontendTool(tool, dependencies) {
|
|
|
17
19
|
}
|
|
18
20
|
if (typeof render === "string") {
|
|
19
21
|
const staticRender = render;
|
|
20
|
-
return () => React.createElement(
|
|
22
|
+
return () => React.createElement(
|
|
23
|
+
React.Fragment,
|
|
24
|
+
null,
|
|
25
|
+
staticRender
|
|
26
|
+
);
|
|
21
27
|
}
|
|
22
28
|
return (args) => {
|
|
23
29
|
const renderArgs = __spreadProps(__spreadValues({}, args), {
|
|
@@ -43,4 +49,4 @@ function useFrontendTool(tool, dependencies) {
|
|
|
43
49
|
export {
|
|
44
50
|
useFrontendTool
|
|
45
51
|
};
|
|
46
|
-
//# sourceMappingURL=chunk-
|
|
52
|
+
//# sourceMappingURL=chunk-T2VBHAAP.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-frontend-tool.ts"],"sourcesContent":["import React from \"react\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport { Parameter, getZodParameters, MappedParameterTypes } from \"@copilotkit/shared\";\nimport { parseJson } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport {\n type ReactFrontendTool,\n useFrontendTool as useFrontendToolVNext,\n} from \"@copilotkitnext/react\";\n\ntype FrontendToolOptions<T extends Parameter[] | []> = ReactFrontendTool<MappedParameterTypes<T>>;\ntype FrontendToolRenderArgs<T extends Parameter[] | []> =\n | {\n name: string;\n args: Partial<MappedParameterTypes<T>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n args: MappedParameterTypes<T>;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n args: MappedParameterTypes<T>;\n status: ToolCallStatus.Complete;\n result: string;\n };\n\nexport type UseFrontendToolArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n} & Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\" | \"handler\" | \"followUp\" | \"render\"\n>;\n\nexport function useFrontendTool<const T extends Parameter[] = []>(\n tool: UseFrontendToolArgs<T>,\n dependencies?: any[],\n) {\n const { name, description, parameters, render, followUp } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const normalizedRender: FrontendToolOptions<T>[\"render\"] | undefined = (() => {\n if (typeof render === \"undefined\") {\n return undefined;\n }\n\n if (typeof render === \"string\") {\n const staticRender = render;\n return (() =>\n React.createElement(\n React.Fragment,\n null,\n staticRender,\n )) as FrontendToolOptions<T>[\"render\"];\n }\n\n return ((args: FrontendToolRenderArgs<T>) => {\n const renderArgs = {\n ...args,\n result: typeof args.result === \"string\" ? parseJson(args.result, args.result) : args.result,\n } as ActionRenderProps<T>;\n\n const rendered = render(renderArgs);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n }) as FrontendToolOptions<T>[\"render\"];\n })();\n\n useFrontendToolVNext<MappedParameterTypes<T>>({\n name,\n description,\n parameters: zodParameters,\n handler: tool.handler,\n followUp,\n render: normalizedRender,\n });\n}\n"],"mappings":";;;;;;AAAA,OAAO,WAAW;AAElB,SAAoB,wBAA8C;AAClE,SAAS,iBAAiB;AAE1B;AAAA,EAEE,mBAAmB;AAAA,OACd;AA8BA,SAAS,gBACd,MACA,cACA;AACA,QAAM,EAAE,MAAM,aAAa,YAAY,QAAQ,SAAS,IAAI;AAC5D,QAAM,gBAAgB,iBAAiB,UAAU;AAEjD,QAAM,oBAAkE,MAAM;AAC5E,QAAI,OAAO,WAAW,aAAa;AACjC,aAAO;AAAA,IACT;AAEA,QAAI,OAAO,WAAW,UAAU;AAC9B,YAAM,eAAe;AACrB,aAAQ,MACN,MAAM;AAAA,QACJ,MAAM;AAAA,QACN;AAAA,QACA;AAAA,MACF;AAAA,IACJ;AAEA,WAAQ,CAAC,SAAoC;AAC3C,YAAM,aAAa,iCACd,OADc;AAAA,QAEjB,QAAQ,OAAO,KAAK,WAAW,WAAW,UAAU,KAAK,QAAQ,KAAK,MAAM,IAAI,KAAK;AAAA,MACvF;AAEA,YAAM,WAAW,OAAO,UAAU;AAElC,UAAI,OAAO,aAAa,UAAU;AAChC,eAAO,MAAM,cAAc,MAAM,UAAU,MAAM,QAAQ;AAAA,MAC3D;AAEA,aAAO,8BAAY;AAAA,IACrB;AAAA,EACF,GAAG;AAEH,uBAA8C;AAAA,IAC5C;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ,SAAS,KAAK;AAAA,IACd;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AACH;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCopilotAction
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-EG56H77V.mjs";
|
|
4
4
|
import {
|
|
5
5
|
__spreadProps,
|
|
6
6
|
__spreadValues
|
|
@@ -14,4 +14,4 @@ function useDefaultTool(tool, dependencies) {
|
|
|
14
14
|
export {
|
|
15
15
|
useDefaultTool
|
|
16
16
|
};
|
|
17
|
-
//# sourceMappingURL=chunk-
|
|
17
|
+
//# sourceMappingURL=chunk-U2ZRVVKT.mjs.map
|
|
@@ -1,26 +1,39 @@
|
|
|
1
|
+
import {
|
|
2
|
+
useAgentNodeName
|
|
3
|
+
} from "./chunk-I76HKHPJ.mjs";
|
|
1
4
|
import {
|
|
2
5
|
useCopilotContext
|
|
3
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-AFNWX62Q.mjs";
|
|
7
|
+
import {
|
|
8
|
+
__spreadProps,
|
|
9
|
+
__spreadValues
|
|
10
|
+
} from "./chunk-SKC7AJIV.mjs";
|
|
4
11
|
|
|
5
12
|
// src/hooks/use-langgraph-interrupt-render.ts
|
|
6
13
|
import React, { useCallback, useEffect, useMemo } from "react";
|
|
7
14
|
import { MetaEventName } from "@copilotkit/runtime-client-gql";
|
|
8
15
|
import { dataToUUID, parseJson } from "@copilotkit/shared";
|
|
16
|
+
import { useCopilotChatConfiguration } from "@copilotkitnext/react";
|
|
9
17
|
var InterruptRenderer = ({ event, result, render, resolve }) => {
|
|
10
18
|
return render({ event, result, resolve });
|
|
11
19
|
};
|
|
12
20
|
function useLangGraphInterruptRender(agent) {
|
|
21
|
+
var _a;
|
|
13
22
|
const {
|
|
14
23
|
interruptActions,
|
|
15
24
|
agentSession,
|
|
16
25
|
threadId,
|
|
17
26
|
interruptEventQueue,
|
|
18
27
|
addInterruptEvent,
|
|
19
|
-
|
|
28
|
+
resolveInterruptEvent
|
|
20
29
|
} = useCopilotContext();
|
|
30
|
+
const existingConfig = useCopilotChatConfiguration();
|
|
31
|
+
const resolvedAgentId = (_a = existingConfig == null ? void 0 : existingConfig.agentId) != null ? _a : "default";
|
|
32
|
+
const nodeName = useAgentNodeName(resolvedAgentId);
|
|
21
33
|
useEffect(() => {
|
|
22
34
|
if (!agent)
|
|
23
35
|
return;
|
|
36
|
+
let localInterrupt = null;
|
|
24
37
|
const subscriber = {
|
|
25
38
|
onCustomEvent: ({ event }) => {
|
|
26
39
|
if (event.name === "on_interrupt") {
|
|
@@ -29,12 +42,21 @@ function useLangGraphInterruptRender(agent) {
|
|
|
29
42
|
type: event.type,
|
|
30
43
|
value: parseJson(event.value, event.value)
|
|
31
44
|
};
|
|
32
|
-
const eventId = dataToUUID(
|
|
33
|
-
|
|
45
|
+
const eventId = dataToUUID(eventData, "interruptEvents");
|
|
46
|
+
localInterrupt = {
|
|
34
47
|
eventId,
|
|
35
48
|
threadId,
|
|
36
49
|
event: eventData
|
|
37
|
-
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
onRunStartedEvent: () => {
|
|
54
|
+
localInterrupt = null;
|
|
55
|
+
},
|
|
56
|
+
onRunFinalized: () => {
|
|
57
|
+
if (localInterrupt) {
|
|
58
|
+
addInterruptEvent(localInterrupt);
|
|
59
|
+
localInterrupt = null;
|
|
38
60
|
}
|
|
39
61
|
}
|
|
40
62
|
};
|
|
@@ -52,7 +74,7 @@ function useLangGraphInterruptRender(agent) {
|
|
|
52
74
|
}
|
|
53
75
|
}
|
|
54
76
|
});
|
|
55
|
-
|
|
77
|
+
resolveInterruptEvent(threadId, eventId, response != null ? response : "");
|
|
56
78
|
},
|
|
57
79
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
58
80
|
[agent, threadId]
|
|
@@ -60,7 +82,7 @@ function useLangGraphInterruptRender(agent) {
|
|
|
60
82
|
return useMemo(() => {
|
|
61
83
|
const eventQueue = interruptEventQueue[threadId] || [];
|
|
62
84
|
const currentQueuedEvent = eventQueue.find((qe) => !qe.event.response);
|
|
63
|
-
if (!currentQueuedEvent)
|
|
85
|
+
if (!currentQueuedEvent || !agentSession)
|
|
64
86
|
return null;
|
|
65
87
|
const allActions = Object.values(interruptActions);
|
|
66
88
|
const matchingAction = allActions.find((action) => {
|
|
@@ -68,7 +90,9 @@ function useLangGraphInterruptRender(agent) {
|
|
|
68
90
|
return true;
|
|
69
91
|
return action.enabled({
|
|
70
92
|
eventValue: currentQueuedEvent.event.value,
|
|
71
|
-
agentMetadata: agentSession
|
|
93
|
+
agentMetadata: __spreadProps(__spreadValues({}, agentSession), {
|
|
94
|
+
nodeName
|
|
95
|
+
})
|
|
72
96
|
});
|
|
73
97
|
});
|
|
74
98
|
if (!matchingAction)
|
|
@@ -98,4 +122,4 @@ function useLangGraphInterruptRender(agent) {
|
|
|
98
122
|
export {
|
|
99
123
|
useLangGraphInterruptRender
|
|
100
124
|
};
|
|
101
|
-
//# sourceMappingURL=chunk-
|
|
125
|
+
//# sourceMappingURL=chunk-VV56AVPB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-langgraph-interrupt-render.ts"],"sourcesContent":["import { useCopilotContext } from \"../context\";\nimport React, { useCallback, useEffect, useMemo } from \"react\";\nimport type { AbstractAgent, AgentSubscriber } from \"@ag-ui/client\";\nimport { MetaEventName } from \"@copilotkit/runtime-client-gql\";\nimport { dataToUUID, parseJson } from \"@copilotkit/shared\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\nimport { useCopilotChatConfiguration } from \"@copilotkitnext/react\";\n\ntype InterruptProps = {\n event: any;\n result: any;\n render: (props: {\n event: any;\n result: any;\n resolve: (response: string) => void;\n }) => string | React.ReactElement;\n resolve: (response: string) => void;\n};\n\nconst InterruptRenderer: React.FC<InterruptProps> = ({ event, result, render, resolve }) => {\n return render({ event, result, resolve });\n};\n\nexport function useLangGraphInterruptRender(\n agent: AbstractAgent,\n): string | React.ReactElement | null {\n const {\n interruptActions,\n agentSession,\n threadId,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n } = useCopilotContext();\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const nodeName = useAgentNodeName(resolvedAgentId);\n\n useEffect(() => {\n if (!agent) return;\n let localInterrupt: any = null;\n const subscriber: AgentSubscriber = {\n onCustomEvent: ({ event }) => {\n if (event.name === \"on_interrupt\") {\n const eventData = {\n name: MetaEventName.LangGraphInterruptEvent,\n type: event.type,\n value: parseJson(event.value, event.value),\n };\n const eventId = dataToUUID(eventData, \"interruptEvents\");\n localInterrupt = {\n eventId,\n threadId,\n event: eventData,\n };\n }\n },\n onRunStartedEvent: () => {\n localInterrupt = null;\n },\n onRunFinalized: () => {\n if (localInterrupt) {\n addInterruptEvent(localInterrupt);\n localInterrupt = null;\n }\n },\n };\n\n const { unsubscribe } = agent.subscribe(subscriber);\n return () => {\n unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agent, threadId]);\n\n const handleResolve = useCallback(\n (eventId: string, response?: string) => {\n agent?.runAgent({\n forwardedProps: {\n command: {\n resume: response,\n },\n },\n });\n resolveInterruptEvent(threadId, eventId, response ?? \"\");\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [agent, threadId],\n );\n\n return useMemo(() => {\n // Get the queue for this thread and find the first unresponded event\n const eventQueue = interruptEventQueue[threadId] || [];\n const currentQueuedEvent = eventQueue.find((qe) => !qe.event.response);\n\n if (!currentQueuedEvent || !agentSession) return null;\n\n // Find the first matching action from all registered actions\n const allActions = Object.values(interruptActions);\n const matchingAction = allActions.find((action) => {\n if (!action.enabled) return true; // No filter = match all\n return action.enabled({\n eventValue: currentQueuedEvent.event.value,\n agentMetadata: {\n ...agentSession,\n nodeName,\n },\n });\n });\n\n if (!matchingAction) return null;\n\n const { render, handler } = matchingAction;\n\n const resolveInterrupt = (response: string) => {\n handleResolve(currentQueuedEvent.eventId, response);\n };\n\n let result = null;\n if (handler) {\n result = handler({\n event: currentQueuedEvent.event,\n resolve: resolveInterrupt,\n });\n }\n\n if (!render) return null;\n\n return React.createElement(InterruptRenderer, {\n event: currentQueuedEvent.event,\n result,\n render,\n resolve: resolveInterrupt,\n });\n }, [interruptActions, interruptEventQueue, threadId, agentSession, handleResolve]);\n}\n"],"mappings":";;;;;;;;;;;;AACA,OAAO,SAAS,aAAa,WAAW,eAAe;AAEvD,SAAS,qBAAqB;AAC9B,SAAS,YAAY,iBAAiB;AAEtC,SAAS,mCAAmC;AAa5C,IAAM,oBAA8C,CAAC,EAAE,OAAO,QAAQ,QAAQ,QAAQ,MAAM;AAC1F,SAAO,OAAO,EAAE,OAAO,QAAQ,QAAQ,CAAC;AAC1C;AAEO,SAAS,4BACd,OACoC;AAzBtC;AA0BE,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,kBAAkB;AACtB,QAAM,iBAAiB,4BAA4B;AACnD,QAAM,mBAAkB,sDAAgB,YAAhB,YAA2B;AACnD,QAAM,WAAW,iBAAiB,eAAe;AAEjD,YAAU,MAAM;AACd,QAAI,CAAC;AAAO;AACZ,QAAI,iBAAsB;AAC1B,UAAM,aAA8B;AAAA,MAClC,eAAe,CAAC,EAAE,MAAM,MAAM;AAC5B,YAAI,MAAM,SAAS,gBAAgB;AACjC,gBAAM,YAAY;AAAA,YAChB,MAAM,cAAc;AAAA,YACpB,MAAM,MAAM;AAAA,YACZ,OAAO,UAAU,MAAM,OAAO,MAAM,KAAK;AAAA,UAC3C;AACA,gBAAM,UAAU,WAAW,WAAW,iBAAiB;AACvD,2BAAiB;AAAA,YACf;AAAA,YACA;AAAA,YACA,OAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF;AAAA,MACA,mBAAmB,MAAM;AACvB,yBAAiB;AAAA,MACnB;AAAA,MACA,gBAAgB,MAAM;AACpB,YAAI,gBAAgB;AAClB,4BAAkB,cAAc;AAChC,2BAAi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