@copilotkit/react-core 1.1.1-feat-runtime-remote-actions.4 → 1.1.1-feat-runtime-remote-actions.5

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 (129) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/{chunk-2MQX7BJL.mjs → chunk-6GOM3DN7.mjs} +2 -2
  3. package/dist/{chunk-IF6P5ZXR.mjs → chunk-6UNB66M3.mjs} +38 -10
  4. package/dist/chunk-6UNB66M3.mjs.map +1 -0
  5. package/dist/{chunk-73KBO5JG.mjs → chunk-73YBF52D.mjs} +2 -2
  6. package/dist/chunk-BWYAGPEF.mjs +1 -0
  7. package/dist/{chunk-DZH3HSXW.mjs → chunk-CHOQ5C7K.mjs} +35 -8
  8. package/dist/chunk-CHOQ5C7K.mjs.map +1 -0
  9. package/dist/{chunk-33ERMMNX.mjs → chunk-DU7PVINC.mjs} +2 -2
  10. package/dist/chunk-IQH77T4S.mjs +44 -0
  11. package/dist/chunk-IQH77T4S.mjs.map +1 -0
  12. package/dist/{chunk-DB4VWZ5Q.mjs → chunk-LTA2O5WH.mjs} +11 -6
  13. package/dist/chunk-LTA2O5WH.mjs.map +1 -0
  14. package/dist/chunk-MTOHRBPJ.mjs +87 -0
  15. package/dist/chunk-MTOHRBPJ.mjs.map +1 -0
  16. package/dist/{chunk-52M7642J.mjs → chunk-PPYZB3IY.mjs} +52 -31
  17. package/dist/chunk-PPYZB3IY.mjs.map +1 -0
  18. package/dist/{chunk-H4XENJME.mjs → chunk-SYJIZLOI.mjs} +2 -2
  19. package/dist/{chunk-3K7JAFGM.mjs → chunk-TFSMXQYS.mjs} +2 -2
  20. package/dist/components/copilot-provider/copilotkit-props.d.ts +4 -0
  21. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  22. package/dist/components/copilot-provider/copilotkit.js +46 -13
  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.js +46 -13
  26. package/dist/components/copilot-provider/index.js.map +1 -1
  27. package/dist/components/copilot-provider/index.mjs +2 -2
  28. package/dist/components/index.js +46 -13
  29. package/dist/components/index.js.map +1 -1
  30. package/dist/components/index.mjs +2 -2
  31. package/dist/context/copilot-context.d.ts +18 -8
  32. package/dist/context/copilot-context.js +10 -5
  33. package/dist/context/copilot-context.js.map +1 -1
  34. package/dist/context/copilot-context.mjs +1 -1
  35. package/dist/context/index.d.ts +2 -1
  36. package/dist/context/index.js +10 -5
  37. package/dist/context/index.js.map +1 -1
  38. package/dist/context/index.mjs +1 -1
  39. package/dist/hooks/index.d.ts +4 -2
  40. package/dist/hooks/index.js +205 -89
  41. package/dist/hooks/index.js.map +1 -1
  42. package/dist/hooks/index.mjs +17 -17
  43. package/dist/hooks/use-chat.d.ts +24 -7
  44. package/dist/hooks/use-chat.js +51 -30
  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-action.d.ts +5 -0
  48. package/dist/hooks/{use-copilot-chat-ui.js → use-coagent-action.js} +48 -22
  49. package/dist/hooks/use-coagent-action.js.map +1 -0
  50. package/dist/hooks/use-coagent-action.mjs +9 -0
  51. package/dist/hooks/use-coagent.d.ts +14 -18
  52. package/dist/hooks/use-coagent.js +184 -17
  53. package/dist/hooks/use-coagent.js.map +1 -1
  54. package/dist/hooks/use-coagent.mjs +6 -20
  55. package/dist/hooks/use-coagent.mjs.map +1 -1
  56. package/dist/hooks/use-copilot-action.js +10 -5
  57. package/dist/hooks/use-copilot-action.js.map +1 -1
  58. package/dist/hooks/use-copilot-action.mjs +2 -2
  59. package/dist/hooks/use-copilot-chat.js +89 -37
  60. package/dist/hooks/use-copilot-chat.js.map +1 -1
  61. package/dist/hooks/use-copilot-chat.mjs +4 -4
  62. package/dist/hooks/use-copilot-readable.js +10 -5
  63. package/dist/hooks/use-copilot-readable.js.map +1 -1
  64. package/dist/hooks/use-copilot-readable.mjs +2 -2
  65. package/dist/hooks/use-make-copilot-document-readable.js +10 -5
  66. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  67. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  68. package/dist/index.d.ts +4 -2
  69. package/dist/index.js +263 -119
  70. package/dist/index.js.map +1 -1
  71. package/dist/index.mjs +21 -21
  72. package/dist/lib/copilot-task.d.ts +2 -1
  73. package/dist/lib/copilot-task.js.map +1 -1
  74. package/dist/lib/copilot-task.mjs +3 -3
  75. package/dist/lib/index.d.ts +2 -1
  76. package/dist/lib/index.js.map +1 -1
  77. package/dist/lib/index.mjs +3 -3
  78. package/dist/types/coagent-action.d.ts +17 -0
  79. package/dist/types/coagent-action.js +19 -0
  80. package/dist/types/coagent-action.js.map +1 -0
  81. package/dist/types/coagent-action.mjs +1 -0
  82. package/dist/types/coagent-state.d.ts +11 -0
  83. package/dist/types/coagent-state.js +19 -0
  84. package/dist/types/coagent-state.js.map +1 -0
  85. package/dist/types/coagent-state.mjs +1 -0
  86. package/dist/types/coagent-state.mjs.map +1 -0
  87. package/dist/utils/extract.d.ts +2 -1
  88. package/dist/utils/extract.js.map +1 -1
  89. package/dist/utils/extract.mjs +3 -3
  90. package/dist/utils/index.d.ts +2 -1
  91. package/dist/utils/index.js.map +1 -1
  92. package/dist/utils/index.mjs +3 -3
  93. package/package.json +5 -5
  94. package/src/components/copilot-provider/copilotkit-props.tsx +5 -0
  95. package/src/components/copilot-provider/copilotkit.tsx +41 -9
  96. package/src/context/copilot-context.tsx +34 -15
  97. package/src/hooks/index.ts +2 -2
  98. package/src/hooks/use-chat.ts +88 -38
  99. package/src/hooks/use-coagent-action.ts +44 -0
  100. package/src/hooks/use-coagent.ts +111 -38
  101. package/src/hooks/use-copilot-chat.ts +29 -2
  102. package/src/types/coagent-action.ts +17 -0
  103. package/src/types/coagent-state.ts +9 -0
  104. package/dist/chunk-52M7642J.mjs.map +0 -1
  105. package/dist/chunk-6YOQY4WD.mjs +0 -20
  106. package/dist/chunk-6YOQY4WD.mjs.map +0 -1
  107. package/dist/chunk-A47L32JN.mjs +0 -52
  108. package/dist/chunk-A47L32JN.mjs.map +0 -1
  109. package/dist/chunk-AIWDXM7L.mjs +0 -1
  110. package/dist/chunk-DB4VWZ5Q.mjs.map +0 -1
  111. package/dist/chunk-DZH3HSXW.mjs.map +0 -1
  112. package/dist/chunk-IF6P5ZXR.mjs.map +0 -1
  113. package/dist/hooks/use-agent-state.d.ts +0 -12
  114. package/dist/hooks/use-agent-state.js +0 -499
  115. package/dist/hooks/use-agent-state.js.map +0 -1
  116. package/dist/hooks/use-agent-state.mjs +0 -19
  117. package/dist/hooks/use-copilot-chat-ui.d.ts +0 -13
  118. package/dist/hooks/use-copilot-chat-ui.js.map +0 -1
  119. package/dist/hooks/use-copilot-chat-ui.mjs +0 -10
  120. package/src/hooks/use-agent-state.ts +0 -63
  121. package/src/hooks/use-copilot-chat-ui.ts +0 -26
  122. /package/dist/{chunk-2MQX7BJL.mjs.map → chunk-6GOM3DN7.mjs.map} +0 -0
  123. /package/dist/{chunk-73KBO5JG.mjs.map → chunk-73YBF52D.mjs.map} +0 -0
  124. /package/dist/{chunk-AIWDXM7L.mjs.map → chunk-BWYAGPEF.mjs.map} +0 -0
  125. /package/dist/{chunk-33ERMMNX.mjs.map → chunk-DU7PVINC.mjs.map} +0 -0
  126. /package/dist/{chunk-H4XENJME.mjs.map → chunk-SYJIZLOI.mjs.map} +0 -0
  127. /package/dist/{chunk-3K7JAFGM.mjs.map → chunk-TFSMXQYS.mjs.map} +0 -0
  128. /package/dist/hooks/{use-agent-state.mjs.map → use-coagent-action.mjs.map} +0 -0
  129. /package/dist/{hooks/use-copilot-chat-ui.mjs.map → types/coagent-action.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-chat.ts"],"sourcesContent":["import { useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n Action,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ActionExecutionMessage,\n ResultMessage,\n CopilotRuntimeClient,\n convertMessagesToGqlInput,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n AgentStateMessage,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n /**\n * Function definitions to be sent to the API.\n */\n actions: Action[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * setState-powered method to update the agent states\n */\n setAgentStates: React.Dispatch<React.SetStateAction<Record<string, AgentStateMessage | null>>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\ninterface AgentSession {\n threadId: string;\n agentName: string;\n nodeName: string;\n}\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n setAgentStates,\n } = options;\n\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const agentSessionRef = useRef<AgentSession | null>(null);\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: actions.map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(messagesWithContext),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: {\n threadId: agentSessionRef.current.threadId,\n agentName: agentSessionRef.current.agentName,\n nodeName: agentSessionRef.current.nodeName,\n },\n }\n : {}),\n },\n properties: copilotConfig.properties,\n signal: abortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let results: { [id: string]: string } = {};\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n\n if (message instanceof AgentStateMessage) {\n if (message.running) {\n setAgentStates((prevAgentStates) => ({\n ...prevAgentStates,\n [message.agentName]: message,\n }));\n agentSessionRef.current = {\n threadId: message.threadId,\n agentName: message.agentName,\n nodeName: message.nodeName,\n };\n } else {\n setAgentStates((prevAgentStates) => {\n const newAgentStates = { ...prevAgentStates };\n delete newAgentStates[message.agentName];\n return newAgentStates;\n });\n agentSessionRef.current = null;\n }\n }\n\n // execute regular action executions\n if (\n message instanceof ActionExecutionMessage &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in results)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n results[message.id] = result;\n }\n\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(results[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Construct filteredMessages inline to remove adjacent AgentStateMessage instances\n // with the same agentName, keeping only the last one.\n const filteredMessages = [...previousMessages, ...newMessages].reduce(\n (acc: Message[], message: Message) => {\n if (\n message instanceof AgentStateMessage && // Check if the current message is an AgentStateMessage\n acc.length > 0 && // Ensure there is at least one message in the accumulator\n acc[acc.length - 1] instanceof AgentStateMessage && // Check if the last message in the accumulator is also an AgentStateMessage\n (acc[acc.length - 1] as AgentStateMessage).agentName === message.agentName && // Check if the agentName is the same\n (acc[acc.length - 1] as AgentStateMessage).nodeName === message.nodeName // Check if the nodeName is the same\n ) {\n // If the conditions are met, replace the last message in the accumulator with the current message\n acc[acc.length - 1] = message;\n } else {\n // Otherwise, add the current message to the accumulator\n acc.push(message);\n }\n return acc; // Return the accumulator for the next iteration\n },\n [],\n );\n\n // Update the state with the filtered messages\n setMessages(filteredMessages);\n }\n }\n\n if (\n // if we have client side results\n Object.values(results).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage)\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage instanceof TextMessage && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAuB;AACvB,oBAKO;AACP,gCAaO;AAgFA,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,QAAM,yBAAqB,qBAAwB;AACnD,QAAM,kBAAc,qBAAsB,IAAI;AAC9C,QAAM,eAAW,qBAAsB,IAAI;AAC3C,QAAM,sBAAkB,qBAA4B,IAAI;AAExD,QAAM,eAAe,cAAc;AAEnC,QAAM,UAAU,kCACV,cAAc,WAAW,CAAC,IAC1B,eAAe,EAAE,CAAC,iDAAmC,GAAG,aAAa,IAAI,CAAC;AAGhF,QAAM,gBAAgB,IAAI,+CAAqB;AAAA,IAC7C,KAAK,cAAc;AAAA,IACnB,cAAc,cAAc;AAAA,IAC5B;AAAA,IACA,aAAa,cAAc;AAAA,EAC7B,CAAC;AAED,QAAM,oBAAoB,CAAO,qBAAoD;AArIvF;AAsII,iBAAa,IAAI;AAIjB,QAAI,cAAyB;AAAA,MAC3B,IAAI,sCAAY;AAAA,QACd,SAAS;AAAA,QACT,MAAM,+BAAK;AAAA,MACb,CAAC;AAAA,IACH;AACA,UAAM,kBAAk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;AAKA,cAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAEtD,eAAO,MAAM,kBAAkB,CAAC,GAAG,kBAAkB,GAAG,WAAW,CAAC;AAAA,MACtE,OAAO;AACL,eAAO,YAAY,MAAM;AAAA,MAC3B;AAAA,IACF,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF;AAEA,QAAM,yCAAyC,CAAOA,cAAuC;AAC3F,UAAM,kBAAkBA,SAAQ;AAAA,EAClC;AAEA,QAAM,SAAS,CAAO,YAAoC;AACxD,QAAI,WAAW;AACb;AAAA,IACF;AAEA,UAAM,cAAc,CAAC,GAAG,UAAU,OAAO;AACzC,gBAAY,WAAW;AACvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,SAAS,MAA2B;AACxC,QAAI,aAAa,SAAS,WAAW,GAAG;AACtC;AAAA,IACF;AACA,QAAI,cAAc,CAAC,GAAG,QAAQ;AAC9B,UAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,QAAI,uBAAuB,yCAAe,YAAY,SAAS,aAAa;AAC1E,oBAAc,YAAY,MAAM,GAAG,EAAE;AAAA,IACvC;AAEA,gBAAY,WAAW;AAEvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,OAAO,MAAY;AA/X3B;AAgYI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["messages"]}
1
+ {"version":3,"sources":["../../src/hooks/use-chat.ts"],"sourcesContent":["import { useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n actionParametersToJsonSchema,\n CoagentActionHandler,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ActionExecutionMessage,\n ResultMessage,\n CopilotRuntimeClient,\n convertMessagesToGqlInput,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n AgentStateMessage,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession } from \"../context/copilot-context\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoagentAction?: CoagentActionHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStates: Record<string, CoagentState>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoagentAction,\n setCoagentStates,\n coagentStates,\n agentSession,\n setAgentSession,\n } = options;\n\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: actions.map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(messagesWithContext),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSession\n ? {\n agentSession,\n }\n : {}),\n agentStates: Object.values(coagentStates).map((state) => ({\n agentName: state.name,\n state: JSON.stringify(state.state),\n })),\n },\n properties: copilotConfig.properties,\n signal: abortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let actionResults: { [id: string]: string } = {};\n let executedCoagentActions: string[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n\n if (message instanceof AgentStateMessage) {\n if (message.running) {\n setCoagentStates((prevAgentStates) => ({\n ...prevAgentStates,\n [message.agentName]: {\n name: message.agentName,\n state: message.state,\n running: message.running,\n active: message.active,\n threadId: message.threadId,\n nodeName: message.nodeName,\n runId: message.runId,\n },\n }));\n setAgentSession({\n threadId: message.threadId,\n agentName: message.agentName,\n nodeName: message.nodeName,\n });\n } else {\n setAgentSession(null);\n }\n }\n\n // execute regular action executions\n if (\n message instanceof ActionExecutionMessage &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in actionResults)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n actionResults[message.id] = result;\n }\n\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(actionResults[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n\n // execute coagent actions\n if (\n message instanceof AgentStateMessage &&\n !message.active &&\n !executedCoagentActions.includes(message.id) &&\n onCoagentAction\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoagentAction({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoagentActions.push(message.id);\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Construct filteredMessages inline to remove adjacent AgentStateMessage instances\n // with the same agentName, keeping only the last one.\n const filteredMessages = [...previousMessages, ...newMessages].reduce(\n (acc: Message[], message: Message) => {\n if (\n // If the current message is an AgentStateMessage\n message instanceof AgentStateMessage &&\n // And there is at least one message in the accumulator\n acc.length > 0 &&\n // And the last message in the accumulator is also an AgentStateMessage\n acc[acc.length - 1] instanceof AgentStateMessage &&\n // And the agentName, nodeName, and runId are the same\n (acc[acc.length - 1] as AgentStateMessage).agentName === message.agentName &&\n (acc[acc.length - 1] as AgentStateMessage).nodeName === message.nodeName &&\n (acc[acc.length - 1] as AgentStateMessage).runId === message.runId\n ) {\n // If the conditions are met, replace the last message in the accumulator with the current message\n acc[acc.length - 1] = message;\n } else {\n // Otherwise, add the current message to the accumulator\n acc.push(message);\n }\n return acc;\n },\n [],\n );\n\n // Update the state with the filtered messages\n setMessages(filteredMessages);\n }\n }\n\n if (\n // if we have client side results\n Object.values(actionResults).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage)\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage instanceof TextMessage && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAuB;AACvB,oBAKO;AACP,gCAaO;AAkGA,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,QAAM,yBAAqB,qBAAwB;AACnD,QAAM,kBAAc,qBAAsB,IAAI;AAC9C,QAAM,eAAW,qBAAsB,IAAI;AAE3C,QAAM,eAAe,cAAc;AAEnC,QAAM,UAAU,k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AAM,kBAAkBA,SAAQ;AAAA,EAClC;AAEA,QAAM,SAAS,CAAO,YAAoC;AACxD,QAAI,WAAW;AACb;AAAA,IACF;AAEA,UAAM,cAAc,CAAC,GAAG,UAAU,OAAO;AACzC,gBAAY,WAAW;AACvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,SAAS,MAA2B;AACxC,QAAI,aAAa,SAAS,WAAW,GAAG;AACtC;AAAA,IACF;AACA,QAAI,cAAc,CAAC,GAAG,QAAQ;AAC9B,UAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,QAAI,uBAAuB,yCAAe,YAAY,SAAS,aAAa;AAC1E,oBAAc,YAAY,MAAM,GAAG,EAAE;AAAA,IACvC;AAEA,gBAAY,WAAW;AAEvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,OAAO,MAAY;AAjb3B;AAkbI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["messages"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useChat
3
- } from "../chunk-52M7642J.mjs";
3
+ } from "../chunk-PPYZB3IY.mjs";
4
4
  import "../chunk-SKC7AJIV.mjs";
5
5
  export {
6
6
  useChat
@@ -0,0 +1,5 @@
1
+ import { CoagentAction } from '../types/coagent-action.js';
2
+
3
+ declare function useCoagentAction<T = any>(action: CoagentAction<T>, dependencies?: any[]): void;
4
+
5
+ export { useCoagentAction };
@@ -47,12 +47,13 @@ var __async = (__this, __arguments, generator) => {
47
47
  });
48
48
  };
49
49
 
50
- // src/hooks/use-copilot-chat-ui.ts
51
- var use_copilot_chat_ui_exports = {};
52
- __export(use_copilot_chat_ui_exports, {
53
- useCopilotChatUI: () => useCopilotChatUI
50
+ // src/hooks/use-coagent-action.ts
51
+ var use_coagent_action_exports = {};
52
+ __export(use_coagent_action_exports, {
53
+ useCoagentAction: () => useCoagentAction
54
54
  });
55
- module.exports = __toCommonJS(use_copilot_chat_ui_exports);
55
+ module.exports = __toCommonJS(use_coagent_action_exports);
56
+ var import_react2 = require("react");
56
57
 
57
58
  // src/context/copilot-context.tsx
58
59
  var import_react = __toESM(require("react"));
@@ -62,7 +63,12 @@ var emptyCopilotContext = {
62
63
  },
63
64
  removeAction: () => {
64
65
  },
65
- chatComponentsCache: { current: { actions: {}, chatUI: {} } },
66
+ coagentActions: {},
67
+ setCoagentAction: () => {
68
+ },
69
+ removeCoagentAction: () => {
70
+ },
71
+ chatComponentsCache: { current: { actions: {}, coagentActions: {} } },
66
72
  getContextString: (documents, categories) => returnAndThrowInDebug(""),
67
73
  addContext: () => "",
68
74
  removeContext: () => {
@@ -96,35 +102,55 @@ var emptyCopilotContext = {
96
102
  removeChatSuggestionConfiguration: () => {
97
103
  },
98
104
  showDevConsole: "auto",
99
- agentStates: {},
100
- setAgentStates: () => {
105
+ coagentStates: {},
106
+ setCoagentStates: () => {
101
107
  },
102
- chatUI: [],
103
- setChatUI: () => {
108
+ agentSession: null,
109
+ setAgentSession: () => {
104
110
  }
105
111
  };
106
112
  var CopilotContext = import_react.default.createContext(emptyCopilotContext);
107
- function useCopilotContext() {
108
- return import_react.default.useContext(CopilotContext);
109
- }
110
113
  function returnAndThrowInDebug(value) {
111
114
  throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
112
115
  return value;
113
116
  }
114
117
 
115
- // src/hooks/use-copilot-chat-ui.ts
116
- var import_react2 = require("react");
117
- function useCopilotChatUI(chatUI, dependencies) {
118
- const { chatUI: chatUIFromContext, setChatUI } = useCopilotContext();
118
+ // src/hooks/use-coagent-action.ts
119
+ var import_shared = require("@copilotkit/shared");
120
+ function useCoagentAction(action, dependencies) {
121
+ const { setCoagentAction, removeCoagentAction, coagentActions, chatComponentsCache } = (0, import_react2.useContext)(CopilotContext);
122
+ const idRef = (0, import_react2.useRef)((0, import_shared.randomId)());
123
+ const key = `${action.name}-${action.nodeName || "global"}`;
124
+ if (dependencies === void 0) {
125
+ if (coagentActions[idRef.current]) {
126
+ coagentActions[idRef.current].handler = action.handler;
127
+ if (typeof action.render === "function") {
128
+ if (chatComponentsCache.current !== null) {
129
+ chatComponentsCache.current.coagentActions[key] = action.render;
130
+ }
131
+ }
132
+ }
133
+ }
119
134
  (0, import_react2.useEffect)(() => {
120
- setChatUI([...chatUIFromContext, chatUI]);
135
+ setCoagentAction(idRef.current, action);
136
+ if (chatComponentsCache.current !== null && action.render !== void 0) {
137
+ chatComponentsCache.current.coagentActions[key] = action.render;
138
+ }
121
139
  return () => {
122
- setChatUI(chatUIFromContext.filter((ui) => ui !== chatUI));
140
+ removeCoagentAction(idRef.current);
123
141
  };
124
- }, [chatUI.agentName, chatUI.nodeName, setChatUI]);
142
+ }, [
143
+ setCoagentAction,
144
+ removeCoagentAction,
145
+ action.name,
146
+ // include render only if it's a string
147
+ typeof action.render === "string" ? action.render : void 0,
148
+ // dependencies set by the developer
149
+ ...dependencies || []
150
+ ]);
125
151
  }
126
152
  // Annotate the CommonJS export names for ESM import in node:
127
153
  0 && (module.exports = {
128
- useCopilotChatUI
154
+ useCoagentAction
129
155
  });
130
- //# sourceMappingURL=use-copilot-chat-ui.js.map
156
+ //# sourceMappingURL=use-coagent-action.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/hooks/use-coagent-action.ts","../../src/context/copilot-context.tsx"],"sourcesContent":["import { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { CoagentAction } from \"../types/coagent-action\";\n\n// We implement useCoagentAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// see useCopilotAction for more details about this approach.\nexport function useCoagentAction<T = any>(action: CoagentAction<T>, dependencies?: any[]): void {\n const { setCoagentAction, removeCoagentAction, coagentActions, chatComponentsCache } =\n useContext(CopilotContext);\n const idRef = useRef<string>(randomId());\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coagentActions[idRef.current]) {\n coagentActions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coagentActions[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setCoagentAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coagentActions[key] = action.render;\n }\n return () => {\n removeCoagentAction(idRef.current);\n };\n }, [\n setCoagentAction,\n removeCoagentAction,\n action.name,\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","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\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 { CoagentAction, CoagentActionRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\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: CoagentActionRenderProps<any>,\n) => string | JSX.Element;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coagentActions: 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 coagentActions: Record<string, CoagentAction<any>>;\n setCoagentAction: (id: string, action: CoagentAction<any>) => void;\n removeCoagentAction: (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 // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\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 agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coagentActions: {},\n setCoagentAction: () => {},\n removeCoagentAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, coagentActions: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\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\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\n agentSession: null,\n setAgentSession: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\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":";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2
+ useCoagentAction
3
+ } from "../chunk-IQH77T4S.mjs";
4
+ import "../chunk-LTA2O5WH.mjs";
5
+ import "../chunk-SKC7AJIV.mjs";
6
+ export {
7
+ useCoagentAction
8
+ };
9
+ //# sourceMappingURL=use-coagent-action.mjs.map
@@ -1,11 +1,17 @@
1
- declare function useCoagent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T>;
2
- declare function useCopilotAction<T = any>(coagentAction: CoagentAction<T>): void;
3
- interface UseCoagentOptions<T> {
1
+ interface WithInternalStateManagementAndInitial<T> {
2
+ name: string;
3
+ initialState: T;
4
+ }
5
+ interface WithInternalStateManagement {
4
6
  name: string;
5
- initialState?: T;
6
- state?: T;
7
- setState?: (newState: T | ((prevState: T | undefined) => T)) => void;
7
+ initialState?: any;
8
+ }
9
+ interface WithExternalStateManagement<T> {
10
+ name: string;
11
+ state: T;
12
+ setState: (newState: T | ((prevState: T | undefined) => T)) => void;
8
13
  }
14
+ type UseCoagentOptions<T> = WithInternalStateManagementAndInitial<T> | WithInternalStateManagement | WithExternalStateManagement<T>;
9
15
  interface UseCoagentReturnType<T> {
10
16
  name: string;
11
17
  nodeName?: string;
@@ -16,16 +22,6 @@ interface UseCoagentReturnType<T> {
16
22
  start: () => void;
17
23
  stop: () => void;
18
24
  }
19
- interface CoagentActionRenderProps<T> {
20
- status: "executing" | "complete" | "in_progress";
21
- args: T;
22
- result: any;
23
- }
24
- interface CoagentAction<T> {
25
- name: string;
26
- nodeName?: string;
27
- handler?: (args: T) => any | Promise<any>;
28
- render?: (props: CoagentActionRenderProps<T>) => string | React.ReactElement;
29
- }
25
+ declare function useCoagent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T>;
30
26
 
31
- export { CoagentAction, CoagentActionRenderProps, UseCoagentOptions, UseCoagentReturnType, useCoagent, useCopilotAction };
27
+ export { UseCoagentReturnType, useCoagent };
@@ -1,8 +1,27 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
3
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
7
  var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
5
10
  var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
6
25
  var __export = (target, all) => {
7
26
  for (var name in all)
8
27
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -15,34 +34,182 @@ var __copyProps = (to, from, except, desc) => {
15
34
  }
16
35
  return to;
17
36
  };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
18
45
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+ var __async = (__this, __arguments, generator) => {
47
+ return new Promise((resolve, reject) => {
48
+ var fulfilled = (value) => {
49
+ try {
50
+ step(generator.next(value));
51
+ } catch (e) {
52
+ reject(e);
53
+ }
54
+ };
55
+ var rejected = (value) => {
56
+ try {
57
+ step(generator.throw(value));
58
+ } catch (e) {
59
+ reject(e);
60
+ }
61
+ };
62
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
63
+ step((generator = generator.apply(__this, __arguments)).next());
64
+ });
65
+ };
19
66
 
20
67
  // src/hooks/use-coagent.ts
21
68
  var use_coagent_exports = {};
22
69
  __export(use_coagent_exports, {
23
- useCoagent: () => useCoagent,
24
- useCopilotAction: () => useCopilotAction
70
+ useCoagent: () => useCoagent
25
71
  });
26
72
  module.exports = __toCommonJS(use_coagent_exports);
27
- var import_react = require("react");
73
+ var import_react2 = require("react");
74
+
75
+ // src/context/copilot-context.tsx
76
+ var import_react = __toESM(require("react"));
77
+ var emptyCopilotContext = {
78
+ actions: {},
79
+ setAction: () => {
80
+ },
81
+ removeAction: () => {
82
+ },
83
+ coagentActions: {},
84
+ setCoagentAction: () => {
85
+ },
86
+ removeCoagentAction: () => {
87
+ },
88
+ chatComponentsCache: { current: { actions: {}, coagentActions: {} } },
89
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
90
+ addContext: () => "",
91
+ removeContext: () => {
92
+ },
93
+ getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
94
+ })),
95
+ messages: [],
96
+ setMessages: () => returnAndThrowInDebug([]),
97
+ isLoading: false,
98
+ setIsLoading: () => returnAndThrowInDebug(false),
99
+ chatInstructions: "",
100
+ setChatInstructions: () => returnAndThrowInDebug(""),
101
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
102
+ addDocumentContext: () => returnAndThrowInDebug(""),
103
+ removeDocumentContext: () => {
104
+ },
105
+ copilotApiConfig: new class {
106
+ get chatApiEndpoint() {
107
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
108
+ }
109
+ get headers() {
110
+ return {};
111
+ }
112
+ get body() {
113
+ return {};
114
+ }
115
+ }(),
116
+ chatSuggestionConfiguration: {},
117
+ addChatSuggestionConfiguration: () => {
118
+ },
119
+ removeChatSuggestionConfiguration: () => {
120
+ },
121
+ showDevConsole: "auto",
122
+ coagentStates: {},
123
+ setCoagentStates: () => {
124
+ },
125
+ agentSession: null,
126
+ setAgentSession: () => {
127
+ }
128
+ };
129
+ var CopilotContext = import_react.default.createContext(emptyCopilotContext);
130
+ function useCopilotContext() {
131
+ return import_react.default.useContext(CopilotContext);
132
+ }
133
+ function returnAndThrowInDebug(value) {
134
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
135
+ return value;
136
+ }
137
+
138
+ // src/hooks/use-coagent.ts
28
139
  function useCoagent(options) {
29
- throw new Error("Not implemented");
140
+ const isExternalStateManagement = (options2) => {
141
+ return "state" in options2 && "setState" in options2;
142
+ };
143
+ const { name } = options;
144
+ const isInternalStateManagementWithInitial = (options2) => {
145
+ return "initialState" in options2;
146
+ };
147
+ const { coagentStates, setCoagentStates } = useCopilotContext();
148
+ const getCoagentState = (coagentStates2, name2) => {
149
+ if (coagentStates2[name2]) {
150
+ return coagentStates2[name2];
151
+ } else {
152
+ return {
153
+ name: name2,
154
+ state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
155
+ running: false,
156
+ active: false,
157
+ threadId: void 0,
158
+ nodeName: void 0,
159
+ runId: void 0
160
+ };
161
+ }
162
+ };
163
+ const setState = (newState) => {
164
+ setCoagentStates((prevAgentStates) => {
165
+ let coagentState2 = getCoagentState(prevAgentStates, name);
166
+ const updatedState = typeof newState === "function" ? newState(coagentState2.state) : newState;
167
+ return __spreadProps(__spreadValues({}, prevAgentStates), {
168
+ [name]: __spreadProps(__spreadValues({}, coagentState2), {
169
+ state: updatedState
170
+ })
171
+ });
172
+ });
173
+ };
174
+ const coagentState = getCoagentState(coagentStates, name);
175
+ const state = isExternalStateManagement(options) ? options.state : coagentState.state;
176
+ (0, import_react2.useEffect)(() => {
177
+ if (isExternalStateManagement(options)) {
178
+ setState(options.state);
179
+ } else if (coagentStates[name] === void 0) {
180
+ setState(options.initialState === void 0 ? {} : options.initialState);
181
+ }
182
+ }, [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]);
183
+ return {
184
+ name,
185
+ nodeName: coagentState.nodeName,
186
+ state,
187
+ setState,
188
+ running: coagentState.running,
189
+ start: () => {
190
+ startAgent(name);
191
+ },
192
+ stop: () => {
193
+ stopAgent(name);
194
+ }
195
+ };
30
196
  }
31
- var [appState, setAppState] = (0, import_react.useState)({
32
- story: "dasfsdf"
33
- });
34
- var [story, setStory] = (0, import_react.useState)({
35
- story: "dasfsdf"
36
- });
37
- var { nodeName } = useCoagent({
38
- name: "myAgent"
39
- });
40
- function useCopilotAction(coagentAction) {
41
- throw new Error("Not implemented");
197
+ function startAgent(name) {
198
+ const { setAgentSession } = useCopilotContext();
199
+ setAgentSession({
200
+ agentName: name
201
+ });
202
+ }
203
+ function stopAgent(name) {
204
+ const { agentSession, setAgentSession } = useCopilotContext();
205
+ if (agentSession && agentSession.agentName === name) {
206
+ setAgentSession(null);
207
+ } else {
208
+ console.warn(`No agent session found for ${name}`);
209
+ }
42
210
  }
43
211
  // Annotate the CommonJS export names for ESM import in node:
44
212
  0 && (module.exports = {
45
- useCoagent,
46
- useCopilotAction
213
+ useCoagent
47
214
  });
48
215
  //# sourceMappingURL=use-coagent.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-coagent.ts"],"sourcesContent":["import { useState } from \"react\";\n\nexport function useCoagent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n throw new Error(\"Not implemented\");\n}\n\nconst [appState, setAppState] = useState({\n story: \"dasfsdf\",\n});\n\nconst [story, setStory] = useState({\n story: \"dasfsdf\",\n});\n\nconst { nodeName } = useCoagent({\n name: \"myAgent\",\n});\n\n// what do we need from useCoagent?\n// - nodeName\n// - threadId\n// - running\n// - state\n\nexport function useCopilotAction<T = any>(coagentAction: CoagentAction<T>) {\n throw new Error(\"Not implemented\");\n}\n\n// <CopilotKit agent=\"lockedInAgentName\" />\n\nexport interface UseCoagentOptions<T> {\n name: string;\n initialState?: T;\n state?: T;\n setState?: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\nexport interface UseCoagentReturnType<T> {\n name: string;\n nodeName?: string;\n threadId?: string;\n running: boolean;\n state: T;\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n start: () => void;\n stop: () => void;\n}\n\nexport interface CoagentActionRenderProps<T> {\n status: \"executing\" | \"complete\" | \"in_progress\";\n args: T;\n result: any;\n}\n\nexport interface CoagentAction<T> {\n name: string;\n nodeName?: string;\n handler?: (args: T) => any | Promise<any>;\n render?: (props: CoagentActionRenderProps<T>) => string | React.ReactElement;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAyB;AAElB,SAAS,WAAoB,SAAwD;AAC1F,QAAM,IAAI,MAAM,iBAAiB;AACnC;AAEA,IAAM,CAAC,UAAU,WAAW,QAAI,uBAAS;AAAA,EACvC,OAAO;AACT,CAAC;AAED,IAAM,CAAC,OAAO,QAAQ,QAAI,uBAAS;AAAA,EACjC,OAAO;AACT,CAAC;AAED,IAAM,EAAE,SAAS,IAAI,WAAW;AAAA,EAC9B,MAAM;AACR,CAAC;AAQM,SAAS,iBAA0B,eAAiC;AACzE,QAAM,IAAI,MAAM,iBAAiB;AACnC;","names":[]}
1
+ {"version":3,"sources":["../../src/hooks/use-coagent.ts","../../src/context/copilot-context.tsx"],"sourcesContent":["import { useEffect } from \"react\";\nimport { useCopilotContext } from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\n\ninterface WithInternalStateManagementAndInitial<T> {\n name: string;\n initialState: T;\n}\n\ninterface WithInternalStateManagement {\n name: string;\n initialState?: any; // Optional initialState with default type any\n}\n\ninterface WithExternalStateManagement<T> {\n name: string;\n state: T;\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n name: string;\n nodeName?: string;\n threadId?: string;\n running: boolean;\n state: T;\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n start: () => void;\n stop: () => void;\n}\n\nexport function useCoagent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const isExternalStateManagement = (\n options: UseCoagentOptions<T>,\n ): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n };\n\n const { name } = options;\n\n const isInternalStateManagementWithInitial = (\n options: UseCoagentOptions<T>,\n ): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n };\n\n const { coagentStates, setCoagentStates } = useCopilotContext();\n\n const getCoagentState = (coagentStates: Record<string, CoagentState>, name: string) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial(options) ? options.initialState : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n };\n\n // if we manage state internally, we need to provide a function to set the state\n const setState = (newState: T | ((prevState: T | undefined) => T)) => {\n setCoagentStates((prevAgentStates) => {\n let coagentState: CoagentState = getCoagentState(prevAgentStates, name);\n\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(coagentState.state) : newState;\n\n return {\n ...prevAgentStates,\n [name]: {\n ...coagentState,\n state: updatedState,\n },\n };\n });\n };\n\n const coagentState = getCoagentState(coagentStates, name);\n\n const state = isExternalStateManagement(options) ? options.state : coagentState.state;\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n setState(options.state);\n } else if (coagentStates[name] === undefined) {\n setState(options.initialState === undefined ? {} : options.initialState);\n }\n }, [isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined]);\n\n // Return the state and setState function\n return {\n name,\n nodeName: coagentState.nodeName,\n state,\n setState,\n running: coagentState.running,\n start: () => {\n startAgent(name);\n },\n stop: () => {\n stopAgent(name);\n },\n };\n}\n\nfunction startAgent(name: string) {\n const { setAgentSession } = useCopilotContext();\n setAgentSession({\n agentName: name,\n });\n}\n\nfunction stopAgent(name: string) {\n const { agentSession, setAgentSession } = useCopilotContext();\n if (agentSession && agentSession.agentName === name) {\n setAgentSession(null);\n } else {\n console.warn(`No agent session found for ${name}`);\n }\n}\n\n// <CopilotKit agent=\"lockedInAgentName\" />\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\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 { CoagentAction, CoagentActionRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\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: CoagentActionRenderProps<any>,\n) => string | JSX.Element;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coagentActions: 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 coagentActions: Record<string, CoagentAction<any>>;\n setCoagentAction: (id: string, action: CoagentAction<any>) => void;\n removeCoagentAction: (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 // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\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 agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coagentActions: {},\n setCoagentAction: () => {},\n removeCoagentAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, coagentActions: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\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\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\n agentSession: null,\n setAgentSession: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\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;A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Ae,IAAI;AAExD,QAAM,QAAQ,0BAA0B,OAAO,IAAI,QAAQ,QAAQ,aAAa;AAGhF,+BAAU,MAAM;AACd,QAAI,0BAA0B,OAAO,GAAG;AACtC,eAAS,QAAQ,KAAK;AAAA,IACxB,WAAW,cAAc,IAAI,MAAM,QAAW;AAC5C,eAAS,QAAQ,iBAAiB,SAAY,CAAC,IAAI,QAAQ,YAAY;AAAA,IACzE;AAAA,EACF,GAAG,CAAC,0BAA0B,OAAO,IAAI,KAAK,UAAU,QAAQ,KAAK,IAAI,MAAS,CAAC;AAGnF,SAAO;AAAA,IACL;AAAA,IACA,UAAU,aAAa;AAAA,IACvB;AAAA,IACA;AAAA,IACA,SAAS,aAAa;AAAA,IACtB,OAAO,MAAM;AACX,iBAAW,IAAI;AAAA,IACjB;AAAA,IACA,MAAM,MAAM;AACV,gBAAU,IAAI;AAAA,IAChB;AAAA,EACF;AACF;AAEA,SAAS,WAAW,MAAc;AAChC,QAAM,EAAE,gBAAgB,IAAI,kBAAkB;AAC9C,kBAAgB;AAAA,IACd,WAAW;AAAA,EACb,CAAC;AACH;AAEA,SAAS,UAAU,MAAc;AAC/B,QAAM,EAAE,cAAc,gBAAgB,IAAI,kBAAkB;AAC5D,MAAI,gBAAgB,aAAa,cAAc,MAAM;AACnD,oBAAgB,IAAI;AAAA,EACtB,OAAO;AACL,YAAQ,KAAK,8BAA8B,MAAM;AAAA,EACnD;AACF;","names":["import_react","React","options","coagentStates","name","coagentState"]}
@@ -1,24 +1,10 @@
1
+ import {
2
+ useCoagent
3
+ } from "../chunk-MTOHRBPJ.mjs";
4
+ import "../chunk-VNRDQJXW.mjs";
5
+ import "../chunk-LTA2O5WH.mjs";
1
6
  import "../chunk-SKC7AJIV.mjs";
2
-
3
- // src/hooks/use-coagent.ts
4
- import { useState } from "react";
5
- function useCoagent(options) {
6
- throw new Error("Not implemented");
7
- }
8
- var [appState, setAppState] = useState({
9
- story: "dasfsdf"
10
- });
11
- var [story, setStory] = useState({
12
- story: "dasfsdf"
13
- });
14
- var { nodeName } = useCoagent({
15
- name: "myAgent"
16
- });
17
- function useCopilotAction(coagentAction) {
18
- throw new Error("Not implemented");
19
- }
20
7
  export {
21
- useCoagent,
22
- useCopilotAction
8
+ useCoagent
23
9
  };
24
10
  //# sourceMappingURL=use-coagent.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-coagent.ts"],"sourcesContent":["import { useState } from \"react\";\n\nexport function useCoagent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n throw new Error(\"Not implemented\");\n}\n\nconst [appState, setAppState] = useState({\n story: \"dasfsdf\",\n});\n\nconst [story, setStory] = useState({\n story: \"dasfsdf\",\n});\n\nconst { nodeName } = useCoagent({\n name: \"myAgent\",\n});\n\n// what do we need from useCoagent?\n// - nodeName\n// - threadId\n// - running\n// - state\n\nexport function useCopilotAction<T = any>(coagentAction: CoagentAction<T>) {\n throw new Error(\"Not implemented\");\n}\n\n// <CopilotKit agent=\"lockedInAgentName\" />\n\nexport interface UseCoagentOptions<T> {\n name: string;\n initialState?: T;\n state?: T;\n setState?: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\nexport interface UseCoagentReturnType<T> {\n name: string;\n nodeName?: string;\n threadId?: string;\n running: boolean;\n state: T;\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n start: () => void;\n stop: () => void;\n}\n\nexport interface CoagentActionRenderProps<T> {\n status: \"executing\" | \"complete\" | \"in_progress\";\n args: T;\n result: any;\n}\n\nexport interface CoagentAction<T> {\n name: string;\n nodeName?: string;\n handler?: (args: T) => any | Promise<any>;\n render?: (props: CoagentActionRenderProps<T>) => string | React.ReactElement;\n}\n"],"mappings":";;;AAAA,SAAS,gBAAgB;AAElB,SAAS,WAAoB,SAAwD;AAC1F,QAAM,IAAI,MAAM,iBAAiB;AACnC;AAEA,IAAM,CAAC,UAAU,WAAW,IAAI,SAAS;AAAA,EACvC,OAAO;AACT,CAAC;AAED,IAAM,CAAC,OAAO,QAAQ,IAAI,SAAS;AAAA,EACjC,OAAO;AACT,CAAC;AAED,IAAM,EAAE,SAAS,IAAI,WAAW;AAAA,EAC9B,MAAM;AACR,CAAC;AAQM,SAAS,iBAA0B,eAAiC;AACzE,QAAM,IAAI,MAAM,iBAAiB;AACnC;","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -63,7 +63,12 @@ var emptyCopilotContext = {
63
63
  },
64
64
  removeAction: () => {
65
65
  },
66
- chatComponentsCache: { current: { actions: {}, chatUI: {} } },
66
+ coagentActions: {},
67
+ setCoagentAction: () => {
68
+ },
69
+ removeCoagentAction: () => {
70
+ },
71
+ chatComponentsCache: { current: { actions: {}, coagentActions: {} } },
67
72
  getContextString: (documents, categories) => returnAndThrowInDebug(""),
68
73
  addContext: () => "",
69
74
  removeContext: () => {
@@ -97,11 +102,11 @@ var emptyCopilotContext = {
97
102
  removeChatSuggestionConfiguration: () => {
98
103
  },
99
104
  showDevConsole: "auto",
100
- agentStates: {},
101
- setAgentStates: () => {
105
+ coagentStates: {},
106
+ setCoagentStates: () => {
102
107
  },
103
- chatUI: [],
104
- setChatUI: () => {
108
+ agentSession: null,
109
+ setAgentSession: () => {
105
110
  }
106
111
  };
107
112
  var CopilotContext = import_react.default.createContext(emptyCopilotContext);