@copilotkit/react-core 1.50.1-next.0 → 1.50.1-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/{chunk-BTZ3TJVX.mjs → chunk-4RRMC7L2.mjs} +4 -4
- package/dist/{chunk-JZN7YOPM.mjs → chunk-4YZA2BZC.mjs} +13 -13
- package/dist/{chunk-ZE4JVTEP.mjs → chunk-53K6WNJG.mjs} +2 -2
- package/dist/{chunk-U2ZRVVKT.mjs → chunk-BUSWSDYO.mjs} +2 -2
- package/dist/{chunk-T2VBHAAP.mjs → chunk-CDUIA2WM.mjs} +11 -3
- package/dist/chunk-CDUIA2WM.mjs.map +1 -0
- package/dist/{chunk-4HRUQH6U.mjs → chunk-E7SE25ZU.mjs} +2 -2
- package/dist/{chunk-5J7RRLRO.mjs → chunk-FQFXYAV7.mjs} +2 -2
- package/dist/{chunk-EG56H77V.mjs → chunk-GPEJNVE5.mjs} +2 -2
- package/dist/{chunk-7HI6VLJJ.mjs → chunk-HE22TZMF.mjs} +4 -4
- package/dist/{chunk-FESRCHUE.mjs → chunk-LCZZ7YGZ.mjs} +2 -2
- package/dist/{chunk-SNON4QA6.mjs → chunk-LHERIF3L.mjs} +4 -4
- package/dist/{chunk-LDEWO5XH.mjs → chunk-LSHFN2Y5.mjs} +28 -7
- package/dist/chunk-LSHFN2Y5.mjs.map +1 -0
- package/dist/{chunk-IUNU4CUG.mjs → chunk-YTQHRJUA.mjs} +4 -4
- package/dist/components/copilot-provider/copilot-messages.mjs +2 -2
- package/dist/components/copilot-provider/copilotkit.mjs +7 -7
- package/dist/components/copilot-provider/index.mjs +7 -7
- package/dist/components/error-boundary/error-boundary.mjs +2 -2
- package/dist/components/index.mjs +7 -7
- package/dist/context/index.mjs +5 -5
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.js +36 -7
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +14 -14
- package/dist/hooks/use-coagent-state-render-bridge.mjs +1 -1
- package/dist/hooks/use-coagent-state-render.mjs +2 -2
- package/dist/hooks/use-copilot-action.js +9 -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-authenticated-action.js +9 -1
- package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
- package/dist/hooks/use-copilot-authenticated-action.mjs +3 -3
- package/dist/hooks/use-copilot-chat-headless_c.js +27 -6
- package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
- package/dist/hooks/use-copilot-chat-headless_c.mjs +5 -5
- package/dist/hooks/use-copilot-chat.js +27 -6
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +5 -5
- package/dist/hooks/use-copilot-chat_internal.d.ts +24 -2
- package/dist/hooks/use-copilot-chat_internal.js +27 -6
- package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
- package/dist/hooks/use-copilot-chat_internal.mjs +4 -4
- package/dist/hooks/use-default-tool.js +9 -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 +9 -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.mjs +1 -1
- package/dist/hooks/use-langgraph-interrupt.mjs +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +36 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +39 -39
- package/dist/lib/copilot-task.mjs +8 -8
- package/dist/lib/index.mjs +8 -8
- package/package.json +3 -3
- package/src/hooks/index.ts +6 -1
- package/src/hooks/use-copilot-chat_internal.ts +59 -3
- package/src/hooks/use-frontend-tool.ts +13 -2
- package/dist/chunk-LDEWO5XH.mjs.map +0 -1
- package/dist/chunk-T2VBHAAP.mjs.map +0 -1
- /package/dist/{chunk-BTZ3TJVX.mjs.map → chunk-4RRMC7L2.mjs.map} +0 -0
- /package/dist/{chunk-JZN7YOPM.mjs.map → chunk-4YZA2BZC.mjs.map} +0 -0
- /package/dist/{chunk-ZE4JVTEP.mjs.map → chunk-53K6WNJG.mjs.map} +0 -0
- /package/dist/{chunk-U2ZRVVKT.mjs.map → chunk-BUSWSDYO.mjs.map} +0 -0
- /package/dist/{chunk-4HRUQH6U.mjs.map → chunk-E7SE25ZU.mjs.map} +0 -0
- /package/dist/{chunk-5J7RRLRO.mjs.map → chunk-FQFXYAV7.mjs.map} +0 -0
- /package/dist/{chunk-EG56H77V.mjs.map → chunk-GPEJNVE5.mjs.map} +0 -0
- /package/dist/{chunk-7HI6VLJJ.mjs.map → chunk-HE22TZMF.mjs.map} +0 -0
- /package/dist/{chunk-FESRCHUE.mjs.map → chunk-LCZZ7YGZ.mjs.map} +0 -0
- /package/dist/{chunk-SNON4QA6.mjs.map → chunk-LHERIF3L.mjs.map} +0 -0
- /package/dist/{chunk-IUNU4CUG.mjs.map → chunk-YTQHRJUA.mjs.map} +0 -0
package/dist/hooks/index.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import "../chunk-A6NKSGH3.mjs";
|
|
2
2
|
import {
|
|
3
3
|
useDefaultTool
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-BUSWSDYO.mjs";
|
|
5
5
|
import {
|
|
6
6
|
useLangGraphInterrupt
|
|
7
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-4RRMC7L2.mjs";
|
|
8
8
|
import {
|
|
9
9
|
useMakeCopilotDocumentReadable
|
|
10
10
|
} from "../chunk-7IBF6RBW.mjs";
|
|
@@ -13,19 +13,19 @@ import {
|
|
|
13
13
|
} from "../chunk-ABWT4DRT.mjs";
|
|
14
14
|
import {
|
|
15
15
|
useCopilotAuthenticatedAction_c
|
|
16
|
-
} from "../chunk-
|
|
16
|
+
} from "../chunk-E7SE25ZU.mjs";
|
|
17
17
|
import {
|
|
18
18
|
useCopilotChatHeadless_c
|
|
19
|
-
} from "../chunk-
|
|
19
|
+
} from "../chunk-FQFXYAV7.mjs";
|
|
20
20
|
import {
|
|
21
21
|
useCopilotChatSuggestions
|
|
22
22
|
} from "../chunk-XDFVCQD3.mjs";
|
|
23
23
|
import {
|
|
24
24
|
useCopilotChat
|
|
25
|
-
} from "../chunk-
|
|
25
|
+
} from "../chunk-53K6WNJG.mjs";
|
|
26
26
|
import {
|
|
27
27
|
useCopilotChatInternal
|
|
28
|
-
} from "../chunk-
|
|
28
|
+
} from "../chunk-LSHFN2Y5.mjs";
|
|
29
29
|
import {
|
|
30
30
|
useLangGraphInterruptRender
|
|
31
31
|
} from "../chunk-VV56AVPB.mjs";
|
|
@@ -38,34 +38,34 @@ import {
|
|
|
38
38
|
import {
|
|
39
39
|
useCopilotRuntimeClient
|
|
40
40
|
} from "../chunk-6ESSSQ7Q.mjs";
|
|
41
|
-
import "../chunk-6PUNP7CD.mjs";
|
|
42
|
-
import "../chunk-O7ARI5CV.mjs";
|
|
43
|
-
import "../chunk-QNUAXSDP.mjs";
|
|
44
41
|
import {
|
|
45
42
|
useCoAgentStateRender
|
|
46
|
-
} from "../chunk-
|
|
43
|
+
} from "../chunk-YTQHRJUA.mjs";
|
|
47
44
|
import {
|
|
48
45
|
useCoAgent
|
|
49
46
|
} from "../chunk-ZYTXB6HH.mjs";
|
|
50
47
|
import "../chunk-I76HKHPJ.mjs";
|
|
51
48
|
import {
|
|
52
49
|
useCopilotAction
|
|
53
|
-
} from "../chunk-
|
|
50
|
+
} from "../chunk-GPEJNVE5.mjs";
|
|
54
51
|
import {
|
|
55
52
|
useRenderToolCall
|
|
56
53
|
} from "../chunk-NBK4KBLX.mjs";
|
|
57
54
|
import {
|
|
58
55
|
useFrontendTool
|
|
59
|
-
} from "../chunk-
|
|
56
|
+
} from "../chunk-CDUIA2WM.mjs";
|
|
60
57
|
import {
|
|
61
58
|
useHumanInTheLoop
|
|
62
59
|
} from "../chunk-7DTB7S5V.mjs";
|
|
60
|
+
import "../chunk-6PUNP7CD.mjs";
|
|
61
|
+
import "../chunk-O7ARI5CV.mjs";
|
|
62
|
+
import "../chunk-QNUAXSDP.mjs";
|
|
63
63
|
import "../chunk-NB2FKV2V.mjs";
|
|
64
|
+
import "../chunk-F555TVE4.mjs";
|
|
65
|
+
import "../chunk-EFL5OBKN.mjs";
|
|
64
66
|
import "../chunk-FDOMAPJY.mjs";
|
|
65
67
|
import "../chunk-AFNWX62Q.mjs";
|
|
66
68
|
import "../chunk-DMLQZG75.mjs";
|
|
67
|
-
import "../chunk-F555TVE4.mjs";
|
|
68
|
-
import "../chunk-EFL5OBKN.mjs";
|
|
69
69
|
import "../chunk-SKC7AJIV.mjs";
|
|
70
70
|
export {
|
|
71
71
|
useCoAgent,
|
|
@@ -3,10 +3,10 @@ import {
|
|
|
3
3
|
useCoagentStateRenderBridge
|
|
4
4
|
} from "../chunk-QNUAXSDP.mjs";
|
|
5
5
|
import "../chunk-NB2FKV2V.mjs";
|
|
6
|
+
import "../chunk-F555TVE4.mjs";
|
|
6
7
|
import "../chunk-FDOMAPJY.mjs";
|
|
7
8
|
import "../chunk-AFNWX62Q.mjs";
|
|
8
9
|
import "../chunk-DMLQZG75.mjs";
|
|
9
|
-
import "../chunk-F555TVE4.mjs";
|
|
10
10
|
import "../chunk-SKC7AJIV.mjs";
|
|
11
11
|
export {
|
|
12
12
|
CoAgentStateRenderBridge,
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCoAgentStateRender
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-YTQHRJUA.mjs";
|
|
4
|
+
import "../chunk-EFL5OBKN.mjs";
|
|
4
5
|
import "../chunk-FDOMAPJY.mjs";
|
|
5
6
|
import "../chunk-AFNWX62Q.mjs";
|
|
6
|
-
import "../chunk-EFL5OBKN.mjs";
|
|
7
7
|
import "../chunk-SKC7AJIV.mjs";
|
|
8
8
|
export {
|
|
9
9
|
useCoAgentStateRender
|
|
@@ -95,11 +95,19 @@ function useFrontendTool(tool, dependencies) {
|
|
|
95
95
|
return rendered != null ? rendered : null;
|
|
96
96
|
};
|
|
97
97
|
})();
|
|
98
|
+
const handlerRef = (0, import_react.useRef)(tool.handler);
|
|
99
|
+
(0, import_react.useEffect)(() => {
|
|
100
|
+
handlerRef.current = tool.handler;
|
|
101
|
+
}, [tool.handler, ...dependencies != null ? dependencies : []]);
|
|
102
|
+
const normalizedHandler = tool.handler ? (args) => {
|
|
103
|
+
var _a;
|
|
104
|
+
return (_a = handlerRef.current) == null ? void 0 : _a.call(handlerRef, args);
|
|
105
|
+
} : void 0;
|
|
98
106
|
(0, import_react2.useFrontendTool)({
|
|
99
107
|
name,
|
|
100
108
|
description,
|
|
101
109
|
parameters: zodParameters,
|
|
102
|
-
handler:
|
|
110
|
+
handler: normalizedHandler,
|
|
103
111
|
followUp,
|
|
104
112
|
render: normalizedRender
|
|
105
113
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-copilot-action.ts","../../src/hooks/use-frontend-tool.ts","../../src/hooks/use-render-tool-call.ts","../../src/hooks/use-human-in-the-loop.ts"],"sourcesContent":["/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { Parameter } from \"@copilotkit/shared\";\nimport { CatchAllFrontendAction, FrontendAction } from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport { useRenderToolCall, UseRenderToolCallArgs } from \"./use-render-tool-call\";\nimport { useHumanInTheLoop, UseHumanInTheLoopArgs } from \"./use-human-in-the-loop\";\nimport { useCopilotContext } from \"../context\";\n\n// Helper to determine which component and action config to use\nfunction getActionConfig<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n) {\n if (action.name === \"*\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n\n if (\"renderAndWaitForResponse\" in action || \"renderAndWait\" in action) {\n let render = action.render;\n if (!render && \"renderAndWaitForResponse\" in action) {\n // @ts-expect-error -- renderAndWaitForResponse is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWaitForResponse;\n }\n if (!render && \"renderAndWait\" in action) {\n // @ts-expect-error -- renderAndWait is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWait;\n }\n\n return {\n type: \"hitl\" as const,\n action: { ...action, render } as UseHumanInTheLoopArgs<T>,\n };\n }\n\n if (\"available\" in action) {\n if (action.available === \"enabled\" || action.available === \"remote\") {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n if (action.available === \"frontend\" || action.available === \"disabled\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n }\n\n if (\"handler\" in action) {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n\n throw new Error(\"Invalid action configuration\");\n}\n\n/**\n * useCopilotAction is a legacy hook maintained for backwards compatibility.\n *\n * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),\n * we use a registration pattern:\n * 1. This hook registers the action configuration with the CopilotContext\n * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper\n * 3. React properly manages hook state since components are rendered, not conditionally called\n *\n * This allows action types to change between renders without corrupting React's hook state.\n */\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const [initialActionConfig] = useState(getActionConfig(action));\n const currentActionConfig = getActionConfig(action);\n\n /**\n * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because\n * React maintains the call stack for hooks like useEffect or useState, and conditionally\n * calling a hook would result in inconsistent call stacks between renders.\n *\n * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the\n * supplied parameters. In order to avoid breaking React's call stack tracking, while\n * breaking the Rule of Hooks, we use a ref to store the initial action configuration\n * and throw an error if the _configuration_ changes such that we would call a different hook.\n */\n if (initialActionConfig.type !== currentActionConfig.type) {\n throw new Error(\"Action configuration changed between renders\");\n }\n\n switch (currentActionConfig.type) {\n case \"render\":\n return useRenderToolCall(currentActionConfig.action, dependencies);\n case \"hitl\":\n return useHumanInTheLoop(currentActionConfig.action, dependencies);\n case \"frontend\":\n return useFrontendTool(currentActionConfig.action, dependencies);\n default:\n throw new Error(\"Invalid action configuration\");\n }\n}\n","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","import {\n ActionRenderProps,\n ActionRenderPropsNoArgs,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types\";\nimport { Parameter, getZodParameters } from \"@copilotkit/shared\";\nimport React, { useEffect, useRef } from \"react\";\nimport { defineToolCallRenderer, useCopilotKit } from \"@copilotkitnext/react\";\nimport { parseJson } from \"@copilotkit/shared\";\n\ntype ToolCallRendererDefinition = Parameters<typeof defineToolCallRenderer>[0];\n\nexport type UseRenderToolCallArgs<T extends Parameter[] | [] = []> = Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\"\n> & {\n available?: \"disabled\" | \"enabled\";\n render: T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => React.ReactElement\n : (props: ActionRenderProps<T>) => React.ReactElement;\n};\n\nexport function useRenderToolCall<const T extends Parameter[] | [] = []>(\n tool: UseRenderToolCallArgs<T>,\n dependencies?: any[],\n) {\n const { copilotkit } = useCopilotKit();\n\n // Track whether we've already added this renderer to avoid duplicates\n const hasAddedRef = useRef(false);\n\n useEffect(() => {\n const { name, parameters, render } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderToolCall =\n name === \"*\"\n ? defineToolCallRenderer({\n name: \"*\",\n render: ((args) => {\n return render({\n ...args,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n })\n : defineToolCallRenderer({\n name,\n args: zodParameters,\n render: ((args) => {\n return render({\n ...args,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n });\n\n // Remove any existing renderer with the same name\n const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);\n if (existingIndex !== -1) {\n copilotkit.renderToolCalls.splice(existingIndex, 1);\n }\n\n // Add the new renderer\n copilotkit.renderToolCalls.push(renderToolCall);\n hasAddedRef.current = true;\n\n // Cleanup: remove this renderer when the component unmounts or tool changes\n return () => {\n if (hasAddedRef.current) {\n const index = copilotkit.renderToolCalls.findIndex((r) => r.name === name);\n if (index !== -1) {\n copilotkit.renderToolCalls.splice(index, 1);\n }\n hasAddedRef.current = false;\n }\n };\n }, [tool, ...(dependencies ?? [])]);\n}\n","import { ActionRenderProps, ActionRenderPropsWait, FrontendAction } from \"../types\";\nimport {\n CopilotKitError,\n CopilotKitErrorCode,\n MappedParameterTypes,\n Parameter,\n getZodParameters,\n parseJson,\n} from \"@copilotkit/shared\";\nimport { useHumanInTheLoop as useHumanInTheLoopVNext } from \"@copilotkitnext/react\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport React, { ComponentType, FunctionComponent, useEffect, useRef } from \"react\";\n\ntype HumanInTheLoopOptions = Parameters<typeof useHumanInTheLoopVNext>[0];\ntype HumanInTheLoopRender = HumanInTheLoopOptions[\"render\"];\ntype HumanInTheLoopRenderArgs = HumanInTheLoopRender extends (props: infer P) => any ? P : never;\n\nexport type UseHumanInTheLoopArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n render: FrontendAction<T>[\"renderAndWaitForResponse\"];\n followUp?: FrontendAction<T>[\"followUp\"];\n} & Pick<FrontendAction<T>, \"name\" | \"description\" | \"parameters\">;\n\ntype HitlRendererArgs =\n | {\n name: string;\n description: string;\n args: Partial<Record<string, unknown>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n respond: undefined;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Executing;\n result: undefined;\n respond: (result: unknown) => Promise<void>;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Complete;\n result: string;\n respond: undefined;\n };\ntype HitlRenderer = FunctionComponent<HitlRendererArgs>;\n\nexport function useHumanInTheLoop<const T extends Parameter[] | [] = []>(\n tool: UseHumanInTheLoopArgs<T>,\n dependencies?: any[],\n) {\n const { render, ...toolRest } = tool;\n const { name, description, parameters, followUp } = toolRest;\n const zodParameters = getZodParameters(parameters);\n const renderRef = useRef<HitlRenderer | null>(null);\n\n useEffect(() => {\n renderRef.current = (args: HitlRendererArgs): React.ReactElement | null => {\n if (typeof render === \"string\") {\n return React.createElement(React.Fragment, null, render);\n }\n\n if (!render) {\n return null;\n }\n\n const renderProps: ActionRenderPropsWait<T> = (() => {\n const mappedArgs = args.args as unknown as MappedParameterTypes<T>;\n\n switch (args.status) {\n case ToolCallStatus.InProgress:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: undefined,\n };\n case ToolCallStatus.Executing:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: () => {},\n };\n case ToolCallStatus.Complete:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n handler: undefined,\n };\n default:\n throw new CopilotKitError({\n code: CopilotKitErrorCode.UNKNOWN,\n message: `Invalid tool call status: ${(args as unknown as { status: string }).status}`,\n });\n }\n })();\n\n const rendered = render(renderProps);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n };\n }, [render, ...(dependencies ?? [])]);\n\n useHumanInTheLoopVNext({\n name,\n description,\n followUp,\n parameters: zodParameters,\n render: ((args: HumanInTheLoopRenderArgs) =>\n renderRef.current?.(args as HitlRendererArgs) ?? null) as HumanInTheLoopOptions[\"render\"],\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoIA,IAAAA,gBAA4C;;;ACpI5C,mBAAkB;AAElB,oBAAkE;AAClE,IAAAC,iBAA0B;AAE1B,IAAAC,gBAGO;AA8BA,SAAS,gBACd,MACA,cACA;AACA,QAAM,EAAE,MAAM,aAAa,YAAY,QAAQ,SAAS,IAAI;AAC5D,QAAM,oBAAgB,gCAAiB,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,aAAAC,QAAM;AAAA,QACJ,aAAAA,QAAM;AAAA,QACN;AAAA,QACA;AAAA,MACF;AAAA,IACJ;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,IAClB;AAEA,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ,iCAAK,SAAL,EAAa,OAAO;AAAA,IAC9B;AAAA,EACF;AAEA,MAAI,eAAe,QAAQ;AACzB,QAAI,OAAO,cAAc,aAAa,OAAO,cAAc,UAAU;AACnE,aAAO;AAAA,QACL,MAAM;AAAA,QACN;AAAA,MACF;AAAA,IACF;AACA,QAAI,OAAO,cAAc,cAAc,OAAO,cAAc,YAAY;AACtE,aAAO;AAAA,QACL,MAAM;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,MAAI,aAAa,QAAQ;AACvB,WAAO;AAAA,MACL,MAAM;AAAA,MACN;AAAA,IACF;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,8BAA8B;AAChD;AAaO,SAAS,iBACd,QACA,cACM;AACN,QAAM,CAAC,mBAAmB,QAAI,wBAAS,gBAAgB,MAAM,CAAC;AAC9D,QAAM,sBAAsB,gBAAgB,MAAM;AAYlD,MAAI,oBAAoB,SAAS,oBAAoB,MAAM;AACzD,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AAEA,UAAQ,oBAAoB,MAAM;AAAA,IAChC,KAAK;AACH,aAAO,kBAAkB,oBAAoB,QAAQ,YAAY;AAAA,IACnE,KAAK;AACH,aAAO,kBAAkB,oBAAoB,QAAQ,YAAY;AAAA,IACnE,KAAK;AACH,aAAO,gBAAgB,oBAAoB,QAAQ,YAAY;AAAA,IACjE;AACE,YAAM,IAAI,MAAM,8BAA8B;AAAA,EAClD;AACF;","names":["import_react","import_shared","import_react","React","useFrontendToolVNext","import_shared","import_react","import_shared","import_react","React","useHumanInTheLoopVNext","_a"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/use-copilot-action.ts","../../src/hooks/use-frontend-tool.ts","../../src/hooks/use-render-tool-call.ts","../../src/hooks/use-human-in-the-loop.ts"],"sourcesContent":["/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { Parameter } from \"@copilotkit/shared\";\nimport { CatchAllFrontendAction, FrontendAction } from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport { useRenderToolCall, UseRenderToolCallArgs } from \"./use-render-tool-call\";\nimport { useHumanInTheLoop, UseHumanInTheLoopArgs } from \"./use-human-in-the-loop\";\nimport { useCopilotContext } from \"../context\";\n\n// Helper to determine which component and action config to use\nfunction getActionConfig<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n) {\n if (action.name === \"*\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n\n if (\"renderAndWaitForResponse\" in action || \"renderAndWait\" in action) {\n let render = action.render;\n if (!render && \"renderAndWaitForResponse\" in action) {\n // @ts-expect-error -- renderAndWaitForResponse is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWaitForResponse;\n }\n if (!render && \"renderAndWait\" in action) {\n // @ts-expect-error -- renderAndWait is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWait;\n }\n\n return {\n type: \"hitl\" as const,\n action: { ...action, render } as UseHumanInTheLoopArgs<T>,\n };\n }\n\n if (\"available\" in action) {\n if (action.available === \"enabled\" || action.available === \"remote\") {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n if (action.available === \"frontend\" || action.available === \"disabled\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n }\n\n if (\"handler\" in action) {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n\n throw new Error(\"Invalid action configuration\");\n}\n\n/**\n * useCopilotAction is a legacy hook maintained for backwards compatibility.\n *\n * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),\n * we use a registration pattern:\n * 1. This hook registers the action configuration with the CopilotContext\n * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper\n * 3. React properly manages hook state since components are rendered, not conditionally called\n *\n * This allows action types to change between renders without corrupting React's hook state.\n */\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const [initialActionConfig] = useState(getActionConfig(action));\n const currentActionConfig = getActionConfig(action);\n\n /**\n * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because\n * React maintains the call stack for hooks like useEffect or useState, and conditionally\n * calling a hook would result in inconsistent call stacks between renders.\n *\n * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the\n * supplied parameters. In order to avoid breaking React's call stack tracking, while\n * breaking the Rule of Hooks, we use a ref to store the initial action configuration\n * and throw an error if the _configuration_ changes such that we would call a different hook.\n */\n if (initialActionConfig.type !== currentActionConfig.type) {\n throw new Error(\"Action configuration changed between renders\");\n }\n\n switch (currentActionConfig.type) {\n case \"render\":\n return useRenderToolCall(currentActionConfig.action, dependencies);\n case \"hitl\":\n return useHumanInTheLoop(currentActionConfig.action, dependencies);\n case \"frontend\":\n return useFrontendTool(currentActionConfig.action, dependencies);\n default:\n throw new Error(\"Invalid action configuration\");\n }\n}\n","import React, { useEffect, useRef } 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 // Handler ref to avoid stale closures\n const handlerRef = useRef<typeof tool.handler>(tool.handler);\n\n useEffect(() => {\n handlerRef.current = tool.handler;\n }, [tool.handler, ...(dependencies ?? [])]);\n\n const normalizedHandler = tool.handler\n ? (args: MappedParameterTypes<T>) => handlerRef.current?.(args)\n : undefined;\n\n useFrontendToolVNext<MappedParameterTypes<T>>({\n name,\n description,\n parameters: zodParameters,\n handler: normalizedHandler,\n followUp,\n render: normalizedRender,\n });\n}\n","import {\n ActionRenderProps,\n ActionRenderPropsNoArgs,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types\";\nimport { Parameter, getZodParameters } from \"@copilotkit/shared\";\nimport React, { useEffect, useRef } from \"react\";\nimport { defineToolCallRenderer, useCopilotKit } from \"@copilotkitnext/react\";\nimport { parseJson } from \"@copilotkit/shared\";\n\ntype ToolCallRendererDefinition = Parameters<typeof defineToolCallRenderer>[0];\n\nexport type UseRenderToolCallArgs<T extends Parameter[] | [] = []> = Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\"\n> & {\n available?: \"disabled\" | \"enabled\";\n render: T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => React.ReactElement\n : (props: ActionRenderProps<T>) => React.ReactElement;\n};\n\nexport function useRenderToolCall<const T extends Parameter[] | [] = []>(\n tool: UseRenderToolCallArgs<T>,\n dependencies?: any[],\n) {\n const { copilotkit } = useCopilotKit();\n\n // Track whether we've already added this renderer to avoid duplicates\n const hasAddedRef = useRef(false);\n\n useEffect(() => {\n const { name, parameters, render } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderToolCall =\n name === \"*\"\n ? defineToolCallRenderer({\n name: \"*\",\n render: ((args) => {\n return render({\n ...args,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n })\n : defineToolCallRenderer({\n name,\n args: zodParameters,\n render: ((args) => {\n return render({\n ...args,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n });\n\n // Remove any existing renderer with the same name\n const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);\n if (existingIndex !== -1) {\n copilotkit.renderToolCalls.splice(existingIndex, 1);\n }\n\n // Add the new renderer\n copilotkit.renderToolCalls.push(renderToolCall);\n hasAddedRef.current = true;\n\n // Cleanup: remove this renderer when the component unmounts or tool changes\n return () => {\n if (hasAddedRef.current) {\n const index = copilotkit.renderToolCalls.findIndex((r) => r.name === name);\n if (index !== -1) {\n copilotkit.renderToolCalls.splice(index, 1);\n }\n hasAddedRef.current = false;\n }\n };\n }, [tool, ...(dependencies ?? [])]);\n}\n","import { ActionRenderProps, ActionRenderPropsWait, FrontendAction } from \"../types\";\nimport {\n CopilotKitError,\n CopilotKitErrorCode,\n MappedParameterTypes,\n Parameter,\n getZodParameters,\n parseJson,\n} from \"@copilotkit/shared\";\nimport { useHumanInTheLoop as useHumanInTheLoopVNext } from \"@copilotkitnext/react\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport React, { ComponentType, FunctionComponent, useEffect, useRef } from \"react\";\n\ntype HumanInTheLoopOptions = Parameters<typeof useHumanInTheLoopVNext>[0];\ntype HumanInTheLoopRender = HumanInTheLoopOptions[\"render\"];\ntype HumanInTheLoopRenderArgs = HumanInTheLoopRender extends (props: infer P) => any ? P : never;\n\nexport type UseHumanInTheLoopArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n render: FrontendAction<T>[\"renderAndWaitForResponse\"];\n followUp?: FrontendAction<T>[\"followUp\"];\n} & Pick<FrontendAction<T>, \"name\" | \"description\" | \"parameters\">;\n\ntype HitlRendererArgs =\n | {\n name: string;\n description: string;\n args: Partial<Record<string, unknown>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n respond: undefined;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Executing;\n result: undefined;\n respond: (result: unknown) => Promise<void>;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Complete;\n result: string;\n respond: undefined;\n };\ntype HitlRenderer = FunctionComponent<HitlRendererArgs>;\n\nexport function useHumanInTheLoop<const T extends Parameter[] | [] = []>(\n tool: UseHumanInTheLoopArgs<T>,\n dependencies?: any[],\n) {\n const { render, ...toolRest } = tool;\n const { name, description, parameters, followUp } = toolRest;\n const zodParameters = getZodParameters(parameters);\n const renderRef = useRef<HitlRenderer | null>(null);\n\n useEffect(() => {\n renderRef.current = (args: HitlRendererArgs): React.ReactElement | null => {\n if (typeof render === \"string\") {\n return React.createElement(React.Fragment, null, render);\n }\n\n if (!render) {\n return null;\n }\n\n const renderProps: ActionRenderPropsWait<T> = (() => {\n const mappedArgs = args.args as unknown as MappedParameterTypes<T>;\n\n switch (args.status) {\n case ToolCallStatus.InProgress:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: undefined,\n };\n case ToolCallStatus.Executing:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: () => {},\n };\n case ToolCallStatus.Complete:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n handler: undefined,\n };\n default:\n throw new CopilotKitError({\n code: CopilotKitErrorCode.UNKNOWN,\n message: `Invalid tool call status: ${(args as unknown as { status: string }).status}`,\n });\n }\n })();\n\n const rendered = render(renderProps);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n };\n }, [render, ...(dependencies ?? [])]);\n\n useHumanInTheLoopVNext({\n name,\n description,\n followUp,\n parameters: zodParameters,\n render: ((args: HumanInTheLoopRenderArgs) =>\n renderRef.current?.(args as HitlRenderer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;AACvB,WAAO;AAAA,MACL,MAAM;AAAA,MACN;AAAA,IACF;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,8BAA8B;AAChD;AAaO,SAAS,iBACd,QACA,cACM;AACN,QAAM,CAAC,mBAAmB,QAAI,wBAAS,gBAAgB,MAAM,CAAC;AAC9D,QAAM,sBAAsB,gBAAgB,MAAM;AAYlD,MAAI,oBAAoB,SAAS,oBAAoB,MAAM;AACzD,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AAEA,UAAQ,oBAAoB,MAAM;AAAA,IAChC,KAAK;AACH,aAAO,kBAAkB,oBAAoB,QAAQ,YAAY;AAAA,IACnE,KAAK;AACH,aAAO,kBAAkB,oBAAoB,QAAQ,YAAY;AAAA,IACnE,KAAK;AACH,aAAO,gBAAgB,oBAAoB,QAAQ,YAAY;AAAA,IACjE;AACE,YAAM,IAAI,MAAM,8BAA8B;AAAA,EAClD;AACF;","names":["import_react","import_shared","import_react","React","useFrontendToolVNext","import_shared","import_react","import_shared","import_react","React","useHumanInTheLoopVNext","_a"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCopilotAction
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-GPEJNVE5.mjs";
|
|
4
4
|
import "../chunk-NBK4KBLX.mjs";
|
|
5
|
-
import "../chunk-
|
|
5
|
+
import "../chunk-CDUIA2WM.mjs";
|
|
6
6
|
import "../chunk-7DTB7S5V.mjs";
|
|
7
7
|
import "../chunk-SKC7AJIV.mjs";
|
|
8
8
|
export {
|
|
@@ -219,11 +219,19 @@ function useFrontendTool(tool, dependencies) {
|
|
|
219
219
|
return rendered != null ? rendered : null;
|
|
220
220
|
};
|
|
221
221
|
})();
|
|
222
|
+
const handlerRef = (0, import_react2.useRef)(tool.handler);
|
|
223
|
+
(0, import_react2.useEffect)(() => {
|
|
224
|
+
handlerRef.current = tool.handler;
|
|
225
|
+
}, [tool.handler, ...dependencies != null ? dependencies : []]);
|
|
226
|
+
const normalizedHandler = tool.handler ? (args) => {
|
|
227
|
+
var _a;
|
|
228
|
+
return (_a = handlerRef.current) == null ? void 0 : _a.call(handlerRef, args);
|
|
229
|
+
} : void 0;
|
|
222
230
|
(0, import_react3.useFrontendTool)({
|
|
223
231
|
name,
|
|
224
232
|
description,
|
|
225
233
|
parameters: zodParameters,
|
|
226
|
-
handler:
|
|
234
|
+
handler: normalizedHandler,
|
|
227
235
|
followUp,
|
|
228
236
|
render: normalizedRender
|
|
229
237
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-copilot-authenticated-action.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-copilot-action.ts","../../src/hooks/use-frontend-tool.ts","../../src/hooks/use-render-tool-call.ts","../../src/hooks/use-human-in-the-loop.ts"],"sourcesContent":["import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({ ...prev, [action.name]: authState }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\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 resolveInterruptEvent: (threadId: string, eventId: string, response: 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 resolveInterruptEvent: () => {},\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","/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { Parameter } from \"@copilotkit/shared\";\nimport { CatchAllFrontendAction, FrontendAction } from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport { useRenderToolCall, UseRenderToolCallArgs } from \"./use-render-tool-call\";\nimport { useHumanInTheLoop, UseHumanInTheLoopArgs } from \"./use-human-in-the-loop\";\nimport { useCopilotContext } from \"../context\";\n\n// Helper to determine which component and action config to use\nfunction getActionConfig<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n) {\n if (action.name === \"*\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n\n if (\"renderAndWaitForResponse\" in action || \"renderAndWait\" in action) {\n let render = action.render;\n if (!render && \"renderAndWaitForResponse\" in action) {\n // @ts-expect-error -- renderAndWaitForResponse is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWaitForResponse;\n }\n if (!render && \"renderAndWait\" in action) {\n // @ts-expect-error -- renderAndWait is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWait;\n }\n\n return {\n type: \"hitl\" as const,\n action: { ...action, render } as UseHumanInTheLoopArgs<T>,\n };\n }\n\n if (\"available\" in action) {\n if (action.available === \"enabled\" || action.available === \"remote\") {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n if (action.available === \"frontend\" || action.available === \"disabled\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n }\n\n if (\"handler\" in action) {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n\n throw new Error(\"Invalid action configuration\");\n}\n\n/**\n * useCopilotAction is a legacy hook maintained for backwards compatibility.\n *\n * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),\n * we use a registration pattern:\n * 1. This hook registers the action configuration with the CopilotContext\n * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper\n * 3. React properly manages hook state since components are rendered, not conditionally called\n *\n * This allows action types to change between renders without corrupting React's hook state.\n */\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const [initialActionConfig] = useState(getActionConfig(action));\n const currentActionConfig = getActionConfig(action);\n\n /**\n * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because\n * React maintains the call stack for hooks like useEffect or useState, and conditionally\n * calling a hook would result in inconsistent call stacks between renders.\n *\n * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the\n * supplied parameters. In order to avoid breaking React's call stack tracking, while\n * breaking the Rule of Hooks, we use a ref to store the initial action configuration\n * and throw an error if the _configuration_ changes such that we would call a different hook.\n */\n if (initialActionConfig.type !== currentActionConfig.type) {\n throw new Error(\"Action configuration changed between renders\");\n }\n\n switch (currentActionConfig.type) {\n case \"render\":\n return useRenderToolCall(currentActionConfig.action, dependencies);\n case \"hitl\":\n return useHumanInTheLoop(currentActionConfig.action, dependencies);\n case \"frontend\":\n return useFrontendTool(currentActionConfig.action, dependencies);\n default:\n throw new Error(\"Invalid action configuration\");\n }\n}\n","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","import {\n ActionRenderProps,\n ActionRenderPropsNoArgs,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types\";\nimport { Parameter, getZodParameters } from \"@copilotkit/shared\";\nimport React, { useEffect, useRef } from \"react\";\nimport { defineToolCallRenderer, useCopilotKit } from \"@copilotkitnext/react\";\nimport { parseJson } from \"@copilotkit/shared\";\n\ntype ToolCallRendererDefinition = Parameters<typeof defineToolCallRenderer>[0];\n\nexport type UseRenderToolCallArgs<T extends Parameter[] | [] = []> = Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\"\n> & {\n available?: \"disabled\" | \"enabled\";\n render: T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => React.ReactElement\n : (props: ActionRenderProps<T>) => React.ReactElement;\n};\n\nexport function useRenderToolCall<const T extends Parameter[] | [] = []>(\n tool: UseRenderToolCallArgs<T>,\n dependencies?: any[],\n) {\n const { copilotkit } = useCopilotKit();\n\n // Track whether we've already added this renderer to avoid duplicates\n const hasAddedRef = useRef(false);\n\n useEffect(() => {\n const { name, parameters, render } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderToolCall =\n name === \"*\"\n ? defineToolCallRenderer({\n name: \"*\",\n render: ((args) => {\n return render({\n ...args,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n })\n : defineToolCallRenderer({\n name,\n args: zodParameters,\n render: ((args) => {\n return render({\n ...args,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n });\n\n // Remove any existing renderer with the same name\n const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);\n if (existingIndex !== -1) {\n copilotkit.renderToolCalls.splice(existingIndex, 1);\n }\n\n // Add the new renderer\n copilotkit.renderToolCalls.push(renderToolCall);\n hasAddedRef.current = true;\n\n // Cleanup: remove this renderer when the component unmounts or tool changes\n return () => {\n if (hasAddedRef.current) {\n const index = copilotkit.renderToolCalls.findIndex((r) => r.name === name);\n if (index !== -1) {\n copilotkit.renderToolCalls.splice(index, 1);\n }\n hasAddedRef.current = false;\n }\n };\n }, [tool, ...(dependencies ?? [])]);\n}\n","import { ActionRenderProps, ActionRenderPropsWait, FrontendAction } from \"../types\";\nimport {\n CopilotKitError,\n CopilotKitErrorCode,\n MappedParameterTypes,\n Parameter,\n getZodParameters,\n parseJson,\n} from \"@copilotkit/shared\";\nimport { useHumanInTheLoop as useHumanInTheLoopVNext } from \"@copilotkitnext/react\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport React, { ComponentType, FunctionComponent, useEffect, useRef } from \"react\";\n\ntype HumanInTheLoopOptions = Parameters<typeof useHumanInTheLoopVNext>[0];\ntype HumanInTheLoopRender = HumanInTheLoopOptions[\"render\"];\ntype HumanInTheLoopRenderArgs = HumanInTheLoopRender extends (props: infer P) => any ? P : never;\n\nexport type UseHumanInTheLoopArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n render: FrontendAction<T>[\"renderAndWaitForResponse\"];\n followUp?: FrontendAction<T>[\"followUp\"];\n} & Pick<FrontendAction<T>, \"name\" | \"description\" | \"parameters\">;\n\ntype HitlRendererArgs =\n | {\n name: string;\n description: string;\n args: Partial<Record<string, unknown>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n respond: undefined;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Executing;\n result: undefined;\n respond: (result: unknown) => Promise<void>;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Complete;\n result: string;\n respond: undefined;\n };\ntype HitlRenderer = FunctionComponent<HitlRendererArgs>;\n\nexport function useHumanInTheLoop<const T extends Parameter[] | [] = []>(\n tool: UseHumanInTheLoopArgs<T>,\n dependencies?: any[],\n) {\n const { render, ...toolRest } = tool;\n const { name, description, parameters, followUp } = toolRest;\n const zodParameters = getZodParameters(parameters);\n const renderRef = useRef<HitlRenderer | null>(null);\n\n useEffect(() => {\n renderRef.current = (args: HitlRendererArgs): React.ReactElement | null => {\n if (typeof render === \"string\") {\n return React.createElement(React.Fragment, null, render);\n }\n\n if (!render) {\n return null;\n }\n\n const renderProps: ActionRenderPropsWait<T> = (() => {\n const mappedArgs = args.args as unknown as MappedParameterTypes<T>;\n\n switch (args.status) {\n case ToolCallStatus.InProgress:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: undefined,\n };\n case ToolCallStatus.Executing:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: () => {},\n };\n case ToolCallStatus.Complete:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n handler: undefined,\n };\n default:\n throw new CopilotKitError({\n code: CopilotKitErrorCode.UNKNOWN,\n message: `Invalid tool call status: ${(args as unknown as { status: string }).status}`,\n });\n }\n })();\n\n const rendered = render(renderProps);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n };\n }, [render, ...(dependencies ?? [])]);\n\n useHumanInTheLoopVNext({\n name,\n description,\n followUp,\n parameters: zodParameters,\n render: ((args: HumanInTheLoopRenderArgs) =>\n renderRef.current?.(args as HitlRendererArgs) ?? null) as HumanInTheLoopOptions[\"render\"],\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,IAAAA,gBAA8C;;;ACU9C,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,MAA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C,IAAI;AAE3E,QAAM,oBAAgB;AAAA,IACpB,CAAC,UAA0C;AACzC,UAAI,OAAO,OAAO,WAAW,YAAY;AACvC,eAAO,OAAO,OAAO,KAAK;AAAA,MAC5B;AACA,aAAO,OAAO,UAAU,eAAAC,QAAM,cAAc,sBAAQ;AAAA,IACtD;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AAEA,QAAM,oBAAgB;AAAA,IACpB,CAAC,UAAuE;AACtE,YAAM,kBAAkB,OAAO,OAAO,gBAAgB,CAAC,CAAC,EAAE;AAAA,QACxD,CAAC,UAAU,MAAM,WAAW;AAAA,MAC9B;AAEA,UAAI,CAAC,iBAAiB;AAEpB,yBAAiB,UAAU;AAE3B,gBAAO,6CAAc,mBACjB,eAAAA,QAAM,cAAc,aAAa,iBAAiB;AAAA,UAChD,kBAAkB,CAAC,cAAc;AAC/B,+DAAkB,CAAC,SAAU,iCAAK,OAAL,EAAW,CAAC,OAAO,IAAI,GAAG,UAAU;AACjE,gBAAI,iBAAiB,SAAS;AAC5B,4BAAc,iBAAiB,OAAO;AACtC,+BAAiB,UAAU;AAAA,YAC7B;AAAA,UACF;AAAA,QACF,CAAC,IACD,eAAAA,QAAM,cAAc,sBAAQ;AAAA,MAClC;AAEA,aAAO,cAAc,KAAK;AAAA,IAC5B;AAAA,IACA,CAAC,QAAQ,cAAc,eAAe;AAAA,EACxC;AAEA;AAAA,IACE,iCACK,SADL;AAAA,MAEE,QAAQ;AAAA,IACV;AAAA,IACA;AAAA,EACF;AACF;","names":["import_react","React","import_react","import_react","import_shared","React","useFrontendToolVNext","import_shared","import_react","import_shared","import_react","React","useHumanInTheLoopVNext","_a","import_react","React"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/use-copilot-authenticated-action.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-copilot-action.ts","../../src/hooks/use-frontend-tool.ts","../../src/hooks/use-render-tool-call.ts","../../src/hooks/use-human-in-the-loop.ts"],"sourcesContent":["import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({ ...prev, [action.name]: authState }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\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 resolveInterruptEvent: (threadId: string, eventId: string, response: 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 resolveInterruptEvent: () => {},\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","/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { Parameter } from \"@copilotkit/shared\";\nimport { CatchAllFrontendAction, FrontendAction } from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport { useRenderToolCall, UseRenderToolCallArgs } from \"./use-render-tool-call\";\nimport { useHumanInTheLoop, UseHumanInTheLoopArgs } from \"./use-human-in-the-loop\";\nimport { useCopilotContext } from \"../context\";\n\n// Helper to determine which component and action config to use\nfunction getActionConfig<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n) {\n if (action.name === \"*\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n\n if (\"renderAndWaitForResponse\" in action || \"renderAndWait\" in action) {\n let render = action.render;\n if (!render && \"renderAndWaitForResponse\" in action) {\n // @ts-expect-error -- renderAndWaitForResponse is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWaitForResponse;\n }\n if (!render && \"renderAndWait\" in action) {\n // @ts-expect-error -- renderAndWait is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWait;\n }\n\n return {\n type: \"hitl\" as const,\n action: { ...action, render } as UseHumanInTheLoopArgs<T>,\n };\n }\n\n if (\"available\" in action) {\n if (action.available === \"enabled\" || action.available === \"remote\") {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n if (action.available === \"frontend\" || action.available === \"disabled\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n }\n\n if (\"handler\" in action) {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n\n throw new Error(\"Invalid action configuration\");\n}\n\n/**\n * useCopilotAction is a legacy hook maintained for backwards compatibility.\n *\n * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),\n * we use a registration pattern:\n * 1. This hook registers the action configuration with the CopilotContext\n * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper\n * 3. React properly manages hook state since components are rendered, not conditionally called\n *\n * This allows action types to change between renders without corrupting React's hook state.\n */\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const [initialActionConfig] = useState(getActionConfig(action));\n const currentActionConfig = getActionConfig(action);\n\n /**\n * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because\n * React maintains the call stack for hooks like useEffect or useState, and conditionally\n * calling a hook would result in inconsistent call stacks between renders.\n *\n * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the\n * supplied parameters. In order to avoid breaking React's call stack tracking, while\n * breaking the Rule of Hooks, we use a ref to store the initial action configuration\n * and throw an error if the _configuration_ changes such that we would call a different hook.\n */\n if (initialActionConfig.type !== currentActionConfig.type) {\n throw new Error(\"Action configuration changed between renders\");\n }\n\n switch (currentActionConfig.type) {\n case \"render\":\n return useRenderToolCall(currentActionConfig.action, dependencies);\n case \"hitl\":\n return useHumanInTheLoop(currentActionConfig.action, dependencies);\n case \"frontend\":\n return useFrontendTool(currentActionConfig.action, dependencies);\n default:\n throw new Error(\"Invalid action configuration\");\n }\n}\n","import React, { useEffect, useRef } 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 // Handler ref to avoid stale closures\n const handlerRef = useRef<typeof tool.handler>(tool.handler);\n\n useEffect(() => {\n handlerRef.current = tool.handler;\n }, [tool.handler, ...(dependencies ?? [])]);\n\n const normalizedHandler = tool.handler\n ? (args: MappedParameterTypes<T>) => handlerRef.current?.(args)\n : undefined;\n\n useFrontendToolVNext<MappedParameterTypes<T>>({\n name,\n description,\n parameters: zodParameters,\n handler: normalizedHandler,\n followUp,\n render: normalizedRender,\n });\n}\n","import {\n ActionRenderProps,\n ActionRenderPropsNoArgs,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types\";\nimport { Parameter, getZodParameters } from \"@copilotkit/shared\";\nimport React, { useEffect, useRef } from \"react\";\nimport { defineToolCallRenderer, useCopilotKit } from \"@copilotkitnext/react\";\nimport { parseJson } from \"@copilotkit/shared\";\n\ntype ToolCallRendererDefinition = Parameters<typeof defineToolCallRenderer>[0];\n\nexport type UseRenderToolCallArgs<T extends Parameter[] | [] = []> = Pick<\n FrontendAction<T>,\n \"name\" | \"description\" | \"parameters\"\n> & {\n available?: \"disabled\" | \"enabled\";\n render: T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => React.ReactElement\n : (props: ActionRenderProps<T>) => React.ReactElement;\n};\n\nexport function useRenderToolCall<const T extends Parameter[] | [] = []>(\n tool: UseRenderToolCallArgs<T>,\n dependencies?: any[],\n) {\n const { copilotkit } = useCopilotKit();\n\n // Track whether we've already added this renderer to avoid duplicates\n const hasAddedRef = useRef(false);\n\n useEffect(() => {\n const { name, parameters, render } = tool;\n const zodParameters = getZodParameters(parameters);\n\n const renderToolCall =\n name === \"*\"\n ? defineToolCallRenderer({\n name: \"*\",\n render: ((args) => {\n return render({\n ...args,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n })\n : defineToolCallRenderer({\n name,\n args: zodParameters,\n render: ((args) => {\n return render({\n ...args,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n });\n }) as ToolCallRendererDefinition[\"render\"],\n });\n\n // Remove any existing renderer with the same name\n const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);\n if (existingIndex !== -1) {\n copilotkit.renderToolCalls.splice(existingIndex, 1);\n }\n\n // Add the new renderer\n copilotkit.renderToolCalls.push(renderToolCall);\n hasAddedRef.current = true;\n\n // Cleanup: remove this renderer when the component unmounts or tool changes\n return () => {\n if (hasAddedRef.current) {\n const index = copilotkit.renderToolCalls.findIndex((r) => r.name === name);\n if (index !== -1) {\n copilotkit.renderToolCalls.splice(index, 1);\n }\n hasAddedRef.current = false;\n }\n };\n }, [tool, ...(dependencies ?? [])]);\n}\n","import { ActionRenderProps, ActionRenderPropsWait, FrontendAction } from \"../types\";\nimport {\n CopilotKitError,\n CopilotKitErrorCode,\n MappedParameterTypes,\n Parameter,\n getZodParameters,\n parseJson,\n} from \"@copilotkit/shared\";\nimport { useHumanInTheLoop as useHumanInTheLoopVNext } from \"@copilotkitnext/react\";\nimport { ToolCallStatus } from \"@copilotkitnext/core\";\nimport React, { ComponentType, FunctionComponent, useEffect, useRef } from \"react\";\n\ntype HumanInTheLoopOptions = Parameters<typeof useHumanInTheLoopVNext>[0];\ntype HumanInTheLoopRender = HumanInTheLoopOptions[\"render\"];\ntype HumanInTheLoopRenderArgs = HumanInTheLoopRender extends (props: infer P) => any ? P : never;\n\nexport type UseHumanInTheLoopArgs<T extends Parameter[] | [] = []> = {\n available?: \"disabled\" | \"enabled\";\n render: FrontendAction<T>[\"renderAndWaitForResponse\"];\n followUp?: FrontendAction<T>[\"followUp\"];\n} & Pick<FrontendAction<T>, \"name\" | \"description\" | \"parameters\">;\n\ntype HitlRendererArgs =\n | {\n name: string;\n description: string;\n args: Partial<Record<string, unknown>>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n respond: undefined;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Executing;\n result: undefined;\n respond: (result: unknown) => Promise<void>;\n }\n | {\n name: string;\n description: string;\n args: Record<string, unknown>;\n status: ToolCallStatus.Complete;\n result: string;\n respond: undefined;\n };\ntype HitlRenderer = FunctionComponent<HitlRendererArgs>;\n\nexport function useHumanInTheLoop<const T extends Parameter[] | [] = []>(\n tool: UseHumanInTheLoopArgs<T>,\n dependencies?: any[],\n) {\n const { render, ...toolRest } = tool;\n const { name, description, parameters, followUp } = toolRest;\n const zodParameters = getZodParameters(parameters);\n const renderRef = useRef<HitlRenderer | null>(null);\n\n useEffect(() => {\n renderRef.current = (args: HitlRendererArgs): React.ReactElement | null => {\n if (typeof render === \"string\") {\n return React.createElement(React.Fragment, null, render);\n }\n\n if (!render) {\n return null;\n }\n\n const renderProps: ActionRenderPropsWait<T> = (() => {\n const mappedArgs = args.args as unknown as MappedParameterTypes<T>;\n\n switch (args.status) {\n case ToolCallStatus.InProgress:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: undefined,\n };\n case ToolCallStatus.Executing:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n handler: () => {},\n };\n case ToolCallStatus.Complete:\n return {\n args: mappedArgs,\n respond: args.respond,\n status: args.status,\n result: args.result ? parseJson(args.result, args.result) : args.result,\n handler: undefined,\n };\n default:\n throw new CopilotKitError({\n code: CopilotKitErrorCode.UNKNOWN,\n message: `Invalid tool call status: ${(args as unknown as { status: string }).status}`,\n });\n }\n })();\n\n const rendered = render(renderProps);\n\n if (typeof rendered === \"string\") {\n return React.createElement(React.Fragment, null, rendered);\n }\n\n return rendered ?? null;\n };\n }, [render, ...(dependencies ?? [])]);\n\n useHumanInTheLoopVNext({\n name,\n description,\n followUp,\n parameters: zodParameters,\n render: ((args: HumanInTheLoopRenderArgs) =>\n renderRef.current?.(args as HitlRendererArgs) ?? null) as HumanInTheLoopOptions[\"render\"],\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,IAAAA,gBAA8C;;;ACU9C,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,cA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;AACvC,eAAO,OAAO,OAAO,KAAK;AAAA,MAC5B;AACA,aAAO,OAAO,UAAU,eAAAC,QAAM,cAAc,sBAAQ;AAAA,IACtD;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AAEA,QAAM,oBAAgB;AAAA,IACpB,CAAC,UAAuE;AACtE,YAAM,kBAAkB,OAAO,OAAO,gBAAgB,CAAC,CAAC,EAAE;AAAA,QACxD,CAAC,UAAU,MAAM,WAAW;AAAA,MAC9B;AAEA,UAAI,CAAC,iBAAiB;AAEpB,yBAAiB,UAAU;AAE3B,gBAAO,6CAAc,mBACjB,eAAAA,QAAM,cAAc,aAAa,iBAAiB;AAAA,UAChD,kBAAkB,CAAC,cAAc;AAC/B,+DAAkB,CAAC,SAAU,iCAAK,OAAL,EAAW,CAAC,OAAO,IAAI,GAAG,UAAU;AACjE,gBAAI,iBAAiB,SAAS;AAC5B,4BAAc,iBAAiB,OAAO;AACtC,+BAAiB,UAAU;AAAA,YAC7B;AAAA,UACF;AAAA,QACF,CAAC,IACD,eAAAA,QAAM,cAAc,sBAAQ;AAAA,MAClC;AAEA,aAAO,cAAc,KAAK;AAAA,IAC5B;AAAA,IACA,CAAC,QAAQ,cAAc,eAAe;AAAA,EACxC;AAEA;AAAA,IACE,iCACK,SADL;AAAA,MAEE,QAAQ;AAAA,IACV;AAAA,IACA;AAAA,EACF;AACF;","names":["import_react","React","import_react","import_react","import_shared","React","useFrontendToolVNext","import_shared","import_react","import_shared","import_react","React","useHumanInTheLoopVNext","_a","import_react","React"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCopilotAuthenticatedAction_c
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
3
|
+
} from "../chunk-E7SE25ZU.mjs";
|
|
4
|
+
import "../chunk-GPEJNVE5.mjs";
|
|
5
5
|
import "../chunk-NBK4KBLX.mjs";
|
|
6
|
-
import "../chunk-
|
|
6
|
+
import "../chunk-CDUIA2WM.mjs";
|
|
7
7
|
import "../chunk-7DTB7S5V.mjs";
|
|
8
8
|
import "../chunk-AFNWX62Q.mjs";
|
|
9
9
|
import "../chunk-SKC7AJIV.mjs";
|
|
@@ -661,7 +661,11 @@ function CoAgentStateRenderBridge(props) {
|
|
|
661
661
|
|
|
662
662
|
// src/hooks/use-copilot-chat_internal.ts
|
|
663
663
|
function useCopilotChatInternal({
|
|
664
|
-
suggestions
|
|
664
|
+
suggestions,
|
|
665
|
+
onInProgress,
|
|
666
|
+
onSubmitMessage,
|
|
667
|
+
onStopGeneration,
|
|
668
|
+
onReloadMessages
|
|
665
669
|
} = {}) {
|
|
666
670
|
var _a, _b, _c;
|
|
667
671
|
const { copilotkit } = (0, import_react14.useCopilotKit)();
|
|
@@ -690,6 +694,9 @@ function useCopilotChatInternal({
|
|
|
690
694
|
return () => {
|
|
691
695
|
};
|
|
692
696
|
}, [existingConfig == null ? void 0 : existingConfig.threadId, agent, copilotkit, resolvedAgentId]);
|
|
697
|
+
(0, import_react13.useEffect)(() => {
|
|
698
|
+
onInProgress == null ? void 0 : onInProgress(Boolean(agent == null ? void 0 : agent.isRunning));
|
|
699
|
+
}, [agent == null ? void 0 : agent.isRunning, onInProgress]);
|
|
693
700
|
const interrupt = useLangGraphInterruptRender(agent);
|
|
694
701
|
const reset = () => {
|
|
695
702
|
agent == null ? void 0 : agent.setMessages([]);
|
|
@@ -770,8 +777,12 @@ function useCopilotChatInternal({
|
|
|
770
777
|
console.error("CopilotChat: runAgent failed", error);
|
|
771
778
|
}
|
|
772
779
|
}
|
|
780
|
+
if (onSubmitMessage) {
|
|
781
|
+
const content = typeof message.content === "string" ? message.content : message.content && "text" in message.content ? message.content.text : message.content && "filename" in message.content ? message.content.filename : "";
|
|
782
|
+
onSubmitMessage(content);
|
|
783
|
+
}
|
|
773
784
|
}),
|
|
774
|
-
[agent, copilotkit, resolvedAgentId]
|
|
785
|
+
[agent, copilotkit, resolvedAgentId, onSubmitMessage]
|
|
775
786
|
);
|
|
776
787
|
const latestAppendFunc = useAsyncCallback(
|
|
777
788
|
(message, options) => __async(this, null, function* () {
|
|
@@ -792,14 +803,24 @@ function useCopilotChatInternal({
|
|
|
792
803
|
const latestReload = useUpdatedRef(reload);
|
|
793
804
|
const latestReloadFunc = useAsyncCallback(
|
|
794
805
|
(messageId) => __async(this, null, function* () {
|
|
806
|
+
var _a2;
|
|
807
|
+
onReloadMessages == null ? void 0 : onReloadMessages({
|
|
808
|
+
messageId,
|
|
809
|
+
currentAgentName: agent == null ? void 0 : agent.agentId,
|
|
810
|
+
messages: (_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : []
|
|
811
|
+
});
|
|
795
812
|
return yield latestReload.current(messageId);
|
|
796
813
|
}),
|
|
797
|
-
[latestReload]
|
|
814
|
+
[latestReload, agent, onReloadMessages]
|
|
798
815
|
);
|
|
799
816
|
const latestStopFunc = (0, import_react13.useCallback)(() => {
|
|
800
|
-
var _a2;
|
|
801
|
-
|
|
802
|
-
|
|
817
|
+
var _a2, _b2;
|
|
818
|
+
onStopGeneration == null ? void 0 : onStopGeneration({
|
|
819
|
+
currentAgentName: agent == null ? void 0 : agent.agentId,
|
|
820
|
+
messages: (_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : []
|
|
821
|
+
});
|
|
822
|
+
return (_b2 = agent == null ? void 0 : agent.abortRun) == null ? void 0 : _b2.call(agent);
|
|
823
|
+
}, [onStopGeneration, agent]);
|
|
803
824
|
const latestReset = useUpdatedRef(reset);
|
|
804
825
|
const latestResetFunc = (0, import_react13.useCallback)(() => {
|
|
805
826
|
return latestReset.current();
|