@copilotkit/react-core 1.50.0-beta.1 → 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 +14 -11
- 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
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useToast
|
|
3
3
|
} from "./chunk-EFL5OBKN.mjs";
|
|
4
|
-
import {
|
|
5
|
-
useCopilotContext
|
|
6
|
-
} from "./chunk-WVLHXIFP.mjs";
|
|
7
4
|
|
|
8
5
|
// src/components/CopilotListeners.tsx
|
|
9
6
|
import { useCallback, useEffect, useRef } from "react";
|
|
@@ -43,11 +40,9 @@ var usePredictStateSubscription = (agent) => {
|
|
|
43
40
|
}, [agent, getSubscriber]);
|
|
44
41
|
};
|
|
45
42
|
function CopilotListeners() {
|
|
46
|
-
var _a, _b;
|
|
47
43
|
const { copilotkit } = useCopilotKit();
|
|
48
|
-
const { agentSession } = useCopilotContext();
|
|
49
44
|
const existingConfig = useCopilotChatConfiguration();
|
|
50
|
-
const resolvedAgentId =
|
|
45
|
+
const resolvedAgentId = existingConfig == null ? void 0 : existingConfig.agentId;
|
|
51
46
|
const { setBannerError } = useToast();
|
|
52
47
|
const { agent } = useAgent({ agentId: resolvedAgentId });
|
|
53
48
|
usePredictStateSubscription(agent);
|
|
@@ -68,4 +63,4 @@ function CopilotListeners() {
|
|
|
68
63
|
export {
|
|
69
64
|
CopilotListeners
|
|
70
65
|
};
|
|
71
|
-
//# sourceMappingURL=chunk-
|
|
66
|
+
//# sourceMappingURL=chunk-WF65O6HX.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/components/CopilotListeners.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { useAgent, useCopilotChatConfiguration, useCopilotKit } from \"@copilotkitnext/react\";\nimport { CopilotKitError, parseJson } from \"@copilotkit/shared\";\nimport { useCopilotContext } from \"../context\";\nimport { AbstractAgent, AgentSubscriber, AGUIConnectNotImplementedError } from \"@ag-ui/client\";\nimport { useErrorToast } from \"./error-boundary/error-utils\";\nimport { CopilotKitCoreSubscriber } from \"@copilotkitnext/core\";\nimport { useToast } from \"./toast/toast-provider\";\nimport { CopilotKitLowLevelError } from \"@copilotkit/shared\";\n\nconst usePredictStateSubscription = (agent?: AbstractAgent) => {\n const predictStateToolsRef = useRef<\n {\n tool: string;\n state_key: string;\n tool_argument: string;\n }[]\n >([]);\n\n const getSubscriber = useCallback(\n (agent: AbstractAgent): AgentSubscriber => ({\n onCustomEvent: ({ event }) => {\n if (event.name === \"PredictState\") {\n predictStateToolsRef.current = event.value;\n }\n },\n onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {\n predictStateToolsRef.current.forEach((t) => {\n if (t?.tool !== toolCallName) return;\n\n const emittedState =\n typeof partialToolCallArgs === \"string\"\n ? parseJson(partialToolCallArgs as unknown as string, partialToolCallArgs)\n : partialToolCallArgs;\n\n agent.setState({\n [t.state_key]: emittedState[t.state_key],\n });\n });\n },\n }),\n [],\n );\n\n useEffect(() => {\n if (!agent) return;\n\n const subscriber = getSubscriber(agent);\n const { unsubscribe } = agent.subscribe(subscriber);\n return () => {\n unsubscribe();\n };\n }, [agent, getSubscriber]);\n};\n\nexport function CopilotListeners() {\n const { copilotkit } = useCopilotKit();\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId;\n const { setBannerError } = useToast();\n\n const { agent } = useAgent({ agentId: resolvedAgentId });\n\n usePredictStateSubscription(agent);\n\n useEffect(() => {\n const subscriber: CopilotKitCoreSubscriber = {\n onError: ({ error }) => {\n // @ts-expect-error -- for now, choose a random CPK error type to display the error toast\n setBannerError(new CopilotKitLowLevelError({ error, message: error.message }));\n },\n };\n const subscription = copilotkit.subscribe(subscriber);\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit?.subscribe]);\n\n return null;\n}\n"],"mapp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,EAAE,MAAM,MAAM;AAEtB,uBAAe,IAAI,wBAAwB,EAAE,OAAO,SAAS,MAAM,QAAQ,CAAC,CAAC;AAAA,MAC/E;AAAA,IACF;AACA,UAAM,eAAe,WAAW,UAAU,UAAU;AAEpD,WAAO,MAAM;AACX,mBAAa,YAAY;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,yCAAY,SAAS,CAAC;AAE1B,SAAO;AACT;","names":["agent"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__spreadProps,
|
|
3
|
+
__spreadValues
|
|
4
|
+
} from "./chunk-SKC7AJIV.mjs";
|
|
5
|
+
|
|
6
|
+
// src/hooks/use-copilot-chat-suggestions.tsx
|
|
7
|
+
import {
|
|
8
|
+
useConfigureSuggestions,
|
|
9
|
+
useCopilotChatConfiguration
|
|
10
|
+
} from "@copilotkitnext/react";
|
|
11
|
+
function useCopilotChatSuggestions(config, dependencies = []) {
|
|
12
|
+
var _a, _b;
|
|
13
|
+
const existingConfig = useCopilotChatConfiguration();
|
|
14
|
+
const resolvedAgentId = (_a = existingConfig == null ? void 0 : existingConfig.agentId) != null ? _a : "default";
|
|
15
|
+
const available = (_b = config.available === "enabled" ? "always" : config.available) != null ? _b : "before-first-message";
|
|
16
|
+
const finalSuggestionConfig = __spreadProps(__spreadValues({}, config), {
|
|
17
|
+
available,
|
|
18
|
+
consumerAgentId: resolvedAgentId
|
|
19
|
+
// Use chatConfig.agentId here
|
|
20
|
+
});
|
|
21
|
+
useConfigureSuggestions(finalSuggestionConfig, dependencies);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export {
|
|
25
|
+
useCopilotChatSuggestions
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=chunk-XDFVCQD3.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-copilot-chat-suggestions.tsx"],"sourcesContent":["/**\n * <Callout type=\"warning\">\n * useCopilotChatSuggestions is experimental. The interface is not final and\n * can change without notice.\n * </Callout>\n *\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * <br/>\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-chat-suggestions/use-copilot-chat-suggestions.gif\" width=\"500\" />\n *\n * ## Usage\n *\n * ### Install Dependencies\n *\n * This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.\n *\n * ```shell npm2yarn \\\"@copilotkit/react-ui\"\\\n * npm install @copilotkit/react-core @copilotkit/react-ui\n * ```\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChatSuggestions } from \"@copilotkit/react-ui\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotChatSuggestions({\n * instructions: `The following employees are on duty: ${JSON.stringify(employees)}`,\n * });\n * }\n * ```\n *\n * ### Dependency Management\n *\n * ```tsx\n * import { useCopilotChatSuggestions } from \"@copilotkit/react-ui\";\n *\n * export function MyComponent() {\n * useCopilotChatSuggestions(\n * {\n * instructions: \"Suggest the most relevant next actions.\",\n * },\n * [appState],\n * );\n * }\n * ```\n *\n * In the example above, the suggestions are generated based on the given instructions.\n * The hook monitors `appState`, and updates suggestions accordingly whenever it changes.\n *\n * ### Behavior and Lifecycle\n *\n * The hook registers the configuration with the chat context upon component mount and\n * removes it on unmount, ensuring a clean and efficient lifecycle management.\n */\nimport {\n useConfigureSuggestions,\n useCopilotChatConfiguration,\n useCopilotKit,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport { useEffect } from \"react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkitnext/core\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> & Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<StaticSuggestionsConfig, \"suggestions\"> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype DynamicSuggestionsConfigInput = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * Whether the suggestions are available. Defaults to `enabled`.\n * @default enabled\n */\n available?: \"enabled\" | \"disabled\" | \"always\" | \"before-first-message\" | \"after-first-message\";\n\n /**\n * An optional class name to apply to the suggestions.\n */\n className?: string;\n};\n\nexport type UseCopilotChatSuggestionsConfiguration =\n | DynamicSuggestionsConfigInput\n | StaticSuggestionsConfigInput;\n\nexport function useCopilotChatSuggestions(\n config: UseCopilotChatSuggestionsConfiguration,\n dependencies: any[] = [],\n) {\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n\n const available =\n (config.available === \"enabled\" ? \"always\" : config.available) ?? \"before-first-message\";\n\n const finalSuggestionConfig = {\n ...config,\n available,\n consumerAgentId: resolvedAgentId, // Use chatConfig.agentId here\n };\n useConfigureSuggestions(finalSuggestionConfig, dependencies);\n}\n"],"mappings":";;;;;;AA4DA;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AA0CA,SAAS,0BACd,QACA,eAAsB,CAAC,GACvB;AA9GF;AA+GE,QAAM,iBAAiB,4BAA4B;AACnD,QAAM,mBAAkB,sDAAgB,YAAhB,YAA2B;AAEnD,QAAM,aACH,YAAO,cAAc,YAAY,WAAW,OAAO,cAAnD,YAAiE;AAEpE,QAAM,wBAAwB,iCACzB,SADyB;AAAA,IAE5B;AAAA,IACA,iBAAiB;AAAA;AAAA,EACnB;AACA,0BAAwB,uBAAuB,YAAY;AAC7D;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
} from "./chunk-PIF5KJYI.mjs";
|
|
6
6
|
import {
|
|
7
7
|
useCopilotContext
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-AFNWX62Q.mjs";
|
|
9
9
|
import {
|
|
10
10
|
useCopilotMessagesContext
|
|
11
11
|
} from "./chunk-DMLQZG75.mjs";
|
|
@@ -756,4 +756,4 @@ function ContextTab({ context }) {
|
|
|
756
756
|
export {
|
|
757
757
|
DeveloperConsoleModal
|
|
758
758
|
};
|
|
759
|
-
//# sourceMappingURL=chunk-
|
|
759
|
+
//# sourceMappingURL=chunk-YCG6SNAU.mjs.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCopilotChatInternal
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-3775VM7Y.mjs";
|
|
4
4
|
import {
|
|
5
5
|
useCopilotContext
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-AFNWX62Q.mjs";
|
|
7
7
|
import {
|
|
8
8
|
__async
|
|
9
9
|
} from "./chunk-SKC7AJIV.mjs";
|
|
@@ -83,4 +83,4 @@ function useCopilotChatHeadless_c(options = {}) {
|
|
|
83
83
|
export {
|
|
84
84
|
useCopilotChatHeadless_c
|
|
85
85
|
};
|
|
86
|
-
//# sourceMappingURL=chunk-
|
|
86
|
+
//# sourceMappingURL=chunk-YJGPIN3R.mjs.map
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-FDOMAPJY.mjs";
|
|
7
7
|
import {
|
|
8
8
|
CopilotContext
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-AFNWX62Q.mjs";
|
|
10
10
|
|
|
11
11
|
// src/hooks/use-coagent-state-render.ts
|
|
12
12
|
import { useRef, useContext, useEffect } from "react";
|
|
@@ -83,4 +83,4 @@ function useCoAgentStateRender(action, dependencies) {
|
|
|
83
83
|
export {
|
|
84
84
|
useCoAgentStateRender
|
|
85
85
|
};
|
|
86
|
-
//# sourceMappingURL=chunk-
|
|
86
|
+
//# sourceMappingURL=chunk-YTQHRJUA.mjs.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// src/hooks/use-copilot-readable.ts
|
|
2
|
+
import { useCopilotKit } from "@copilotkitnext/react";
|
|
3
|
+
import { useEffect, useRef } from "react";
|
|
4
|
+
function useCopilotReadable({ description, value, convert, available }, dependencies) {
|
|
5
|
+
const { copilotkit } = useCopilotKit();
|
|
6
|
+
const ctxIdRef = useRef(void 0);
|
|
7
|
+
useEffect(() => {
|
|
8
|
+
if (!copilotkit)
|
|
9
|
+
return;
|
|
10
|
+
const found = Object.entries(copilotkit.context).find(([id, ctxItem]) => {
|
|
11
|
+
return JSON.stringify({ description, value }) == JSON.stringify(ctxItem);
|
|
12
|
+
});
|
|
13
|
+
if (found) {
|
|
14
|
+
ctxIdRef.current = found[0];
|
|
15
|
+
if (available === "disabled")
|
|
16
|
+
copilotkit.removeContext(ctxIdRef.current);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (!found && available === "disabled")
|
|
20
|
+
return;
|
|
21
|
+
ctxIdRef.current = copilotkit.addContext({
|
|
22
|
+
description,
|
|
23
|
+
value: (convert != null ? convert : JSON.stringify)(value)
|
|
24
|
+
});
|
|
25
|
+
return () => {
|
|
26
|
+
if (!ctxIdRef.current)
|
|
27
|
+
return;
|
|
28
|
+
copilotkit.removeContext(ctxIdRef.current);
|
|
29
|
+
};
|
|
30
|
+
}, [description, value, convert]);
|
|
31
|
+
return ctxIdRef.current;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export {
|
|
35
|
+
useCopilotReadable
|
|
36
|
+
};
|
|
37
|
+
//# sourceMappingURL=chunk-Z6JV2LRY.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-copilot-readable.ts"],"sourcesContent":["/**\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * ```tsx\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotReadable({\n * description: \"The list of employees\",\n * value: employees,\n * });\n * }\n * ```\n *\n * ### Nested Components\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`. This allows you to use `useCopilotReadable` in nested components:\n *\n * ```tsx /employeeContextId/1 {17,23}\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information to copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n *\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useCopilotKit } from \"@copilotkitnext/react\";\nimport { useEffect, useRef } from \"react\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context. Object values are automatically stringified.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * Whether the context is available to the Copilot.\n */\n available?: \"enabled\" | \"disabled\";\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, convert, available }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { copilotkit } = useCopilotKit();\n const ctxIdRef = useRef<string | undefined>(undefined);\n useEffect(() => {\n if (!copilotkit) return;\n\n const found = Object.entries(copilotkit.context).find(([id, ctxItem]) => {\n return JSON.stringify({ description, value }) == JSON.stringify(ctxItem);\n });\n if (found) {\n ctxIdRef.current = found[0];\n if (available === \"disabled\") copilotkit.removeContext(ctxIdRef.current);\n return;\n }\n if (!found && available === \"disabled\") return;\n\n ctxIdRef.current = copilotkit.addContext({\n description,\n value: (convert ?? JSON.stringify)(value),\n });\n\n return () => {\n if (!ctxIdRef.current) return;\n copilotkit.removeContext(ctxIdRef.current);\n };\n }, [description, value, convert]);\n\n return ctxIdRef.current;\n}\n"],"mappings":";AA+DA,SAAS,qBAAqB;AAC9B,SAAS,WAAW,cAAc;AAuC3B,SAAS,mBACd,EAAE,aAAa,OAAO,SAAS,UAAU,GACzC,cACoB;AACpB,QAAM,EAAE,WAAW,IAAI,cAAc;AACrC,QAAM,WAAW,OAA2B,MAAS;AACrD,YAAU,MAAM;AACd,QAAI,CAAC;AAAY;AAEjB,UAAM,QAAQ,OAAO,QAAQ,WAAW,OAAO,EAAE,KAAK,CAAC,CAAC,IAAI,OAAO,MAAM;AACvE,aAAO,KAAK,UAAU,EAAE,aAAa,MAAM,CAAC,KAAK,KAAK,UAAU,OAAO;AAAA,IACzE,CAAC;AACD,QAAI,OAAO;AACT,eAAS,UAAU,MAAM,CAAC;AAC1B,UAAI,cAAc;AAAY,mBAAW,cAAc,SAAS,OAAO;AACvE;AAAA,IACF;AACA,QAAI,CAAC,SAAS,cAAc;AAAY;AAExC,aAAS,UAAU,WAAW,WAAW;AAAA,MACvC;AAAA,MACA,QAAQ,4BAAW,KAAK,WAAW,KAAK;AAAA,IAC1C,CAAC;AAED,WAAO,MAAM;AACX,UAAI,CAAC,SAAS;AAAS;AACvB,iBAAW,cAAc,SAAS,OAAO;AAAA,IAC3C;AAAA,EACF,GAAG,CAAC,aAAa,OAAO,OAAO,CAAC;AAEhC,SAAO,SAAS;AAClB;","names":[]}
|
|
@@ -1,14 +1,19 @@
|
|
|
1
|
+
import {
|
|
2
|
+
useAgentNodeName
|
|
3
|
+
} from "./chunk-I76HKHPJ.mjs";
|
|
1
4
|
import {
|
|
2
5
|
__async,
|
|
6
|
+
__spreadProps,
|
|
3
7
|
__spreadValues
|
|
4
8
|
} from "./chunk-SKC7AJIV.mjs";
|
|
5
9
|
|
|
6
10
|
// src/hooks/use-coagent.ts
|
|
7
11
|
import { useCallback, useEffect, useMemo, useRef } from "react";
|
|
8
|
-
import { useAgent } from "@copilotkitnext/react";
|
|
12
|
+
import { useAgent, useCopilotKit } from "@copilotkitnext/react";
|
|
9
13
|
function useCoAgent(options) {
|
|
10
14
|
const { agent } = useAgent({ agentId: options.name });
|
|
11
|
-
const
|
|
15
|
+
const { copilotkit } = useCopilotKit();
|
|
16
|
+
const nodeName = useAgentNodeName(options.name);
|
|
12
17
|
const handleStateUpdate = useCallback(
|
|
13
18
|
(newState) => {
|
|
14
19
|
if (!agent)
|
|
@@ -22,6 +27,18 @@ function useCoAgent(options) {
|
|
|
22
27
|
},
|
|
23
28
|
[agent == null ? void 0 : agent.state, agent == null ? void 0 : agent.setState]
|
|
24
29
|
);
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
var _a;
|
|
32
|
+
if (!options.config && !options.configurable)
|
|
33
|
+
return;
|
|
34
|
+
let config = (_a = options.config) != null ? _a : {};
|
|
35
|
+
if (options.configurable) {
|
|
36
|
+
config = __spreadProps(__spreadValues({}, config), {
|
|
37
|
+
configurable: __spreadValues(__spreadValues({}, options.configurable), config.configurable)
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
copilotkit.setProperties(config);
|
|
41
|
+
}, [options.config, options.configurable]);
|
|
25
42
|
const externalStateStr = useMemo(
|
|
26
43
|
() => isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
|
|
27
44
|
[isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]
|
|
@@ -67,15 +84,6 @@ function useCoAgent(options) {
|
|
|
67
84
|
if (initialStateRef.current !== void 0) {
|
|
68
85
|
handleStateUpdate(initialStateRef.current);
|
|
69
86
|
}
|
|
70
|
-
},
|
|
71
|
-
onStepStartedEvent: ({ event }) => {
|
|
72
|
-
nodeNameRef.current = event.stepName;
|
|
73
|
-
},
|
|
74
|
-
onRunStartedEvent: () => {
|
|
75
|
-
nodeNameRef.current = "start";
|
|
76
|
-
},
|
|
77
|
-
onRunFinishedEvent: () => {
|
|
78
|
-
nodeNameRef.current = "end";
|
|
79
87
|
}
|
|
80
88
|
};
|
|
81
89
|
const subscription = agent.subscribe(subscriber);
|
|
@@ -99,7 +107,7 @@ function useCoAgent(options) {
|
|
|
99
107
|
);
|
|
100
108
|
return {
|
|
101
109
|
name: options.name,
|
|
102
|
-
nodeName
|
|
110
|
+
nodeName,
|
|
103
111
|
threadId: void 0,
|
|
104
112
|
running: false,
|
|
105
113
|
state: initialState,
|
|
@@ -111,7 +119,7 @@ function useCoAgent(options) {
|
|
|
111
119
|
}
|
|
112
120
|
return {
|
|
113
121
|
name: (_c = agent == null ? void 0 : agent.agentId) != null ? _c : options.name,
|
|
114
|
-
nodeName
|
|
122
|
+
nodeName,
|
|
115
123
|
threadId: agent.threadId,
|
|
116
124
|
running: agent.isRunning,
|
|
117
125
|
state: agent.state,
|
|
@@ -140,4 +148,4 @@ var isExternalStateManagement = (options) => {
|
|
|
140
148
|
export {
|
|
141
149
|
useCoAgent
|
|
142
150
|
};
|
|
143
|
-
//# sourceMappingURL=chunk-
|
|
151
|
+
//# sourceMappingURL=chunk-ZYTXB6HH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-coagent.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Message } from \"@copilotkit/shared\";\nimport { useAgent, useCopilotKit } from \"@copilotkitnext/react\";\nimport { type AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<T> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (...args: any[]) => Promise<any>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const { agent } = useAgent({ agentId: options.name });\n const { copilotkit } = useCopilotKit();\n const nodeName = useAgentNodeName(options.name);\n\n const handleStateUpdate = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n if (!agent) return;\n\n if (typeof newState === \"function\") {\n const updater = newState as (prevState: T | undefined) => T;\n agent.setState(updater(agent.state));\n } else {\n agent.setState({ ...agent.state, ...newState });\n }\n },\n [agent?.state, agent?.setState],\n );\n\n useEffect(() => {\n if (!options.config && !options.configurable) return;\n\n let config = options.config ?? {};\n if (options.configurable) {\n config = {\n ...config,\n configurable: {\n ...options.configurable,\n ...config.configurable,\n },\n };\n }\n copilotkit.setProperties(config);\n }, [options.config, options.configurable]);\n\n const externalStateStr = useMemo(\n () => (isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined),\n [isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined],\n );\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (\n agent?.state &&\n isExternalStateManagement(options) &&\n JSON.stringify(options.state) !== JSON.stringify(agent.state)\n ) {\n handleStateUpdate(options.state);\n }\n }, [agent, externalStateStr, handleStateUpdate]);\n\n const hasStateValues = useCallback((value?: Record<string, any>) => {\n return Boolean(value && Object.keys(value).length);\n }, []);\n\n const initialStateRef = useRef<any>(\n isExternalStateManagement(options)\n ? options.state\n : \"initialState\" in options\n ? options.initialState\n : undefined,\n );\n\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n initialStateRef.current = options.state;\n } else if (\"initialState\" in options) {\n initialStateRef.current = options.initialState;\n }\n }, [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : \"initialState\" in options\n ? JSON.stringify(options.initialState)\n : undefined,\n ]);\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStateChanged: (args: any) => {\n if (isExternalStateManagement(options)) {\n options.setState(args.state);\n }\n },\n onRunInitialized: (args: any) => {\n const runHasState = hasStateValues(args.state);\n if (runHasState) {\n handleStateUpdate(args.state);\n return;\n }\n\n if (hasStateValues(agent.state)) {\n return;\n }\n\n if (initialStateRef.current !== undefined) {\n handleStateUpdate(initialStateRef.current);\n }\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent, handleStateUpdate, hasStateValues]);\n\n // Return a consistent shape whether or not the agent is available\n return useMemo<UseCoagentReturnType<T>>(() => {\n if (!agent) {\n const noop = () => {};\n const noopAsync = async () => {};\n const initialState =\n // prefer externally provided state if available\n (\"state\" in options && (options as any).state) ??\n // then initialState if provided\n (\"initialState\" in options && (options as any).initialState) ??\n ({} as T);\n return {\n name: options.name,\n nodeName,\n threadId: undefined,\n running: false,\n state: initialState as T,\n setState: noop,\n start: noop,\n stop: noop,\n run: noopAsync,\n };\n }\n\n return {\n name: agent?.agentId ?? options.name,\n nodeName,\n threadId: agent.threadId,\n running: agent.isRunning,\n state: agent.state,\n setState: handleStateUpdate,\n // TODO: start and run both have same thing. need to figure out\n start: agent.runAgent,\n stop: agent.abortRun,\n run: agent.runAgent,\n };\n }, [\n agent?.state,\n agent?.runAgent,\n agent?.abortRun,\n agent?.runAgent,\n agent?.threadId,\n agent?.isRunning,\n agent?.agentId,\n handleStateUpdate,\n options.name,\n ]);\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n"],"mappings":";;;;;;;;;;AA0FA,SAAS,aAAa,WAAW,SAAS,cAAwB;AAElE,SAAS,UAAU,qBAAqB;AAgHjC,SAAS,WAAoB,SAAwD;AAC1F,QAAM,EAAE,MAAM,IAAI,SAAS,EAAE,SAAS,QAAQ,KAAK,CAAC;AACpD,QAAM,EAAE,WAAW,IAAI,cAAc;AACrC,QAAM,WAAW,iBAAiB,QAAQ,IAAI;AAE9C,QAAM,oBAAoB;AAAA,IACxB,CAAC,aAAoD;AACnD,UAAI,CAAC;AAAO;AAEZ,UAAI,OAAO,aAAa,YAAY;AAClC,cAAM,UAAU;AAChB,cAAM,SAAS,QAAQ,MAAM,KAAK,CAAC;AAAA,MACrC,OAAO;AACL,cAAM,SAAS,kCAAK,MAAM,QAAU,SAAU;AAAA,MAChD;AAAA,IACF;AAAA,IACA,CAAC,+BAAO,OAAO,+BAAO,QAAQ;AAAA,EAChC;AAEA,YAAU,MAAM;AA/NlB;AAgOI,QAAI,CAAC,QAAQ,UAAU,CAAC,QAAQ;AAAc;AAE9C,QAAI,UAAS,aAAQ,WAAR,YAAkB,CAAC;AAChC,QAAI,QAAQ,cAAc;AACxB,eAAS,iCACJ,SADI;AAAA,QAEP,cAAc,kCACT,QAAQ,eACR,OAAO;AAAA,MAEd;AAAA,IACF;AACA,eAAW,cAAc,MAAM;AAAA,EACjC,GAAG,CAAC,QAAQ,QAAQ,QAAQ,YAAY,CAAC;AAEzC,QAAM,mBAAmB;AAAA,IACvB,MAAO,0BAA0B,OAAO,IAAI,KAAK,UAAU,QAAQ,KAAK,IAAI;AAAA,IAC5E,CAAC,0BAA0B,OAAO,IAAI,KAAK,UAAU,QAAQ,KAAK,IAAI,MAAS;AAAA,EACjF;AAGA,YAAU,MAAM;AACd,SACE,+BAAO,UACP,0BAA0B,O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C3B;AAAA,EACF,GAAG,CAAC,OAAO,mBAAmB,cAAc,CAAC;AAG7C,SAAO,QAAiC,MAAM;AAzThD;AA0TI,QAAI,CAAC,OAAO;AACV,YAAM,OAAO,MAAM;AAAA,MAAC;AACpB,YAAM,YAAY,MAAY;AAAA,MAAC;AAC/B,YAAM;AAAA;AAAA,SAEH,sBAAW,WAAY,QAAgB,UAAvC;AAAA;AAAA,UAEA,kBAAkB,WAAY,QAAgB;AAAA,cAF9C,YAGA,CAAC;AAAA;AACJ,aAAO;AAAA,QACL,MAAM,QAAQ;AAAA,QACd;AAAA,QACA,UAAU;AAAA,QACV,SAAS;AAAA,QACT,OAAO;AAAA,QACP,UAAU;AAAA,QACV,OAAO;AAAA,QACP,MAAM;AAAA,QACN,KAAK;AAAA,MACP;AAAA,IACF;AAEA,WAAO;AAAA,MACL,OAAM,oCAAO,YAAP,YAAkB,QAAQ;AAAA,MAChC;AAAA,MACA,UAAU,MAAM;AAAA,MAChB,SAAS,MAAM;AAAA,MACf,OAAO,MAAM;AAAA,MACb,UAAU;AAAA;AAAA,MAEV,OAAO,MAAM;AAAA,MACb,MAAM,MAAM;AAAA,MACZ,KAAK,MAAM;AAAA,IACb;AAAA,EACF,GAAG;AAAA,IACD,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AACH;AAEA,IAAM,4BAA4B,CAChC,YAC8C;AAC9C,SAAO,WAAW,WAAW,cAAc;AAC7C;","names":[]}
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
2
|
var __defProp = Object.defineProperty;
|
|
4
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
6
|
var __export = (target, all) => {
|
|
9
7
|
for (var name in all)
|
|
@@ -17,35 +15,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
17
15
|
}
|
|
18
16
|
return to;
|
|
19
17
|
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
var __async = (__this, __arguments, generator) => {
|
|
30
|
-
return new Promise((resolve, reject) => {
|
|
31
|
-
var fulfilled = (value) => {
|
|
32
|
-
try {
|
|
33
|
-
step(generator.next(value));
|
|
34
|
-
} catch (e) {
|
|
35
|
-
reject(e);
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
var rejected = (value) => {
|
|
39
|
-
try {
|
|
40
|
-
step(generator.throw(value));
|
|
41
|
-
} catch (e) {
|
|
42
|
-
reject(e);
|
|
43
|
-
}
|
|
44
|
-
};
|
|
45
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
46
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
47
|
-
});
|
|
48
|
-
};
|
|
49
19
|
|
|
50
20
|
// src/components/CopilotListeners.tsx
|
|
51
21
|
var CopilotListeners_exports = {};
|
|
@@ -53,118 +23,17 @@ __export(CopilotListeners_exports, {
|
|
|
53
23
|
CopilotListeners: () => CopilotListeners
|
|
54
24
|
});
|
|
55
25
|
module.exports = __toCommonJS(CopilotListeners_exports);
|
|
56
|
-
var
|
|
57
|
-
var
|
|
26
|
+
var import_react2 = require("react");
|
|
27
|
+
var import_react3 = require("@copilotkitnext/react");
|
|
58
28
|
var import_shared2 = require("@copilotkit/shared");
|
|
59
29
|
|
|
60
|
-
// src/context/copilot-context.tsx
|
|
61
|
-
var import_react = __toESM(require("react"));
|
|
62
|
-
var emptyCopilotContext = {
|
|
63
|
-
actions: {},
|
|
64
|
-
setAction: () => {
|
|
65
|
-
},
|
|
66
|
-
removeAction: () => {
|
|
67
|
-
},
|
|
68
|
-
setRegisteredActions: () => "",
|
|
69
|
-
removeRegisteredAction: () => {
|
|
70
|
-
},
|
|
71
|
-
chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
|
|
72
|
-
getContextString: (documents, categories) => returnAndThrowInDebug(""),
|
|
73
|
-
addContext: () => "",
|
|
74
|
-
removeContext: () => {
|
|
75
|
-
},
|
|
76
|
-
getAllContext: () => [],
|
|
77
|
-
getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
|
|
78
|
-
})),
|
|
79
|
-
isLoading: false,
|
|
80
|
-
setIsLoading: () => returnAndThrowInDebug(false),
|
|
81
|
-
chatInstructions: "",
|
|
82
|
-
setChatInstructions: () => returnAndThrowInDebug(""),
|
|
83
|
-
additionalInstructions: [],
|
|
84
|
-
setAdditionalInstructions: () => returnAndThrowInDebug([]),
|
|
85
|
-
getDocumentsContext: (categories) => returnAndThrowInDebug([]),
|
|
86
|
-
addDocumentContext: () => returnAndThrowInDebug(""),
|
|
87
|
-
removeDocumentContext: () => {
|
|
88
|
-
},
|
|
89
|
-
copilotApiConfig: new class {
|
|
90
|
-
get chatApiEndpoint() {
|
|
91
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
92
|
-
}
|
|
93
|
-
get headers() {
|
|
94
|
-
return {};
|
|
95
|
-
}
|
|
96
|
-
get body() {
|
|
97
|
-
return {};
|
|
98
|
-
}
|
|
99
|
-
}(),
|
|
100
|
-
chatSuggestionConfiguration: {},
|
|
101
|
-
addChatSuggestionConfiguration: () => {
|
|
102
|
-
},
|
|
103
|
-
removeChatSuggestionConfiguration: () => {
|
|
104
|
-
},
|
|
105
|
-
showDevConsole: false,
|
|
106
|
-
coagentStates: {},
|
|
107
|
-
setCoagentStates: () => {
|
|
108
|
-
},
|
|
109
|
-
coagentStatesRef: { current: {} },
|
|
110
|
-
setCoagentStatesWithRef: () => {
|
|
111
|
-
},
|
|
112
|
-
agentSession: null,
|
|
113
|
-
setAgentSession: () => {
|
|
114
|
-
},
|
|
115
|
-
forwardedParameters: {},
|
|
116
|
-
agentLock: null,
|
|
117
|
-
threadId: "",
|
|
118
|
-
setThreadId: () => {
|
|
119
|
-
},
|
|
120
|
-
runId: null,
|
|
121
|
-
setRunId: () => {
|
|
122
|
-
},
|
|
123
|
-
chatAbortControllerRef: { current: null },
|
|
124
|
-
availableAgents: [],
|
|
125
|
-
extensions: {},
|
|
126
|
-
setExtensions: () => {
|
|
127
|
-
},
|
|
128
|
-
interruptActions: {},
|
|
129
|
-
setInterruptAction: () => {
|
|
130
|
-
},
|
|
131
|
-
removeInterruptAction: () => {
|
|
132
|
-
},
|
|
133
|
-
interruptEventQueue: {},
|
|
134
|
-
addInterruptEvent: () => {
|
|
135
|
-
},
|
|
136
|
-
removeInterruptEvent: () => {
|
|
137
|
-
},
|
|
138
|
-
onError: () => {
|
|
139
|
-
},
|
|
140
|
-
bannerError: null,
|
|
141
|
-
setBannerError: () => {
|
|
142
|
-
},
|
|
143
|
-
internalErrorHandlers: {},
|
|
144
|
-
setInternalErrorHandler: () => {
|
|
145
|
-
},
|
|
146
|
-
removeInternalErrorHandler: () => {
|
|
147
|
-
}
|
|
148
|
-
};
|
|
149
|
-
var CopilotContext = import_react.default.createContext(emptyCopilotContext);
|
|
150
|
-
function useCopilotContext() {
|
|
151
|
-
const context = import_react.default.useContext(CopilotContext);
|
|
152
|
-
if (context === emptyCopilotContext) {
|
|
153
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
154
|
-
}
|
|
155
|
-
return context;
|
|
156
|
-
}
|
|
157
|
-
function returnAndThrowInDebug(_value) {
|
|
158
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
159
|
-
}
|
|
160
|
-
|
|
161
30
|
// src/components/toast/toast-provider.tsx
|
|
162
|
-
var
|
|
31
|
+
var import_react = require("react");
|
|
163
32
|
var import_shared = require("@copilotkit/shared");
|
|
164
33
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
165
|
-
var ToastContext = (0,
|
|
34
|
+
var ToastContext = (0, import_react.createContext)(void 0);
|
|
166
35
|
function useToast() {
|
|
167
|
-
const context = (0,
|
|
36
|
+
const context = (0, import_react.useContext)(ToastContext);
|
|
168
37
|
if (!context) {
|
|
169
38
|
throw new Error("useToast must be used within a ToastProvider");
|
|
170
39
|
}
|
|
@@ -174,8 +43,8 @@ function useToast() {
|
|
|
174
43
|
// src/components/CopilotListeners.tsx
|
|
175
44
|
var import_shared3 = require("@copilotkit/shared");
|
|
176
45
|
var usePredictStateSubscription = (agent) => {
|
|
177
|
-
const predictStateToolsRef = (0,
|
|
178
|
-
const getSubscriber = (0,
|
|
46
|
+
const predictStateToolsRef = (0, import_react2.useRef)([]);
|
|
47
|
+
const getSubscriber = (0, import_react2.useCallback)(
|
|
179
48
|
(agent2) => ({
|
|
180
49
|
onCustomEvent: ({ event }) => {
|
|
181
50
|
if (event.name === "PredictState") {
|
|
@@ -195,7 +64,7 @@ var usePredictStateSubscription = (agent) => {
|
|
|
195
64
|
}),
|
|
196
65
|
[]
|
|
197
66
|
);
|
|
198
|
-
(0,
|
|
67
|
+
(0, import_react2.useEffect)(() => {
|
|
199
68
|
if (!agent)
|
|
200
69
|
return;
|
|
201
70
|
const subscriber = getSubscriber(agent);
|
|
@@ -206,15 +75,13 @@ var usePredictStateSubscription = (agent) => {
|
|
|
206
75
|
}, [agent, getSubscriber]);
|
|
207
76
|
};
|
|
208
77
|
function CopilotListeners() {
|
|
209
|
-
|
|
210
|
-
const
|
|
211
|
-
const
|
|
212
|
-
const existingConfig = (0, import_react4.useCopilotChatConfiguration)();
|
|
213
|
-
const resolvedAgentId = (_b = (_a = agentSession == null ? void 0 : agentSession.agentName) != null ? _a : existingConfig == null ? void 0 : existingConfig.agentId) != null ? _b : "default";
|
|
78
|
+
const { copilotkit } = (0, import_react3.useCopilotKit)();
|
|
79
|
+
const existingConfig = (0, import_react3.useCopilotChatConfiguration)();
|
|
80
|
+
const resolvedAgentId = existingConfig == null ? void 0 : existingConfig.agentId;
|
|
214
81
|
const { setBannerError } = useToast();
|
|
215
|
-
const { agent } = (0,
|
|
82
|
+
const { agent } = (0, import_react3.useAgent)({ agentId: resolvedAgentId });
|
|
216
83
|
usePredictStateSubscription(agent);
|
|
217
|
-
(0,
|
|
84
|
+
(0, import_react2.useEffect)(() => {
|
|
218
85
|
const subscriber = {
|
|
219
86
|
onError: ({ error }) => {
|
|
220
87
|
setBannerError(new import_shared3.CopilotKitLowLevelError({ error, message: error.message }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/CopilotListeners.tsx","../../src/context/copilot-context.tsx","../../src/components/toast/toast-provider.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { useAgent, useCopilotChatConfiguration, useCopilotKit } from \"@copilotkitnext/react\";\nimport { CopilotKitError, parseJson } from \"@copilotkit/shared\";\nimport { useCopilotContext } from \"../context\";\nimport { AbstractAgent, AgentSubscriber, AGUIConnectNotImplementedError } from \"@ag-ui/client\";\nimport { useErrorToast } from \"./error-boundary/error-utils\";\nimport { CopilotKitCoreSubscriber } from \"@copilotkitnext/core\";\nimport { useToast } from \"./toast/toast-provider\";\nimport { CopilotKitLowLevelError } from \"@copilotkit/shared\";\n\nconst usePredictStateSubscription = (agent?: AbstractAgent) => {\n const predictStateToolsRef = useRef<\n {\n tool: string;\n state_key: string;\n tool_argument: string;\n }[]\n >([]);\n\n const getSubscriber = useCallback(\n (agent: AbstractAgent): AgentSubscriber => ({\n onCustomEvent: ({ event }) => {\n if (event.name === \"PredictState\") {\n predictStateToolsRef.current = event.value;\n }\n },\n onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {\n predictStateToolsRef.current.forEach((t) => {\n if (t?.tool !== toolCallName) return;\n\n const emittedState =\n typeof partialToolCallArgs === \"string\"\n ? parseJson(partialToolCallArgs as unknown as string, partialToolCallArgs)\n : partialToolCallArgs;\n\n agent.setState({\n [t.state_key]: emittedState[t.state_key],\n });\n });\n },\n }),\n [],\n );\n\n useEffect(() => {\n if (!agent) return;\n\n const subscriber = getSubscriber(agent);\n const { unsubscribe } = agent.subscribe(subscriber);\n return () => {\n unsubscribe();\n };\n }, [agent, getSubscriber]);\n};\n\nexport function CopilotListeners() {\n const { copilotkit } = useCopilotKit();\n const { agentSession } = useCopilotContext();\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = agentSession?.agentName ?? existingConfig?.agentId ?? \"default\";\n const { setBannerError } = useToast();\n\n const { agent } = useAgent({ agentId: resolvedAgentId });\n\n usePredictStateSubscription(agent);\n\n useEffect(() => {\n const subscriber: CopilotKitCoreSubscriber = {\n onError: ({ error }) => {\n // @ts-expect-error -- for now, choose a random CPK error type to display the error toast\n setBannerError(new CopilotKitLowLevelError({ error, message: error.message }));\n },\n };\n const subscription = copilotkit.subscribe(subscriber);\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit?.subscribe]);\n\n return null;\n}\n","import {\n CopilotCloudConfig,\n FunctionCallHandler,\n CopilotErrorHandler,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetter,\n QueuedInterruptEvent,\n} from \"../types/interrupt-action\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Optional configuration for connecting to Model Context Protocol (MCP) servers.\n * This is typically derived from the CopilotKitProps and used internally.\n * @experimental\n */\n mcpServers?: Array<{ endpoint: string; apiKey?: string }>;\n}\n\nexport type InChatRenderFunction<TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>> =\n (props: TProps) => string | React.JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | React.JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\nexport type ContextTree = Tree;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // registered actions for component-based rendering\n setRegisteredActions: (actionConfig: any) => string;\n removeRegisteredAction: (actionKey: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean;\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Partial<Pick<ForwardedParametersInput, \"temperature\">>;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n interruptActions: Record<string, LangGraphInterruptRender>;\n setInterruptAction: LangGraphInterruptActionSetter;\n removeInterruptAction: (actionId: string) => void;\n interruptEventQueue: Record<string, QueuedInterruptEvent[]>;\n addInterruptEvent: (queuedEvent: QueuedInterruptEvent) => void;\n removeInterruptEvent: (threadId: string, eventId: string) => void;\n\n /**\n * Optional trace handler for comprehensive debugging and observability.\n */\n onError: CopilotErrorHandler;\n\n // banner error state\n bannerError: CopilotKitError | null;\n setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;\n // Internal error handlers\n // These are used to handle errors that occur during the execution of the chat.\n // They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed\n internalErrorHandlers: Record<string, CopilotErrorHandler>;\n setInternalErrorHandler: (handler: Record<string, CopilotErrorHandler>) => void;\n removeInternalErrorHandler: (id: string) => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n setRegisteredActions: () => \"\",\n removeRegisteredAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n getAllContext: () => [],\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: false,\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n interruptActions: {},\n setInterruptAction: () => {},\n removeInterruptAction: () => {},\n interruptEventQueue: {},\n addInterruptEvent: () => {},\n removeInterruptEvent: () => {},\n onError: () => {},\n bannerError: null,\n setBannerError: () => {},\n internalErrorHandlers: {},\n setInternalErrorHandler: () => {},\n removeInternalErrorHandler: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(null);\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBAAwD;AACxD,IAAAA,gBAAqE;AACrE,IAAAC,iBAA2C;;;ACS3C,mBAAkB;AAuOlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,sBAAsB,MAAM;AAAA,EAC5B,wBAAwB,MAAM;AAAA,EAAC;AAAA,EAE/B,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAAA,EACzE,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,eAAe,MAAM,CAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,wBAAwB,CAAC;AAAA,EACzB,2BAA2B,MAAM,sBAAsB,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C;AAAA,MACH;AAAA,IACF;AAAA,IACA,CAAC;AAAA,EACH;AAEA,+BAAU,MAAM;AACd,QAAI,CAAC;AAAO;AAEZ,UAAM,aAAa,cAAc,KAAK;AACtC,UAAM,EAAE,YAAY,IAAI,MAAM,UAAU,UAAU;AAClD,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,OAAO,aAAa,CAAC;AAC3B;AAEO,SAAS,mBAAmB;AAvDnC;AAwDE,QAAM,EAAE,WAAW,QAAI,6BAAc;AACrC,QAAM,EAAE,aAAa,IAAI,kBAAkB;AAC3C,QAAM,qBAAiB,2CAA4B;AACnD,QAAM,mBAAkB,wDAAc,cAAd,YAA2B,iDAAgB,YAA3C,YAAsD;AAC9E,QAAM,EAAE,eAAe,IAAI,SAAS;AAEpC,QAAM,EAAE,MAAM,QAAI,wBAAS,EAAE,SAAS,gBAAgB,CAAC;AAEvD,8BAA4B,KAAK;AAEjC,+BAAU,MAAM;AACd,UAAM,aAAuC;AAAA,MAC3C,SAAS,CAAC,EAAE,MAAM,MAAM;AAEtB,uBAAe,IAAI,uCAAwB,EAAE,OAAO,SAAS,MAAM,QAAQ,CAAC,CAAC;AAAA,MAC/E;AAAA,IACF;AACA,UAAM,eAAe,WAAW,UAAU,UAAU;AAEpD,WAAO,MAAM;AACX,mBAAa,YAAY;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,yCAAY,SAAS,CAAC;AAE1B,SAAO;AACT;","names":["import_react","import_shared","React","import_react","import_shared","agent"]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/CopilotListeners.tsx","../../src/components/toast/toast-provider.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { useAgent, useCopilotChatConfiguration, useCopilotKit } from \"@copilotkitnext/react\";\nimport { CopilotKitError, parseJson } from \"@copilotkit/shared\";\nimport { useCopilotContext } from \"../context\";\nimport { AbstractAgent, AgentSubscriber, AGUIConnectNotImplementedError } from \"@ag-ui/client\";\nimport { useErrorToast } from \"./error-boundary/error-utils\";\nimport { CopilotKitCoreSubscriber } from \"@copilotkitnext/core\";\nimport { useToast } from \"./toast/toast-provider\";\nimport { CopilotKitLowLevelError } from \"@copilotkit/shared\";\n\nconst usePredictStateSubscription = (agent?: AbstractAgent) => {\n const predictStateToolsRef = useRef<\n {\n tool: string;\n state_key: string;\n tool_argument: string;\n }[]\n >([]);\n\n const getSubscriber = useCallback(\n (agent: AbstractAgent): AgentSubscriber => ({\n onCustomEvent: ({ event }) => {\n if (event.name === \"PredictState\") {\n predictStateToolsRef.current = event.value;\n }\n },\n onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {\n predictStateToolsRef.current.forEach((t) => {\n if (t?.tool !== toolCallName) return;\n\n const emittedState =\n typeof partialToolCallArgs === \"string\"\n ? parseJson(partialToolCallArgs as unknown as string, partialToolCallArgs)\n : partialToolCallArgs;\n\n agent.setState({\n [t.state_key]: emittedState[t.state_key],\n });\n });\n },\n }),\n [],\n );\n\n useEffect(() => {\n if (!agent) return;\n\n const subscriber = getSubscriber(agent);\n const { unsubscribe } = agent.subscribe(subscriber);\n return () => {\n unsubscribe();\n };\n }, [agent, getSubscriber]);\n};\n\nexport function CopilotListeners() {\n const { copilotkit } = useCopilotKit();\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId;\n const { setBannerError } = useToast();\n\n const { agent } = useAgent({ agentId: resolvedAgentId });\n\n usePredictStateSubscription(agent);\n\n useEffect(() => {\n const subscriber: CopilotKitCoreSubscriber = {\n onError: ({ error }) => {\n // @ts-expect-error -- for now, choose a random CPK error type to display the error toast\n setBannerError(new CopilotKitLowLevelError({ error, message: error.message }));\n },\n };\n const subscription = copilotkit.subscribe(subscriber);\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit?.subscribe]);\n\n return null;\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(null);\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AA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B,iDAAgB;AACxC,QAAM,EAAE,eAAe,IAAI,SAAS;AAEpC,QAAM,EAAE,MAAM,QAAI,wBAAS,EAAE,SAAS,gBAAgB,CAAC;AAEvD,8BAA4B,KAAK;AAEjC,+BAAU,MAAM;AACd,UAAM,aAAuC;AAAA,MAC3C,SAAS,CAAC,EAAE,MAAM,MAAM;AAEtB,uBAAe,IAAI,uCAAwB,EAAE,OAAO,SAAS,MAAM,QAAQ,CAAC,CAAC;AAAA,MAC/E;AAAA,IACF;AACA,UAAM,eAAe,WAAW,UAAU,UAAU;AAEpD,WAAO,MAAM;AACX,mBAAa,YAAY;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,yCAAY,SAAS,CAAC;AAE1B,SAAO;AACT;","names":["import_react","import_shared","import_shared","agent"]}
|
|
@@ -1,12 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CopilotListeners
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-NB2FKV2V.mjs";
|
|
5
|
-
import "../chunk-F555TVE4.mjs";
|
|
3
|
+
} from "../chunk-WF65O6HX.mjs";
|
|
6
4
|
import "../chunk-EFL5OBKN.mjs";
|
|
7
|
-
import "../chunk-FDOMAPJY.mjs";
|
|
8
|
-
import "../chunk-WVLHXIFP.mjs";
|
|
9
|
-
import "../chunk-DMLQZG75.mjs";
|
|
10
5
|
import "../chunk-SKC7AJIV.mjs";
|
|
11
6
|
export {
|
|
12
7
|
CopilotListeners
|