@copilotkit/react-core 1.4.8-coagents-v0-3.1 → 1.4.8-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CHANGELOG.md +4 -5
  2. package/dist/{chunk-UOVONDR6.mjs → chunk-6AZIHHSX.mjs} +2 -2
  3. package/dist/{chunk-OT67R4NB.mjs → chunk-6CMAB4VV.mjs} +10 -7
  4. package/dist/chunk-6CMAB4VV.mjs.map +1 -0
  5. package/dist/{chunk-EC5YZTSH.mjs → chunk-FOPYVT6C.mjs} +59 -92
  6. package/dist/chunk-FOPYVT6C.mjs.map +1 -0
  7. package/dist/{chunk-TNSI3FLW.mjs → chunk-HBXWZT7F.mjs} +8 -6
  8. package/dist/chunk-HBXWZT7F.mjs.map +1 -0
  9. package/dist/{chunk-XQFVXX6R.mjs → chunk-LK52LEEB.mjs} +3 -2
  10. package/dist/chunk-LK52LEEB.mjs.map +1 -0
  11. package/dist/{chunk-DHGXL5PC.mjs → chunk-R5G2G5F2.mjs} +8 -6
  12. package/dist/chunk-R5G2G5F2.mjs.map +1 -0
  13. package/dist/{chunk-XIDLJSIH.mjs → chunk-RQQVEHNP.mjs} +3 -3
  14. package/dist/chunk-RQQVEHNP.mjs.map +1 -0
  15. package/dist/{chunk-Y7MI4PBB.mjs → chunk-WIBNPMZ7.mjs} +2 -2
  16. package/dist/{chunk-X6ZF5WAX.mjs → chunk-WUEMPEM7.mjs} +2 -2
  17. package/dist/{chunk-AG7FH7OD.mjs → chunk-Z657A5VX.mjs} +2 -2
  18. package/dist/components/copilot-provider/copilot-messages.d.ts +1 -0
  19. package/dist/components/copilot-provider/copilotkit-props.d.ts +5 -0
  20. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  21. package/dist/components/copilot-provider/copilotkit.d.ts +1 -0
  22. package/dist/components/copilot-provider/copilotkit.js +4 -2
  23. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  24. package/dist/components/copilot-provider/copilotkit.mjs +2 -2
  25. package/dist/components/copilot-provider/index.d.ts +1 -0
  26. package/dist/components/copilot-provider/index.js +4 -2
  27. package/dist/components/copilot-provider/index.js.map +1 -1
  28. package/dist/components/copilot-provider/index.mjs +2 -2
  29. package/dist/components/index.d.ts +1 -0
  30. package/dist/components/index.js +4 -2
  31. package/dist/components/index.js.map +1 -1
  32. package/dist/components/index.mjs +2 -2
  33. package/dist/context/copilot-context.d.ts +5 -1
  34. package/dist/context/copilot-context.js +2 -1
  35. package/dist/context/copilot-context.js.map +1 -1
  36. package/dist/context/copilot-context.mjs +1 -1
  37. package/dist/context/index.js +2 -1
  38. package/dist/context/index.js.map +1 -1
  39. package/dist/context/index.mjs +1 -1
  40. package/dist/hooks/index.js +63 -92
  41. package/dist/hooks/index.js.map +1 -1
  42. package/dist/hooks/index.mjs +16 -16
  43. package/dist/hooks/use-chat.d.ts +2 -1
  44. package/dist/hooks/use-chat.js +57 -89
  45. package/dist/hooks/use-chat.js.map +1 -1
  46. package/dist/hooks/use-chat.mjs +1 -1
  47. package/dist/hooks/use-coagent-state-render.js +2 -1
  48. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  49. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  50. package/dist/hooks/use-coagent.js +63 -92
  51. package/dist/hooks/use-coagent.js.map +1 -1
  52. package/dist/hooks/use-coagent.mjs +6 -6
  53. package/dist/hooks/use-copilot-action.js +2 -1
  54. package/dist/hooks/use-copilot-action.js.map +1 -1
  55. package/dist/hooks/use-copilot-action.mjs +2 -2
  56. package/dist/hooks/use-copilot-chat.js +63 -92
  57. package/dist/hooks/use-copilot-chat.js.map +1 -1
  58. package/dist/hooks/use-copilot-chat.mjs +5 -5
  59. package/dist/hooks/use-copilot-readable.js +2 -1
  60. package/dist/hooks/use-copilot-readable.js.map +1 -1
  61. package/dist/hooks/use-copilot-readable.mjs +2 -2
  62. package/dist/hooks/use-make-copilot-document-readable.js +2 -1
  63. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  64. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  65. package/dist/index.d.ts +1 -1
  66. package/dist/index.js +74 -100
  67. package/dist/index.js.map +1 -1
  68. package/dist/index.mjs +17 -17
  69. package/dist/lib/copilot-task.d.ts +6 -1
  70. package/dist/lib/copilot-task.js +22 -4
  71. package/dist/lib/copilot-task.js.map +1 -1
  72. package/dist/lib/copilot-task.mjs +3 -3
  73. package/dist/lib/index.d.ts +1 -1
  74. package/dist/lib/index.js +22 -4
  75. package/dist/lib/index.js.map +1 -1
  76. package/dist/lib/index.mjs +3 -3
  77. package/dist/utils/extract.d.ts +3 -2
  78. package/dist/utils/extract.js +21 -3
  79. package/dist/utils/extract.js.map +1 -1
  80. package/dist/utils/extract.mjs +2 -2
  81. package/dist/utils/index.js +21 -3
  82. package/dist/utils/index.js.map +1 -1
  83. package/dist/utils/index.mjs +2 -2
  84. package/package.json +3 -3
  85. package/src/components/copilot-provider/copilotkit-props.tsx +6 -0
  86. package/src/components/copilot-provider/copilotkit.tsx +1 -0
  87. package/src/context/copilot-context.tsx +8 -1
  88. package/src/hooks/use-chat.ts +84 -128
  89. package/src/hooks/use-coagent.ts +1 -0
  90. package/src/hooks/use-copilot-chat.ts +2 -0
  91. package/src/lib/copilot-task.ts +10 -2
  92. package/src/utils/extract.ts +4 -0
  93. package/dist/chunk-DHGXL5PC.mjs.map +0 -1
  94. package/dist/chunk-EC5YZTSH.mjs.map +0 -1
  95. package/dist/chunk-OT67R4NB.mjs.map +0 -1
  96. package/dist/chunk-TNSI3FLW.mjs.map +0 -1
  97. package/dist/chunk-XIDLJSIH.mjs.map +0 -1
  98. package/dist/chunk-XQFVXX6R.mjs.map +0 -1
  99. /package/dist/{chunk-UOVONDR6.mjs.map → chunk-6AZIHHSX.mjs.map} +0 -0
  100. /package/dist/{chunk-Y7MI4PBB.mjs.map → chunk-WIBNPMZ7.mjs.map} +0 -0
  101. /package/dist/{chunk-X6ZF5WAX.mjs.map → chunk-WUEMPEM7.mjs.map} +0 -0
  102. /package/dist/{chunk-AG7FH7OD.mjs.map → chunk-Z657A5VX.mjs.map} +0 -0
@@ -1,19 +1,19 @@
1
1
  import {
2
2
  useCoAgent
3
- } from "../chunk-XIDLJSIH.mjs";
4
- import "../chunk-TNSI3FLW.mjs";
5
- import "../chunk-DHGXL5PC.mjs";
3
+ } from "../chunk-RQQVEHNP.mjs";
4
+ import "../chunk-HBXWZT7F.mjs";
5
+ import "../chunk-YPSGKPDA.mjs";
6
+ import "../chunk-R5G2G5F2.mjs";
6
7
  import "../chunk-MLAS4QUR.mjs";
7
8
  import "../chunk-XXR4QFAQ.mjs";
8
9
  import "../chunk-5FHSUKQL.mjs";
9
10
  import "../chunk-6U3UH3KO.mjs";
10
- import "../chunk-YPSGKPDA.mjs";
11
11
  import "../chunk-DCTJZ742.mjs";
12
- import "../chunk-EC5YZTSH.mjs";
12
+ import "../chunk-FOPYVT6C.mjs";
13
13
  import "../chunk-ODN4H66E.mjs";
14
14
  import "../chunk-2KCEHGSI.mjs";
15
15
  import "../chunk-O7ARI5CV.mjs";
16
- import "../chunk-XQFVXX6R.mjs";
16
+ import "../chunk-LK52LEEB.mjs";
17
17
  import "../chunk-SKC7AJIV.mjs";
18
18
  export {
19
19
  useCoAgent
@@ -124,7 +124,8 @@ var emptyCopilotContext = {
124
124
  },
125
125
  agentSession: null,
126
126
  setAgentSession: () => {
127
- }
127
+ },
128
+ forwardedParameters: {}
128
129
  };
129
130
  var CopilotContext = import_react.default.createContext(emptyCopilotContext);
130
131
  function useCopilotContext() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-copilot-action.ts","../../src/context/copilot-context.tsx"],"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\n/**\n * <img src=\"/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 { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types/frontend-action\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // If the developer provides a renderAndWait function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (action.renderAndWait || action.renderAndWaitForResponse) {\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n // add a handler that will be called when the action is executed\n action.handler = (async () => {\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = { promise, resolve: resolve!, reject: reject! };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n return await promise;\n }) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T>): React.ReactElement => {\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status: props.status,\n args: props.args,\n result: props.result,\n handler: props.status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n respond: props.status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n actions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.actions[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.actions[action.name] = action.render;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n action.description,\n action.name,\n action.disabled,\n action.available,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\ninterface RenderAndWaitForResponse {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } 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 { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\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\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | 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 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 // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: 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 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 // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\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 // runtime\n runtimeClient: CopilotRuntimeClient;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n runtimeClient: {} as any,\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: \"auto\",\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n\n agentSession: null,\n setAgentSession: () => {},\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 return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA2HA,oBAAoC;AACpC,IAAAA,gBAA2D;;;AC1H3D,mBAAkB;AAkJlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,CAAC;AAAA,EACtB,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,0BAA0B,MAAM;AAAA,EAAC;AAAA,EAEjC,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,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,EACvE,oBAAoB,MAAM,sBAAsB,EAAE;AAAA,EAClD,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,eAAe,CAAC;AAAA,EAEhB,kBAAkB,IAAK,MAAkC;AAAA,IACvD,IAAI,kBAA0B;AAC5B,YAAM,IAAI,MA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AAK,UAAU,OAAO,UAAU;AAAA;AAAA,IAEhC,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":["import_react","React"]}
1
+ {"version":3,"sources":["../../src/hooks/use-copilot-action.ts","../../src/context/copilot-context.tsx"],"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\n/**\n * <img src=\"/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 { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types/frontend-action\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // If the developer provides a renderAndWait function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (action.renderAndWait || action.renderAndWaitForResponse) {\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n // add a handler that will be called when the action is executed\n action.handler = (async () => {\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = { promise, resolve: resolve!, reject: reject! };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n return await promise;\n }) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T>): React.ReactElement => {\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status: props.status,\n args: props.args,\n result: props.result,\n handler: props.status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n respond: props.status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n actions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.actions[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.actions[action.name] = action.render;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n action.description,\n action.name,\n action.disabled,\n action.available,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\ninterface RenderAndWaitForResponse {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } 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 { CopilotRuntimeClient, ForwardedParametersInput } from \"@copilotkit/runtime-client-gql\";\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\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | 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 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 // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: 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 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 // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\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 // runtime\n runtimeClient: CopilotRuntimeClient;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n runtimeClient: {} as any,\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: \"auto\",\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n\n agentSession: null,\n setAgentSession: () => {},\n\n forwardedParameters: {},\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 return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA2HA,oBAAoC;AACpC,IAAAA,gBAA2D;;;AC1H3D,mBAAkB;AAuJlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,CAAC;AAAA,EACtB,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,0BAA0B,MAAM;AAAA,EAAC;AAAA,EAEjC,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAAA,EACzE,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AA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AO,OAAO,WAAW,YAAY;AACvC,YAAI,oBAAoB,YAAY,MAAM;AACxC,8BAAoB,QAAQ,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,QAC5D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,+BAAU,MAAM;AACd,cAAU,MAAM,SAAS,MAAa;AACtC,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,IAC5D;AACA,WAAO,MAAM;AAGX,mBAAa,MAAM,OAAO;AAAA,IAC5B;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA;AAAA;AAAA,IAGP,KAAK,UAAU,OAAO,UAAU;AAAA;AAAA,IAEhC,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":["import_react","React"]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  useCopilotAction
3
- } from "../chunk-Y7MI4PBB.mjs";
4
- import "../chunk-XQFVXX6R.mjs";
3
+ } from "../chunk-WIBNPMZ7.mjs";
4
+ import "../chunk-LK52LEEB.mjs";
5
5
  import "../chunk-SKC7AJIV.mjs";
6
6
  export {
7
7
  useCopilotAction
@@ -139,7 +139,8 @@ var emptyCopilotContext = {
139
139
  },
140
140
  agentSession: null,
141
141
  setAgentSession: () => {
142
- }
142
+ },
143
+ forwardedParameters: {}
143
144
  };
144
145
  var CopilotContext = import_react.default.createContext(emptyCopilotContext);
145
146
  function useCopilotContext() {
@@ -238,28 +239,28 @@ function useChat(options) {
238
239
  setMessages([...previousMessages, ...newMessages]);
239
240
  const systemMessage = makeSystemMessageCallback();
240
241
  const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
241
- const filteredActions = actions.filter((action) => action.available !== import_runtime_client_gql2.ActionInputAvailability.Disabled || !action.disabled).map((action) => {
242
- let available = import_runtime_client_gql2.ActionInputAvailability.Enabled;
243
- if (action.disabled) {
244
- available = import_runtime_client_gql2.ActionInputAvailability.Disabled;
245
- } else if (action.available === "disabled") {
246
- available = import_runtime_client_gql2.ActionInputAvailability.Disabled;
247
- } else if (action.available === "remote") {
248
- available = import_runtime_client_gql2.ActionInputAvailability.Remote;
249
- }
250
- return {
251
- name: action.name,
252
- description: action.description || "",
253
- jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
254
- available
255
- };
256
- });
257
- const isAgentRun = agentSessionRef.current !== null;
258
242
  const stream = runtimeClient.asStream(
259
243
  runtimeClient.generateCopilotResponse({
260
244
  data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
261
245
  frontend: {
262
- actions: filteredActions,
246
+ actions: actions.filter(
247
+ (action) => action.available !== import_runtime_client_gql2.ActionInputAvailability.Disabled || !action.disabled
248
+ ).map((action) => {
249
+ let available = import_runtime_client_gql2.ActionInputAvailability.Enabled;
250
+ if (action.disabled) {
251
+ available = import_runtime_client_gql2.ActionInputAvailability.Disabled;
252
+ } else if (action.available === "disabled") {
253
+ available = import_runtime_client_gql2.ActionInputAvailability.Disabled;
254
+ } else if (action.available === "remote") {
255
+ available = import_runtime_client_gql2.ActionInputAvailability.Remote;
256
+ }
257
+ return {
258
+ name: action.name,
259
+ description: action.description || "",
260
+ jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
261
+ available
262
+ };
263
+ }),
263
264
  url: window.location.href
264
265
  },
265
266
  threadId: threadIdRef.current,
@@ -284,7 +285,8 @@ function useChat(options) {
284
285
  agentStates: Object.values(coagentStatesRef.current).map((state) => ({
285
286
  agentName: state.name,
286
287
  state: JSON.stringify(state.state)
287
- }))
288
+ })),
289
+ forwardedParameters: options.forwardedParameters || {}
288
290
  }),
289
291
  properties: copilotConfig.properties,
290
292
  signal: (_d = abortControllerRef.current) == null ? void 0 : _d.signal
@@ -292,10 +294,9 @@ function useChat(options) {
292
294
  );
293
295
  const guardrailsEnabled = ((_g = (_f = (_e = copilotConfig.cloud) == null ? void 0 : _e.guardrails) == null ? void 0 : _f.input) == null ? void 0 : _g.restrictToTopic.enabled) || false;
294
296
  const reader = stream.getReader();
297
+ let actionResults = {};
295
298
  let executedCoAgentStateRenders = [];
296
299
  let followUp = void 0;
297
- let messages2 = [];
298
- let syncedMessages = [];
299
300
  try {
300
301
  while (true) {
301
302
  let done, value;
@@ -314,7 +315,7 @@ function useChat(options) {
314
315
  }
315
316
  threadIdRef.current = value.generateCopilotResponse.threadId || null;
316
317
  runIdRef.current = value.generateCopilotResponse.runId || null;
317
- messages2 = (0, import_runtime_client_gql2.convertGqlOutputToMessages)(
318
+ const messages2 = (0, import_runtime_client_gql2.convertGqlOutputToMessages)(
318
319
  (0, import_runtime_client_gql2.filterAdjacentAgentStateMessages)(value.generateCopilotResponse.messages)
319
320
  );
320
321
  if (messages2.length === 0) {
@@ -328,11 +329,39 @@ function useChat(options) {
328
329
  content: ((_i = value.generateCopilotResponse.status.details) == null ? void 0 : _i.guardrailsReason) || ""
329
330
  })
330
331
  ];
331
- setMessages([...previousMessages, ...newMessages]);
332
- break;
333
332
  } else {
334
- newMessages = [...messages2];
335
333
  for (const message of messages2) {
334
+ newMessages.push(message);
335
+ if (message.isActionExecutionMessage() && message.status.code !== import_runtime_client_gql2.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
336
+ if (!(message.id in actionResults)) {
337
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
338
+ break;
339
+ }
340
+ try {
341
+ setMessages([...previousMessages, ...newMessages]);
342
+ const action = actions.find((action2) => action2.name === message.name);
343
+ if (action) {
344
+ followUp = action.followUp;
345
+ }
346
+ const result = yield onFunctionCall({
347
+ messages: previousMessages,
348
+ name: message.name,
349
+ args: message.arguments
350
+ });
351
+ actionResults[message.id] = result;
352
+ } catch (e) {
353
+ actionResults[message.id] = `Failed to execute action ${message.name}`;
354
+ console.error(`Failed to execute action ${message.name}: ${e}`);
355
+ }
356
+ }
357
+ newMessages.push(
358
+ new import_runtime_client_gql2.ResultMessage({
359
+ result: import_runtime_client_gql2.ResultMessage.encodeResult(actionResults[message.id]),
360
+ actionExecutionId: message.id,
361
+ actionName: message.name
362
+ })
363
+ );
364
+ }
336
365
  if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
337
366
  if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
338
367
  break;
@@ -347,11 +376,6 @@ function useChat(options) {
347
376
  }
348
377
  const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
349
378
  if (lastAgentStateMessage) {
350
- if (lastAgentStateMessage.state.messages && lastAgentStateMessage.state.messages.length > 0) {
351
- syncedMessages = (0, import_runtime_client_gql2.loadMessagesFromJsonRepresentation)(
352
- lastAgentStateMessage.state.messages
353
- );
354
- }
355
379
  setCoagentStatesWithRef((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
356
380
  [lastAgentStateMessage.agentName]: {
357
381
  name: lastAgentStateMessage.agentName,
@@ -378,52 +402,14 @@ function useChat(options) {
378
402
  setMessages([...previousMessages, ...newMessages]);
379
403
  }
380
404
  }
381
- const finalMessages = constructFinalMessages(syncedMessages, previousMessages, newMessages);
382
- let didExecuteAction = false;
383
- if (onFunctionCall) {
384
- const lastMessages = [];
385
- for (let i = finalMessages.length - 1; i >= 0; i--) {
386
- const message = finalMessages[i];
387
- if (message.isActionExecutionMessage() && message.status.code !== import_runtime_client_gql2.MessageStatusCode.Pending) {
388
- lastMessages.unshift(message);
389
- } else {
390
- break;
391
- }
392
- }
393
- for (const message of lastMessages) {
394
- setMessages(finalMessages);
395
- const action = actions.find((action2) => action2.name === message.name);
396
- if (action) {
397
- followUp = action.followUp;
398
- const result = yield onFunctionCall({
399
- messages: finalMessages,
400
- name: message.name,
401
- args: message.arguments
402
- });
403
- didExecuteAction = true;
404
- const messageIndex = finalMessages.findIndex((msg) => msg.id === message.id);
405
- finalMessages.splice(
406
- messageIndex + 1,
407
- 0,
408
- new import_runtime_client_gql2.ResultMessage({
409
- id: "result-" + message.id,
410
- result: import_runtime_client_gql2.ResultMessage.encodeResult(result),
411
- actionExecutionId: message.id,
412
- actionName: message.name
413
- })
414
- );
415
- }
416
- }
417
- setMessages(finalMessages);
418
- }
419
405
  if (
420
406
  // if followUp is not explicitly false
421
- followUp !== false && // and we executed an action
422
- (didExecuteAction || // the last message is a server side result
423
- !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage())
407
+ followUp !== false && // if we have client side results
408
+ (Object.values(actionResults).length || // or the last message we received is a result
409
+ newMessages.length && newMessages[newMessages.length - 1].isResultMessage())
424
410
  ) {
425
411
  yield new Promise((resolve) => setTimeout(resolve, 10));
426
- return yield runChatCompletionRef.current(finalMessages);
412
+ return yield runChatCompletionRef.current([...previousMessages, ...newMessages]);
427
413
  } else {
428
414
  return newMessages.slice();
429
415
  }
@@ -466,23 +452,6 @@ function useChat(options) {
466
452
  runChatCompletion: () => runChatCompletionRef.current(messages)
467
453
  };
468
454
  }
469
- function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
470
- const finalMessages = syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];
471
- if (syncedMessages.length > 0) {
472
- const messagesWithAgentState = [...previousMessages, ...newMessages];
473
- let previousMessageId = void 0;
474
- for (const message of messagesWithAgentState) {
475
- if (message.isAgentStateMessage()) {
476
- const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);
477
- if (index !== -1) {
478
- finalMessages.splice(index + 1, 0, message);
479
- }
480
- }
481
- previousMessageId = message.id;
482
- }
483
- }
484
- return finalMessages;
485
- }
486
455
 
487
456
  // src/components/copilot-provider/copilotkit.tsx
488
457
  var import_react6 = require("react");
@@ -529,7 +498,8 @@ function useCopilotChat(_a = {}) {
529
498
  setCoagentStatesWithRef,
530
499
  coAgentStateRenders,
531
500
  agentSession,
532
- setAgentSession
501
+ setAgentSession,
502
+ forwardedParameters
533
503
  } = useCopilotContext();
534
504
  const { messages, setMessages } = useCopilotMessagesContext();
535
505
  const latestGetContextString = useUpdatedRef(getContextString);
@@ -579,7 +549,8 @@ function useCopilotChat(_a = {}) {
579
549
  coagentStatesRef,
580
550
  setCoagentStatesWithRef,
581
551
  agentSession,
582
- setAgentSession
552
+ setAgentSession,
553
+ forwardedParameters
583
554
  }));
584
555
  const latestAppend = useUpdatedRef(append);
585
556
  const latestAppendFunc = (0, import_react7.useCallback)(