@copilotkitnext/react 1.52.0 → 1.52.1-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.
- package/dist/index.umd.js +9 -5
- package/dist/index.umd.js.map +1 -1
- package/dist/providers/CopilotKitProvider.cjs +9 -5
- package/dist/providers/CopilotKitProvider.cjs.map +1 -1
- package/dist/providers/CopilotKitProvider.d.cts +1 -0
- package/dist/providers/CopilotKitProvider.d.cts.map +1 -1
- package/dist/providers/CopilotKitProvider.d.mts +1 -0
- package/dist/providers/CopilotKitProvider.d.mts.map +1 -1
- package/dist/providers/CopilotKitProvider.mjs +9 -5
- package/dist/providers/CopilotKitProvider.mjs.map +1 -1
- package/package.json +6 -6
|
@@ -24,7 +24,7 @@ function useStableArrayProp(prop, warningMessage, isMeaningfulChange) {
|
|
|
24
24
|
}, [value, warningMessage]);
|
|
25
25
|
return value;
|
|
26
26
|
}
|
|
27
|
-
const CopilotKitProvider = ({ children, runtimeUrl, headers = {}, credentials, publicApiKey, publicLicenseKey, properties = {}, agents__unsafe_dev_only: agents = {}, renderToolCalls, renderActivityMessages, renderCustomMessages, frontendTools, humanInTheLoop, showDevConsole = false, useSingleEndpoint = false }) => {
|
|
27
|
+
const CopilotKitProvider = ({ children, runtimeUrl, headers = {}, credentials, publicApiKey, publicLicenseKey, properties = {}, agents__unsafe_dev_only: agents = {}, selfManagedAgents = {}, renderToolCalls, renderActivityMessages, renderCustomMessages, frontendTools, humanInTheLoop, showDevConsole = false, useSingleEndpoint = false }) => {
|
|
28
28
|
const [shouldRenderInspector, setShouldRenderInspector] = (0, react.useState)(false);
|
|
29
29
|
(0, react.useEffect)(() => {
|
|
30
30
|
if (typeof window === "undefined") return;
|
|
@@ -53,7 +53,11 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers = {}, credentials, p
|
|
|
53
53
|
return [...renderActivityMessagesList, ...builtInActivityRenderers];
|
|
54
54
|
}, [renderActivityMessagesList, builtInActivityRenderers]);
|
|
55
55
|
const resolvedPublicKey = publicApiKey ?? publicLicenseKey;
|
|
56
|
-
const
|
|
56
|
+
const mergedAgents = (0, react.useMemo)(() => ({
|
|
57
|
+
...agents,
|
|
58
|
+
...selfManagedAgents
|
|
59
|
+
}), [agents, selfManagedAgents]);
|
|
60
|
+
const hasLocalAgents = mergedAgents && Object.keys(mergedAgents).length > 0;
|
|
57
61
|
const mergedHeaders = (0, react.useMemo)(() => {
|
|
58
62
|
if (!resolvedPublicKey) return headers;
|
|
59
63
|
if (headers[HEADER_NAME]) return headers;
|
|
@@ -132,7 +136,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers = {}, credentials, p
|
|
|
132
136
|
headers: mergedHeaders,
|
|
133
137
|
credentials,
|
|
134
138
|
properties,
|
|
135
|
-
agents__unsafe_dev_only:
|
|
139
|
+
agents__unsafe_dev_only: mergedAgents,
|
|
136
140
|
tools: allTools,
|
|
137
141
|
renderToolCalls: allRenderToolCalls,
|
|
138
142
|
renderActivityMessages: allActivityRenderers,
|
|
@@ -184,13 +188,13 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers = {}, credentials, p
|
|
|
184
188
|
copilotkit.setHeaders(mergedHeaders);
|
|
185
189
|
copilotkit.setCredentials(credentials);
|
|
186
190
|
copilotkit.setProperties(properties);
|
|
187
|
-
copilotkit.setAgents__unsafe_dev_only(
|
|
191
|
+
copilotkit.setAgents__unsafe_dev_only(mergedAgents);
|
|
188
192
|
}, [
|
|
189
193
|
chatApiEndpoint,
|
|
190
194
|
mergedHeaders,
|
|
191
195
|
credentials,
|
|
192
196
|
properties,
|
|
193
|
-
|
|
197
|
+
mergedAgents,
|
|
194
198
|
useSingleEndpoint
|
|
195
199
|
]);
|
|
196
200
|
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotKitContext.Provider, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CopilotKitProvider.cjs","names":["MCPAppsActivityType","MCPAppsActivityContentSchema","MCPAppsActivityRenderer","z","CopilotKitCoreReact","CopilotKitInspector"],"sources":["../../src/providers/CopilotKitProvider.tsx"],"sourcesContent":["\"use client\";\n\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { FrontendTool } from \"@copilotkitnext/core\";\nimport type React from \"react\";\nimport {\n createContext,\n useContext,\n type ReactNode,\n useMemo,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from \"react\";\nimport { z } from \"zod\";\nimport { CopilotKitInspector } from \"../components/CopilotKitInspector\";\nimport {\n MCPAppsActivityContentSchema,\n MCPAppsActivityRenderer,\n MCPAppsActivityType,\n} from \"../components/MCPAppsActivityRenderer\";\nimport { CopilotKitCoreReact } from \"../lib/react-core\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\n\nconst HEADER_NAME = \"X-CopilotCloud-Public-Api-Key\";\nconst COPILOT_CLOUD_CHAT_URL = \"https://api.cloud.copilotkit.ai/copilotkit/v1\";\n\n// Define the context value interface - idiomatic React naming\nexport interface CopilotKitContextValue {\n copilotkit: CopilotKitCoreReact;\n /**\n * Set of tool call IDs currently being executed.\n * This is tracked at the provider level to ensure tool execution events\n * are captured even before child components mount.\n */\n executingToolCallIds: ReadonlySet<string>;\n}\n\n// Empty set for default context value\nconst EMPTY_SET: ReadonlySet<string> = new Set();\n\n// Create the CopilotKit context\nconst CopilotKitContext = createContext<CopilotKitContextValue>({\n copilotkit: null!,\n executingToolCallIds: EMPTY_SET,\n});\n\n// Provider props interface\nexport interface CopilotKitProviderProps {\n children: ReactNode;\n runtimeUrl?: string;\n headers?: Record<string, string>;\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /**\n * The Copilot Cloud public API key.\n */\n publicApiKey?: string;\n /**\n * Alias for `publicApiKey`\n **/\n publicLicenseKey?: string;\n properties?: Record<string, unknown>;\n useSingleEndpoint?: boolean;\n agents__unsafe_dev_only?: Record<string, AbstractAgent>;\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n renderCustomMessages?: ReactCustomMessageRenderer[];\n frontendTools?: ReactFrontendTool[];\n humanInTheLoop?: ReactHumanInTheLoop[];\n showDevConsole?: boolean | \"auto\";\n}\n\n// Small helper to normalize array props to a stable reference and warn\nfunction useStableArrayProp<T>(\n prop: T[] | undefined,\n warningMessage?: string,\n isMeaningfulChange?: (initial: T[], next: T[]) => boolean,\n): T[] {\n const empty = useMemo<T[]>(() => [], []);\n const value = prop ?? empty;\n const initial = useRef(value);\n\n useEffect(() => {\n if (\n warningMessage &&\n value !== initial.current &&\n (isMeaningfulChange ? isMeaningfulChange(initial.current, value) : true)\n ) {\n console.error(warningMessage);\n }\n }, [value, warningMessage]);\n\n return value;\n}\n\n// Provider component\nexport const CopilotKitProvider: React.FC<CopilotKitProviderProps> = ({\n children,\n runtimeUrl,\n headers = {},\n credentials,\n publicApiKey,\n publicLicenseKey,\n properties = {},\n agents__unsafe_dev_only: agents = {},\n renderToolCalls,\n renderActivityMessages,\n renderCustomMessages,\n frontendTools,\n humanInTheLoop,\n showDevConsole = false,\n useSingleEndpoint = false,\n}) => {\n const [shouldRenderInspector, setShouldRenderInspector] = useState(false);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n return;\n }\n\n if (showDevConsole === true) {\n // Explicitly show the inspector\n setShouldRenderInspector(true);\n } else if (showDevConsole === \"auto\") {\n // Show on localhost or 127.0.0.1 only\n const localhostHosts = new Set([\"localhost\", \"127.0.0.1\"]);\n if (localhostHosts.has(window.location.hostname)) {\n setShouldRenderInspector(true);\n } else {\n setShouldRenderInspector(false);\n }\n } else {\n // showDevConsole is false or undefined (default false)\n setShouldRenderInspector(false);\n }\n }, [showDevConsole]);\n\n // Normalize array props to stable references with clear dev warnings\n const renderToolCallsList = useStableArrayProp<ReactToolCallRenderer<any>>(\n renderToolCalls,\n \"renderToolCalls must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n (initial, next) => {\n // Only warn if the shape (names+agentId) changed. Allow identity changes\n // to support updated closures from parents (e.g., Storybook state).\n const key = (rc?: ReactToolCallRenderer<unknown>) =>\n `${rc?.agentId ?? \"\"}:${rc?.name ?? \"\"}`;\n const setFrom = (arr: ReactToolCallRenderer<unknown>[]) =>\n new Set(arr.map(key));\n const a = setFrom(initial);\n const b = setFrom(next);\n if (a.size !== b.size) return true;\n for (const k of a) if (!b.has(k)) return true;\n return false;\n },\n );\n\n const renderCustomMessagesList =\n useStableArrayProp<ReactCustomMessageRenderer>(\n renderCustomMessages,\n \"renderCustomMessages must be a stable array.\",\n );\n\n const renderActivityMessagesList = useStableArrayProp<\n ReactActivityMessageRenderer<any>\n >(renderActivityMessages, \"renderActivityMessages must be a stable array.\");\n\n // Built-in activity renderers that are always included\n const builtInActivityRenderers = useMemo<ReactActivityMessageRenderer<any>[]>(\n () => [\n {\n activityType: MCPAppsActivityType,\n content: MCPAppsActivityContentSchema,\n render: MCPAppsActivityRenderer,\n },\n ],\n [],\n );\n\n // Combine user-provided activity renderers with built-in ones\n // User-provided renderers take precedence (come first) so they can override built-ins\n const allActivityRenderers = useMemo(() => {\n return [...renderActivityMessagesList, ...builtInActivityRenderers];\n }, [renderActivityMessagesList, builtInActivityRenderers]);\n\n const resolvedPublicKey = publicApiKey ?? publicLicenseKey;\n const hasLocalAgents = agents && Object.keys(agents).length > 0;\n\n // Merge a provided publicApiKey into headers (without overwriting an explicit header).\n const mergedHeaders = useMemo(() => {\n if (!resolvedPublicKey) return headers;\n if (headers[HEADER_NAME]) return headers;\n return {\n ...headers,\n [HEADER_NAME]: resolvedPublicKey,\n };\n }, [headers, resolvedPublicKey]);\n\n if (!runtimeUrl && !resolvedPublicKey && !hasLocalAgents) {\n const message =\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\";\n if (process.env.NODE_ENV === \"production\") {\n throw new Error(message);\n } else {\n // In dev/test we warn but allow to facilitate local agents and unit tests.\n console.warn(message);\n }\n }\n\n const chatApiEndpoint =\n runtimeUrl ?? (resolvedPublicKey ? COPILOT_CLOUD_CHAT_URL : undefined);\n\n const frontendToolsList = useStableArrayProp<ReactFrontendTool>(\n frontendTools,\n \"frontendTools must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n );\n const humanInTheLoopList = useStableArrayProp<ReactHumanInTheLoop>(\n humanInTheLoop,\n \"humanInTheLoop must be a stable array. If you want to dynamically add or remove human-in-the-loop tools, use `useHumanInTheLoop` instead.\",\n );\n\n // Note: warnings for array identity changes are handled by useStableArrayProp\n\n // Process humanInTheLoop tools to create handlers and add render components\n const processedHumanInTheLoopTools = useMemo(() => {\n const processedTools: FrontendTool[] = [];\n const processedRenderToolCalls: ReactToolCallRenderer<unknown>[] = [];\n\n humanInTheLoopList.forEach((tool) => {\n // Create a promise-based handler for each human-in-the-loop tool\n const frontendTool: FrontendTool = {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n followUp: tool.followUp,\n ...(tool.agentId && { agentId: tool.agentId }),\n handler: async () => {\n // This handler will be replaced by the hook when it runs\n // For provider-level tools, we create a basic handler that waits for user interaction\n return new Promise((resolve) => {\n // The actual implementation will be handled by the render component\n // This is a placeholder that the hook will override\n console.warn(\n `Human-in-the-loop tool '${tool.name}' called but no interactive handler is set up.`,\n );\n resolve(undefined);\n });\n },\n };\n processedTools.push(frontendTool);\n\n // Add the render component to renderToolCalls\n if (tool.render) {\n processedRenderToolCalls.push({\n name: tool.name,\n args: tool.parameters!,\n render: tool.render,\n ...(tool.agentId && { agentId: tool.agentId }),\n } as ReactToolCallRenderer<unknown>);\n }\n });\n\n return { tools: processedTools, renderToolCalls: processedRenderToolCalls };\n }, [humanInTheLoopList]);\n\n // Combine all tools for CopilotKitCore\n const allTools = useMemo(() => {\n const tools: FrontendTool[] = [];\n\n // Add frontend tools\n tools.push(...frontendToolsList);\n\n // Add processed human-in-the-loop tools\n tools.push(...processedHumanInTheLoopTools.tools);\n\n return tools;\n }, [frontendToolsList, processedHumanInTheLoopTools]);\n\n // Combine all render tool calls\n const allRenderToolCalls = useMemo(() => {\n const combined: ReactToolCallRenderer<unknown>[] = [...renderToolCallsList];\n\n // Add render components from frontend tools\n frontendToolsList.forEach((tool) => {\n if (tool.render) {\n // For wildcard tools without parameters, default to z.any()\n const args =\n tool.parameters || (tool.name === \"*\" ? z.any() : undefined);\n if (args) {\n combined.push({\n name: tool.name,\n args: args,\n render: tool.render,\n } as ReactToolCallRenderer<unknown>);\n }\n }\n });\n\n // Add render components from human-in-the-loop tools\n combined.push(...processedHumanInTheLoopTools.renderToolCalls);\n\n return combined;\n }, [renderToolCallsList, frontendToolsList, processedHumanInTheLoopTools]);\n\n const copilotkit = useMemo(() => {\n const copilotkit = new CopilotKitCoreReact({\n runtimeUrl: chatApiEndpoint,\n runtimeTransport: useSingleEndpoint ? \"single\" : \"rest\",\n headers: mergedHeaders,\n credentials,\n properties,\n agents__unsafe_dev_only: agents,\n tools: allTools,\n renderToolCalls: allRenderToolCalls,\n renderActivityMessages: allActivityRenderers,\n renderCustomMessages: renderCustomMessagesList,\n });\n\n return copilotkit;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n allTools,\n allRenderToolCalls,\n allActivityRenderers,\n renderCustomMessagesList,\n useSingleEndpoint,\n ]);\n\n // Subscribe to render tool calls changes to force re-renders\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onRenderToolCallsChanged: () => {\n forceUpdate();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // Track executing tool call IDs at the provider level.\n // This is critical for HITL reconnection: when connecting to a thread with\n // pending tool calls, the onToolExecutionStart event fires before child components\n // (like CopilotChatToolCallsView) mount. By tracking at the provider level,\n // we ensure the executing state is captured and available when children mount.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n useEffect(() => {\n copilotkit.setRuntimeUrl(chatApiEndpoint);\n copilotkit.setRuntimeTransport(useSingleEndpoint ? \"single\" : \"rest\");\n copilotkit.setHeaders(mergedHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(properties);\n copilotkit.setAgents__unsafe_dev_only(agents);\n }, [\n chatApiEndpoint,\n mergedHeaders,\n credentials,\n properties,\n agents,\n useSingleEndpoint,\n ]);\n\n return (\n <CopilotKitContext.Provider\n value={{\n copilotkit,\n executingToolCallIds,\n }}\n >\n {children}\n {shouldRenderInspector ? <CopilotKitInspector core={copilotkit} /> : null}\n </CopilotKitContext.Provider>\n );\n};\n\n// Hook to use the CopilotKit instance - returns the full context value\nexport const useCopilotKit = (): CopilotKitContextValue => {\n const context = useContext(CopilotKitContext);\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n if (!context) {\n throw new Error(\"useCopilotKit must be used within CopilotKitProvider\");\n }\n useEffect(() => {\n const subscription = context.copilotkit.subscribe({\n onRuntimeConnectionStatusChanged: () => {\n forceUpdate();\n },\n });\n return () => {\n subscription.unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return context;\n};\n"],"mappings":";;;;;;;;;;;AA+BA,MAAM,cAAc;AACp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AAgB;EACd,MAAM,eAAe,WAAW,UAAU;GACxC,uBAAuB,EAAE,iBAAiB;AACxC,6BAAyB,SAAS;AAChC,SAAI,KAAK,IAAI,WAAW,CAAE,QAAO;KACjC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,IAAI,WAAW;AACpB,YAAO;MACP;;GAEJ,qBAAqB,EAAE,iBAAiB;AACtC,6BAAyB,SAAS;AAChC,SAAI,CAAC,KAAK,IAAI,WAAW,CAAE,QAAO;KAClC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,OAAO,WAAW;AACvB,YAAO;MACP;;GAEL,CAAC;AAEF,eAAa;AACX,gBAAa,aAAa;;IAE3B,CAAC,WAAW,CAAC;AAEhB,4BAAgB;AACd,aAAW,cAAc,gBAAgB;AACzC,aAAW,oBAAoB,oBAAoB,WAAW,OAAO;AACrE,aAAW,WAAW,cAAc;AACpC,aAAW,eAAe,YAAY;AACtC,aAAW,cAAc,WAAW;AACpC,aAAW,2BAA2B,OAAO;IAC5C;EACD;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAEF,QACE,4CAAC,kBAAkB;EACjB,OAAO;GACL;GACA;GACD;aAEA,UACA,wBAAwB,2CAACC,mDAAoB,MAAM,aAAc,GAAG;GAC1C;;AAKjC,MAAa,sBAA8C;CACzD,MAAM,gCAAqB,kBAAkB;CAC7C,MAAM,GAAG,sCAA2B,MAAM,IAAI,GAAG,EAAE;AAEnD,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,uDAAuD;AAEzE,4BAAgB;EACd,MAAM,eAAe,QAAQ,WAAW,UAAU,EAChD,wCAAwC;AACtC,gBAAa;KAEhB,CAAC;AACF,eAAa;AACX,gBAAa,aAAa;;IAG3B,EAAE,CAAC;AAEN,QAAO"}
|
|
1
|
+
{"version":3,"file":"CopilotKitProvider.cjs","names":["MCPAppsActivityType","MCPAppsActivityContentSchema","MCPAppsActivityRenderer","z","CopilotKitCoreReact","CopilotKitInspector"],"sources":["../../src/providers/CopilotKitProvider.tsx"],"sourcesContent":["\"use client\";\n\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { FrontendTool } from \"@copilotkitnext/core\";\nimport type React from \"react\";\nimport {\n createContext,\n useContext,\n type ReactNode,\n useMemo,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from \"react\";\nimport { z } from \"zod\";\nimport { CopilotKitInspector } from \"../components/CopilotKitInspector\";\nimport {\n MCPAppsActivityContentSchema,\n MCPAppsActivityRenderer,\n MCPAppsActivityType,\n} from \"../components/MCPAppsActivityRenderer\";\nimport { CopilotKitCoreReact } from \"../lib/react-core\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\n\nconst HEADER_NAME = \"X-CopilotCloud-Public-Api-Key\";\nconst COPILOT_CLOUD_CHAT_URL = \"https://api.cloud.copilotkit.ai/copilotkit/v1\";\n\n// Define the context value interface - idiomatic React naming\nexport interface CopilotKitContextValue {\n copilotkit: CopilotKitCoreReact;\n /**\n * Set of tool call IDs currently being executed.\n * This is tracked at the provider level to ensure tool execution events\n * are captured even before child components mount.\n */\n executingToolCallIds: ReadonlySet<string>;\n}\n\n// Empty set for default context value\nconst EMPTY_SET: ReadonlySet<string> = new Set();\n\n// Create the CopilotKit context\nconst CopilotKitContext = createContext<CopilotKitContextValue>({\n copilotkit: null!,\n executingToolCallIds: EMPTY_SET,\n});\n\n// Provider props interface\nexport interface CopilotKitProviderProps {\n children: ReactNode;\n runtimeUrl?: string;\n headers?: Record<string, string>;\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /**\n * The Copilot Cloud public API key.\n */\n publicApiKey?: string;\n /**\n * Alias for `publicApiKey`\n **/\n publicLicenseKey?: string;\n properties?: Record<string, unknown>;\n useSingleEndpoint?: boolean;\n agents__unsafe_dev_only?: Record<string, AbstractAgent>;\n selfManagedAgents?: Record<string, AbstractAgent>;\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n renderCustomMessages?: ReactCustomMessageRenderer[];\n frontendTools?: ReactFrontendTool[];\n humanInTheLoop?: ReactHumanInTheLoop[];\n showDevConsole?: boolean | \"auto\";\n}\n\n// Small helper to normalize array props to a stable reference and warn\nfunction useStableArrayProp<T>(\n prop: T[] | undefined,\n warningMessage?: string,\n isMeaningfulChange?: (initial: T[], next: T[]) => boolean,\n): T[] {\n const empty = useMemo<T[]>(() => [], []);\n const value = prop ?? empty;\n const initial = useRef(value);\n\n useEffect(() => {\n if (\n warningMessage &&\n value !== initial.current &&\n (isMeaningfulChange ? isMeaningfulChange(initial.current, value) : true)\n ) {\n console.error(warningMessage);\n }\n }, [value, warningMessage]);\n\n return value;\n}\n\n// Provider component\nexport const CopilotKitProvider: React.FC<CopilotKitProviderProps> = ({\n children,\n runtimeUrl,\n headers = {},\n credentials,\n publicApiKey,\n publicLicenseKey,\n properties = {},\n agents__unsafe_dev_only: agents = {},\n selfManagedAgents = {},\n renderToolCalls,\n renderActivityMessages,\n renderCustomMessages,\n frontendTools,\n humanInTheLoop,\n showDevConsole = false,\n useSingleEndpoint = false,\n}) => {\n const [shouldRenderInspector, setShouldRenderInspector] = useState(false);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n return;\n }\n\n if (showDevConsole === true) {\n // Explicitly show the inspector\n setShouldRenderInspector(true);\n } else if (showDevConsole === \"auto\") {\n // Show on localhost or 127.0.0.1 only\n const localhostHosts = new Set([\"localhost\", \"127.0.0.1\"]);\n if (localhostHosts.has(window.location.hostname)) {\n setShouldRenderInspector(true);\n } else {\n setShouldRenderInspector(false);\n }\n } else {\n // showDevConsole is false or undefined (default false)\n setShouldRenderInspector(false);\n }\n }, [showDevConsole]);\n\n // Normalize array props to stable references with clear dev warnings\n const renderToolCallsList = useStableArrayProp<ReactToolCallRenderer<any>>(\n renderToolCalls,\n \"renderToolCalls must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n (initial, next) => {\n // Only warn if the shape (names+agentId) changed. Allow identity changes\n // to support updated closures from parents (e.g., Storybook state).\n const key = (rc?: ReactToolCallRenderer<unknown>) =>\n `${rc?.agentId ?? \"\"}:${rc?.name ?? \"\"}`;\n const setFrom = (arr: ReactToolCallRenderer<unknown>[]) =>\n new Set(arr.map(key));\n const a = setFrom(initial);\n const b = setFrom(next);\n if (a.size !== b.size) return true;\n for (const k of a) if (!b.has(k)) return true;\n return false;\n },\n );\n\n const renderCustomMessagesList =\n useStableArrayProp<ReactCustomMessageRenderer>(\n renderCustomMessages,\n \"renderCustomMessages must be a stable array.\",\n );\n\n const renderActivityMessagesList = useStableArrayProp<\n ReactActivityMessageRenderer<any>\n >(renderActivityMessages, \"renderActivityMessages must be a stable array.\");\n\n // Built-in activity renderers that are always included\n const builtInActivityRenderers = useMemo<ReactActivityMessageRenderer<any>[]>(\n () => [\n {\n activityType: MCPAppsActivityType,\n content: MCPAppsActivityContentSchema,\n render: MCPAppsActivityRenderer,\n },\n ],\n [],\n );\n\n // Combine user-provided activity renderers with built-in ones\n // User-provided renderers take precedence (come first) so they can override built-ins\n const allActivityRenderers = useMemo(() => {\n return [...renderActivityMessagesList, ...builtInActivityRenderers];\n }, [renderActivityMessagesList, builtInActivityRenderers]);\n\n const resolvedPublicKey = publicApiKey ?? publicLicenseKey;\n const mergedAgents = useMemo(\n () => ({ ...agents, ...selfManagedAgents }),\n [agents, selfManagedAgents],\n );\n const hasLocalAgents = mergedAgents && Object.keys(mergedAgents).length > 0;\n\n // Merge a provided publicApiKey into headers (without overwriting an explicit header).\n const mergedHeaders = useMemo(() => {\n if (!resolvedPublicKey) return headers;\n if (headers[HEADER_NAME]) return headers;\n return {\n ...headers,\n [HEADER_NAME]: resolvedPublicKey,\n };\n }, [headers, resolvedPublicKey]);\n\n if (!runtimeUrl && !resolvedPublicKey && !hasLocalAgents) {\n const message =\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\";\n if (process.env.NODE_ENV === \"production\") {\n throw new Error(message);\n } else {\n // In dev/test we warn but allow to facilitate local agents and unit tests.\n console.warn(message);\n }\n }\n\n const chatApiEndpoint =\n runtimeUrl ?? (resolvedPublicKey ? COPILOT_CLOUD_CHAT_URL : undefined);\n\n const frontendToolsList = useStableArrayProp<ReactFrontendTool>(\n frontendTools,\n \"frontendTools must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n );\n const humanInTheLoopList = useStableArrayProp<ReactHumanInTheLoop>(\n humanInTheLoop,\n \"humanInTheLoop must be a stable array. If you want to dynamically add or remove human-in-the-loop tools, use `useHumanInTheLoop` instead.\",\n );\n\n // Note: warnings for array identity changes are handled by useStableArrayProp\n\n // Process humanInTheLoop tools to create handlers and add render components\n const processedHumanInTheLoopTools = useMemo(() => {\n const processedTools: FrontendTool[] = [];\n const processedRenderToolCalls: ReactToolCallRenderer<unknown>[] = [];\n\n humanInTheLoopList.forEach((tool) => {\n // Create a promise-based handler for each human-in-the-loop tool\n const frontendTool: FrontendTool = {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n followUp: tool.followUp,\n ...(tool.agentId && { agentId: tool.agentId }),\n handler: async () => {\n // This handler will be replaced by the hook when it runs\n // For provider-level tools, we create a basic handler that waits for user interaction\n return new Promise((resolve) => {\n // The actual implementation will be handled by the render component\n // This is a placeholder that the hook will override\n console.warn(\n `Human-in-the-loop tool '${tool.name}' called but no interactive handler is set up.`,\n );\n resolve(undefined);\n });\n },\n };\n processedTools.push(frontendTool);\n\n // Add the render component to renderToolCalls\n if (tool.render) {\n processedRenderToolCalls.push({\n name: tool.name,\n args: tool.parameters!,\n render: tool.render,\n ...(tool.agentId && { agentId: tool.agentId }),\n } as ReactToolCallRenderer<unknown>);\n }\n });\n\n return { tools: processedTools, renderToolCalls: processedRenderToolCalls };\n }, [humanInTheLoopList]);\n\n // Combine all tools for CopilotKitCore\n const allTools = useMemo(() => {\n const tools: FrontendTool[] = [];\n\n // Add frontend tools\n tools.push(...frontendToolsList);\n\n // Add processed human-in-the-loop tools\n tools.push(...processedHumanInTheLoopTools.tools);\n\n return tools;\n }, [frontendToolsList, processedHumanInTheLoopTools]);\n\n // Combine all render tool calls\n const allRenderToolCalls = useMemo(() => {\n const combined: ReactToolCallRenderer<unknown>[] = [...renderToolCallsList];\n\n // Add render components from frontend tools\n frontendToolsList.forEach((tool) => {\n if (tool.render) {\n // For wildcard tools without parameters, default to z.any()\n const args =\n tool.parameters || (tool.name === \"*\" ? z.any() : undefined);\n if (args) {\n combined.push({\n name: tool.name,\n args: args,\n render: tool.render,\n } as ReactToolCallRenderer<unknown>);\n }\n }\n });\n\n // Add render components from human-in-the-loop tools\n combined.push(...processedHumanInTheLoopTools.renderToolCalls);\n\n return combined;\n }, [renderToolCallsList, frontendToolsList, processedHumanInTheLoopTools]);\n\n const copilotkit = useMemo(() => {\n const copilotkit = new CopilotKitCoreReact({\n runtimeUrl: chatApiEndpoint,\n runtimeTransport: useSingleEndpoint ? \"single\" : \"rest\",\n headers: mergedHeaders,\n credentials,\n properties,\n agents__unsafe_dev_only: mergedAgents,\n tools: allTools,\n renderToolCalls: allRenderToolCalls,\n renderActivityMessages: allActivityRenderers,\n renderCustomMessages: renderCustomMessagesList,\n });\n\n return copilotkit;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n allTools,\n allRenderToolCalls,\n allActivityRenderers,\n renderCustomMessagesList,\n useSingleEndpoint,\n ]);\n\n // Subscribe to render tool calls changes to force re-renders\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onRenderToolCallsChanged: () => {\n forceUpdate();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // Track executing tool call IDs at the provider level.\n // This is critical for HITL reconnection: when connecting to a thread with\n // pending tool calls, the onToolExecutionStart event fires before child components\n // (like CopilotChatToolCallsView) mount. By tracking at the provider level,\n // we ensure the executing state is captured and available when children mount.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n useEffect(() => {\n copilotkit.setRuntimeUrl(chatApiEndpoint);\n copilotkit.setRuntimeTransport(useSingleEndpoint ? \"single\" : \"rest\");\n copilotkit.setHeaders(mergedHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(properties);\n copilotkit.setAgents__unsafe_dev_only(mergedAgents);\n }, [\n chatApiEndpoint,\n mergedHeaders,\n credentials,\n properties,\n mergedAgents,\n useSingleEndpoint,\n ]);\n\n return (\n <CopilotKitContext.Provider\n value={{\n copilotkit,\n executingToolCallIds,\n }}\n >\n {children}\n {shouldRenderInspector ? <CopilotKitInspector core={copilotkit} /> : null}\n </CopilotKitContext.Provider>\n );\n};\n\n// Hook to use the CopilotKit instance - returns the full context value\nexport const useCopilotKit = (): CopilotKitContextValue => {\n const context = useContext(CopilotKitContext);\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n if (!context) {\n throw new Error(\"useCopilotKit must be used within CopilotKitProvider\");\n }\n useEffect(() => {\n const subscription = context.copilotkit.subscribe({\n onRuntimeConnectionStatusChanged: () => {\n forceUpdate();\n },\n });\n return () => {\n subscription.unsubscribe();\n };\n // eslint-dis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AC;AACF,eAAa;AACX,gBAAa,aAAa;;IAG3B,EAAE,CAAC;AAEN,QAAO"}
|
|
@@ -37,6 +37,7 @@ interface CopilotKitProviderProps {
|
|
|
37
37
|
properties?: Record<string, unknown>;
|
|
38
38
|
useSingleEndpoint?: boolean;
|
|
39
39
|
agents__unsafe_dev_only?: Record<string, AbstractAgent>;
|
|
40
|
+
selfManagedAgents?: Record<string, AbstractAgent>;
|
|
40
41
|
renderToolCalls?: ReactToolCallRenderer<any>[];
|
|
41
42
|
renderActivityMessages?: ReactActivityMessageRenderer<any>[];
|
|
42
43
|
renderCustomMessages?: ReactCustomMessageRenderer[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CopilotKitProvider.d.cts","names":[],"sources":["../../src/providers/CopilotKitProvider.tsx"],"mappings":";;;;;;;;;;;UAmCiB,sBAAA;EACf,UAAA,EAAY,mBAAA;;AADd;;;;EAOE,oBAAA,EAAsB,WAAA;AAAA;AAAA,UAaP,uBAAA;EACf,QAAA,EAAU,SAAA;EACV,UAAA;EACA,OAAA,GAAU,MAAA;EAHK;;;EAOf,WAAA,GAAc,kBAAA;EAJJ;;;EAQV,YAAA;EAO0B;;;EAH1B,gBAAA;EACA,UAAA,GAAa,MAAA;EACb,iBAAA;EACA,uBAAA,GAA0B,MAAA,SAAe,aAAA;EACzC,eAAA,GAAkB,qBAAA;EAClB,sBAAA,GAAyB,4BAAA;EACzB,oBAAA,GAAuB,0BAAA;EACvB,aAAA,GAAgB,iBAAA;EAChB,cAAA,GAAiB,mBAAA;EACjB,cAAA;AAAA;AAAA,cA2BW,kBAAA,EAAoB,KAAA,CAAM,EAAA,CAAG,uBAAA;AAAA,
|
|
1
|
+
{"version":3,"file":"CopilotKitProvider.d.cts","names":[],"sources":["../../src/providers/CopilotKitProvider.tsx"],"mappings":";;;;;;;;;;;UAmCiB,sBAAA;EACf,UAAA,EAAY,mBAAA;;AADd;;;;EAOE,oBAAA,EAAsB,WAAA;AAAA;AAAA,UAaP,uBAAA;EACf,QAAA,EAAU,SAAA;EACV,UAAA;EACA,OAAA,GAAU,MAAA;EAHK;;;EAOf,WAAA,GAAc,kBAAA;EAJJ;;;EAQV,YAAA;EAO0B;;;EAH1B,gBAAA;EACA,UAAA,GAAa,MAAA;EACb,iBAAA;EACA,uBAAA,GAA0B,MAAA,SAAe,aAAA;EACzC,iBAAA,GAAoB,MAAA,SAAe,aAAA;EACnC,eAAA,GAAkB,qBAAA;EAClB,sBAAA,GAAyB,4BAAA;EACzB,oBAAA,GAAuB,0BAAA;EACvB,aAAA,GAAgB,iBAAA;EAChB,cAAA,GAAiB,mBAAA;EACjB,cAAA;AAAA;AAAA,cA2BW,kBAAA,EAAoB,KAAA,CAAM,EAAA,CAAG,uBAAA;AAAA,cA2T7B,aAAA,QAAoB,sBAAA"}
|
|
@@ -37,6 +37,7 @@ interface CopilotKitProviderProps {
|
|
|
37
37
|
properties?: Record<string, unknown>;
|
|
38
38
|
useSingleEndpoint?: boolean;
|
|
39
39
|
agents__unsafe_dev_only?: Record<string, AbstractAgent>;
|
|
40
|
+
selfManagedAgents?: Record<string, AbstractAgent>;
|
|
40
41
|
renderToolCalls?: ReactToolCallRenderer<any>[];
|
|
41
42
|
renderActivityMessages?: ReactActivityMessageRenderer<any>[];
|
|
42
43
|
renderCustomMessages?: ReactCustomMessageRenderer[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CopilotKitProvider.d.mts","names":[],"sources":["../../src/providers/CopilotKitProvider.tsx"],"mappings":";;;;;;;;;;;UAmCiB,sBAAA;EACf,UAAA,EAAY,mBAAA;;AADd;;;;EAOE,oBAAA,EAAsB,WAAA;AAAA;AAAA,UAaP,uBAAA;EACf,QAAA,EAAU,SAAA;EACV,UAAA;EACA,OAAA,GAAU,MAAA;EAHK;;;EAOf,WAAA,GAAc,kBAAA;EAJJ;;;EAQV,YAAA;EAO0B;;;EAH1B,gBAAA;EACA,UAAA,GAAa,MAAA;EACb,iBAAA;EACA,uBAAA,GAA0B,MAAA,SAAe,aAAA;EACzC,eAAA,GAAkB,qBAAA;EAClB,sBAAA,GAAyB,4BAAA;EACzB,oBAAA,GAAuB,0BAAA;EACvB,aAAA,GAAgB,iBAAA;EAChB,cAAA,GAAiB,mBAAA;EACjB,cAAA;AAAA;AAAA,cA2BW,kBAAA,EAAoB,KAAA,CAAM,EAAA,CAAG,uBAAA;AAAA,
|
|
1
|
+
{"version":3,"file":"CopilotKitProvider.d.mts","names":[],"sources":["../../src/providers/CopilotKitProvider.tsx"],"mappings":";;;;;;;;;;;UAmCiB,sBAAA;EACf,UAAA,EAAY,mBAAA;;AADd;;;;EAOE,oBAAA,EAAsB,WAAA;AAAA;AAAA,UAaP,uBAAA;EACf,QAAA,EAAU,SAAA;EACV,UAAA;EACA,OAAA,GAAU,MAAA;EAHK;;;EAOf,WAAA,GAAc,kBAAA;EAJJ;;;EAQV,YAAA;EAO0B;;;EAH1B,gBAAA;EACA,UAAA,GAAa,MAAA;EACb,iBAAA;EACA,uBAAA,GAA0B,MAAA,SAAe,aAAA;EACzC,iBAAA,GAAoB,MAAA,SAAe,aAAA;EACnC,eAAA,GAAkB,qBAAA;EAClB,sBAAA,GAAyB,4BAAA;EACzB,oBAAA,GAAuB,0BAAA;EACvB,aAAA,GAAgB,iBAAA;EAChB,cAAA,GAAiB,mBAAA;EACjB,cAAA;AAAA;AAAA,cA2BW,kBAAA,EAAoB,KAAA,CAAM,EAAA,CAAG,uBAAA;AAAA,cA2T7B,aAAA,QAAoB,sBAAA"}
|
|
@@ -23,7 +23,7 @@ function useStableArrayProp(prop, warningMessage, isMeaningfulChange) {
|
|
|
23
23
|
}, [value, warningMessage]);
|
|
24
24
|
return value;
|
|
25
25
|
}
|
|
26
|
-
const CopilotKitProvider = ({ children, runtimeUrl, headers = {}, credentials, publicApiKey, publicLicenseKey, properties = {}, agents__unsafe_dev_only: agents = {}, renderToolCalls, renderActivityMessages, renderCustomMessages, frontendTools, humanInTheLoop, showDevConsole = false, useSingleEndpoint = false }) => {
|
|
26
|
+
const CopilotKitProvider = ({ children, runtimeUrl, headers = {}, credentials, publicApiKey, publicLicenseKey, properties = {}, agents__unsafe_dev_only: agents = {}, selfManagedAgents = {}, renderToolCalls, renderActivityMessages, renderCustomMessages, frontendTools, humanInTheLoop, showDevConsole = false, useSingleEndpoint = false }) => {
|
|
27
27
|
const [shouldRenderInspector, setShouldRenderInspector] = useState(false);
|
|
28
28
|
useEffect(() => {
|
|
29
29
|
if (typeof window === "undefined") return;
|
|
@@ -52,7 +52,11 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers = {}, credentials, p
|
|
|
52
52
|
return [...renderActivityMessagesList, ...builtInActivityRenderers];
|
|
53
53
|
}, [renderActivityMessagesList, builtInActivityRenderers]);
|
|
54
54
|
const resolvedPublicKey = publicApiKey ?? publicLicenseKey;
|
|
55
|
-
const
|
|
55
|
+
const mergedAgents = useMemo(() => ({
|
|
56
|
+
...agents,
|
|
57
|
+
...selfManagedAgents
|
|
58
|
+
}), [agents, selfManagedAgents]);
|
|
59
|
+
const hasLocalAgents = mergedAgents && Object.keys(mergedAgents).length > 0;
|
|
56
60
|
const mergedHeaders = useMemo(() => {
|
|
57
61
|
if (!resolvedPublicKey) return headers;
|
|
58
62
|
if (headers[HEADER_NAME]) return headers;
|
|
@@ -131,7 +135,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers = {}, credentials, p
|
|
|
131
135
|
headers: mergedHeaders,
|
|
132
136
|
credentials,
|
|
133
137
|
properties,
|
|
134
|
-
agents__unsafe_dev_only:
|
|
138
|
+
agents__unsafe_dev_only: mergedAgents,
|
|
135
139
|
tools: allTools,
|
|
136
140
|
renderToolCalls: allRenderToolCalls,
|
|
137
141
|
renderActivityMessages: allActivityRenderers,
|
|
@@ -183,13 +187,13 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers = {}, credentials, p
|
|
|
183
187
|
copilotkit.setHeaders(mergedHeaders);
|
|
184
188
|
copilotkit.setCredentials(credentials);
|
|
185
189
|
copilotkit.setProperties(properties);
|
|
186
|
-
copilotkit.setAgents__unsafe_dev_only(
|
|
190
|
+
copilotkit.setAgents__unsafe_dev_only(mergedAgents);
|
|
187
191
|
}, [
|
|
188
192
|
chatApiEndpoint,
|
|
189
193
|
mergedHeaders,
|
|
190
194
|
credentials,
|
|
191
195
|
properties,
|
|
192
|
-
|
|
196
|
+
mergedAgents,
|
|
193
197
|
useSingleEndpoint
|
|
194
198
|
]);
|
|
195
199
|
return /* @__PURE__ */ jsxs(CopilotKitContext.Provider, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CopilotKitProvider.mjs","names":[],"sources":["../../src/providers/CopilotKitProvider.tsx"],"sourcesContent":["\"use client\";\n\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { FrontendTool } from \"@copilotkitnext/core\";\nimport type React from \"react\";\nimport {\n createContext,\n useContext,\n type ReactNode,\n useMemo,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from \"react\";\nimport { z } from \"zod\";\nimport { CopilotKitInspector } from \"../components/CopilotKitInspector\";\nimport {\n MCPAppsActivityContentSchema,\n MCPAppsActivityRenderer,\n MCPAppsActivityType,\n} from \"../components/MCPAppsActivityRenderer\";\nimport { CopilotKitCoreReact } from \"../lib/react-core\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\n\nconst HEADER_NAME = \"X-CopilotCloud-Public-Api-Key\";\nconst COPILOT_CLOUD_CHAT_URL = \"https://api.cloud.copilotkit.ai/copilotkit/v1\";\n\n// Define the context value interface - idiomatic React naming\nexport interface CopilotKitContextValue {\n copilotkit: CopilotKitCoreReact;\n /**\n * Set of tool call IDs currently being executed.\n * This is tracked at the provider level to ensure tool execution events\n * are captured even before child components mount.\n */\n executingToolCallIds: ReadonlySet<string>;\n}\n\n// Empty set for default context value\nconst EMPTY_SET: ReadonlySet<string> = new Set();\n\n// Create the CopilotKit context\nconst CopilotKitContext = createContext<CopilotKitContextValue>({\n copilotkit: null!,\n executingToolCallIds: EMPTY_SET,\n});\n\n// Provider props interface\nexport interface CopilotKitProviderProps {\n children: ReactNode;\n runtimeUrl?: string;\n headers?: Record<string, string>;\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /**\n * The Copilot Cloud public API key.\n */\n publicApiKey?: string;\n /**\n * Alias for `publicApiKey`\n **/\n publicLicenseKey?: string;\n properties?: Record<string, unknown>;\n useSingleEndpoint?: boolean;\n agents__unsafe_dev_only?: Record<string, AbstractAgent>;\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n renderCustomMessages?: ReactCustomMessageRenderer[];\n frontendTools?: ReactFrontendTool[];\n humanInTheLoop?: ReactHumanInTheLoop[];\n showDevConsole?: boolean | \"auto\";\n}\n\n// Small helper to normalize array props to a stable reference and warn\nfunction useStableArrayProp<T>(\n prop: T[] | undefined,\n warningMessage?: string,\n isMeaningfulChange?: (initial: T[], next: T[]) => boolean,\n): T[] {\n const empty = useMemo<T[]>(() => [], []);\n const value = prop ?? empty;\n const initial = useRef(value);\n\n useEffect(() => {\n if (\n warningMessage &&\n value !== initial.current &&\n (isMeaningfulChange ? isMeaningfulChange(initial.current, value) : true)\n ) {\n console.error(warningMessage);\n }\n }, [value, warningMessage]);\n\n return value;\n}\n\n// Provider component\nexport const CopilotKitProvider: React.FC<CopilotKitProviderProps> = ({\n children,\n runtimeUrl,\n headers = {},\n credentials,\n publicApiKey,\n publicLicenseKey,\n properties = {},\n agents__unsafe_dev_only: agents = {},\n renderToolCalls,\n renderActivityMessages,\n renderCustomMessages,\n frontendTools,\n humanInTheLoop,\n showDevConsole = false,\n useSingleEndpoint = false,\n}) => {\n const [shouldRenderInspector, setShouldRenderInspector] = useState(false);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n return;\n }\n\n if (showDevConsole === true) {\n // Explicitly show the inspector\n setShouldRenderInspector(true);\n } else if (showDevConsole === \"auto\") {\n // Show on localhost or 127.0.0.1 only\n const localhostHosts = new Set([\"localhost\", \"127.0.0.1\"]);\n if (localhostHosts.has(window.location.hostname)) {\n setShouldRenderInspector(true);\n } else {\n setShouldRenderInspector(false);\n }\n } else {\n // showDevConsole is false or undefined (default false)\n setShouldRenderInspector(false);\n }\n }, [showDevConsole]);\n\n // Normalize array props to stable references with clear dev warnings\n const renderToolCallsList = useStableArrayProp<ReactToolCallRenderer<any>>(\n renderToolCalls,\n \"renderToolCalls must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n (initial, next) => {\n // Only warn if the shape (names+agentId) changed. Allow identity changes\n // to support updated closures from parents (e.g., Storybook state).\n const key = (rc?: ReactToolCallRenderer<unknown>) =>\n `${rc?.agentId ?? \"\"}:${rc?.name ?? \"\"}`;\n const setFrom = (arr: ReactToolCallRenderer<unknown>[]) =>\n new Set(arr.map(key));\n const a = setFrom(initial);\n const b = setFrom(next);\n if (a.size !== b.size) return true;\n for (const k of a) if (!b.has(k)) return true;\n return false;\n },\n );\n\n const renderCustomMessagesList =\n useStableArrayProp<ReactCustomMessageRenderer>(\n renderCustomMessages,\n \"renderCustomMessages must be a stable array.\",\n );\n\n const renderActivityMessagesList = useStableArrayProp<\n ReactActivityMessageRenderer<any>\n >(renderActivityMessages, \"renderActivityMessages must be a stable array.\");\n\n // Built-in activity renderers that are always included\n const builtInActivityRenderers = useMemo<ReactActivityMessageRenderer<any>[]>(\n () => [\n {\n activityType: MCPAppsActivityType,\n content: MCPAppsActivityContentSchema,\n render: MCPAppsActivityRenderer,\n },\n ],\n [],\n );\n\n // Combine user-provided activity renderers with built-in ones\n // User-provided renderers take precedence (come first) so they can override built-ins\n const allActivityRenderers = useMemo(() => {\n return [...renderActivityMessagesList, ...builtInActivityRenderers];\n }, [renderActivityMessagesList, builtInActivityRenderers]);\n\n const resolvedPublicKey = publicApiKey ?? publicLicenseKey;\n const hasLocalAgents = agents && Object.keys(agents).length > 0;\n\n // Merge a provided publicApiKey into headers (without overwriting an explicit header).\n const mergedHeaders = useMemo(() => {\n if (!resolvedPublicKey) return headers;\n if (headers[HEADER_NAME]) return headers;\n return {\n ...headers,\n [HEADER_NAME]: resolvedPublicKey,\n };\n }, [headers, resolvedPublicKey]);\n\n if (!runtimeUrl && !resolvedPublicKey && !hasLocalAgents) {\n const message =\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\";\n if (process.env.NODE_ENV === \"production\") {\n throw new Error(message);\n } else {\n // In dev/test we warn but allow to facilitate local agents and unit tests.\n console.warn(message);\n }\n }\n\n const chatApiEndpoint =\n runtimeUrl ?? (resolvedPublicKey ? COPILOT_CLOUD_CHAT_URL : undefined);\n\n const frontendToolsList = useStableArrayProp<ReactFrontendTool>(\n frontendTools,\n \"frontendTools must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n );\n const humanInTheLoopList = useStableArrayProp<ReactHumanInTheLoop>(\n humanInTheLoop,\n \"humanInTheLoop must be a stable array. If you want to dynamically add or remove human-in-the-loop tools, use `useHumanInTheLoop` instead.\",\n );\n\n // Note: warnings for array identity changes are handled by useStableArrayProp\n\n // Process humanInTheLoop tools to create handlers and add render components\n const processedHumanInTheLoopTools = useMemo(() => {\n const processedTools: FrontendTool[] = [];\n const processedRenderToolCalls: ReactToolCallRenderer<unknown>[] = [];\n\n humanInTheLoopList.forEach((tool) => {\n // Create a promise-based handler for each human-in-the-loop tool\n const frontendTool: FrontendTool = {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n followUp: tool.followUp,\n ...(tool.agentId && { agentId: tool.agentId }),\n handler: async () => {\n // This handler will be replaced by the hook when it runs\n // For provider-level tools, we create a basic handler that waits for user interaction\n return new Promise((resolve) => {\n // The actual implementation will be handled by the render component\n // This is a placeholder that the hook will override\n console.warn(\n `Human-in-the-loop tool '${tool.name}' called but no interactive handler is set up.`,\n );\n resolve(undefined);\n });\n },\n };\n processedTools.push(frontendTool);\n\n // Add the render component to renderToolCalls\n if (tool.render) {\n processedRenderToolCalls.push({\n name: tool.name,\n args: tool.parameters!,\n render: tool.render,\n ...(tool.agentId && { agentId: tool.agentId }),\n } as ReactToolCallRenderer<unknown>);\n }\n });\n\n return { tools: processedTools, renderToolCalls: processedRenderToolCalls };\n }, [humanInTheLoopList]);\n\n // Combine all tools for CopilotKitCore\n const allTools = useMemo(() => {\n const tools: FrontendTool[] = [];\n\n // Add frontend tools\n tools.push(...frontendToolsList);\n\n // Add processed human-in-the-loop tools\n tools.push(...processedHumanInTheLoopTools.tools);\n\n return tools;\n }, [frontendToolsList, processedHumanInTheLoopTools]);\n\n // Combine all render tool calls\n const allRenderToolCalls = useMemo(() => {\n const combined: ReactToolCallRenderer<unknown>[] = [...renderToolCallsList];\n\n // Add render components from frontend tools\n frontendToolsList.forEach((tool) => {\n if (tool.render) {\n // For wildcard tools without parameters, default to z.any()\n const args =\n tool.parameters || (tool.name === \"*\" ? z.any() : undefined);\n if (args) {\n combined.push({\n name: tool.name,\n args: args,\n render: tool.render,\n } as ReactToolCallRenderer<unknown>);\n }\n }\n });\n\n // Add render components from human-in-the-loop tools\n combined.push(...processedHumanInTheLoopTools.renderToolCalls);\n\n return combined;\n }, [renderToolCallsList, frontendToolsList, processedHumanInTheLoopTools]);\n\n const copilotkit = useMemo(() => {\n const copilotkit = new CopilotKitCoreReact({\n runtimeUrl: chatApiEndpoint,\n runtimeTransport: useSingleEndpoint ? \"single\" : \"rest\",\n headers: mergedHeaders,\n credentials,\n properties,\n agents__unsafe_dev_only: agents,\n tools: allTools,\n renderToolCalls: allRenderToolCalls,\n renderActivityMessages: allActivityRenderers,\n renderCustomMessages: renderCustomMessagesList,\n });\n\n return copilotkit;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n allTools,\n allRenderToolCalls,\n allActivityRenderers,\n renderCustomMessagesList,\n useSingleEndpoint,\n ]);\n\n // Subscribe to render tool calls changes to force re-renders\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onRenderToolCallsChanged: () => {\n forceUpdate();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // Track executing tool call IDs at the provider level.\n // This is critical for HITL reconnection: when connecting to a thread with\n // pending tool calls, the onToolExecutionStart event fires before child components\n // (like CopilotChatToolCallsView) mount. By tracking at the provider level,\n // we ensure the executing state is captured and available when children mount.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n useEffect(() => {\n copilotkit.setRuntimeUrl(chatApiEndpoint);\n copilotkit.setRuntimeTransport(useSingleEndpoint ? \"single\" : \"rest\");\n copilotkit.setHeaders(mergedHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(properties);\n copilotkit.setAgents__unsafe_dev_only(agents);\n }, [\n chatApiEndpoint,\n mergedHeaders,\n credentials,\n properties,\n agents,\n useSingleEndpoint,\n ]);\n\n return (\n <CopilotKitContext.Provider\n value={{\n copilotkit,\n executingToolCallIds,\n }}\n >\n {children}\n {shouldRenderInspector ? <CopilotKitInspector core={copilotkit} /> : null}\n </CopilotKitContext.Provider>\n );\n};\n\n// Hook to use the CopilotKit instance - returns the full context value\nexport const useCopilotKit = (): CopilotKitContextValue => {\n const context = useContext(CopilotKitContext);\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n if (!context) {\n throw new Error(\"useCopilotKit must be used within CopilotKitProvider\");\n }\n useEffect(() => {\n const subscription = context.copilotkit.subscribe({\n onRuntimeConnectionStatusChanged: () => {\n forceUpdate();\n },\n });\n return () => {\n subscription.unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return context;\n};\n"],"mappings":";;;;;;;;;;AA+BA,MAAM,cAAc;AACpB,MAAM,yBAAyB;AAiB/B,MAAM,oBAAoB,cAAsC;CAC9D,YAAY;CACZ,sCALqC,IAAI,KAAK;CAM/C,CAAC;AA+BF,SAAS,mBACP,MACA,gBACA,oBACK;CACL,MAAM,QAAQ,cAAmB,EAAE,EAAE,EAAE,CAAC;CACxC,MAAM,QAAQ,QAAQ;CACtB,MAAM,UAAU,OAAO,MAAM;AAE7B,iBAAgB;AACd,MACE,kBACA,UAAU,QAAQ,YACjB,qBAAqB,mBAAmB,QAAQ,SAAS,MAAM,GAAG,MAEnE,SAAQ,MAAM,eAAe;IAE9B,CAAC,OAAO,eAAe,CAAC;AAE3B,QAAO;;AAIT,MAAa,sBAAyD,EACpE,UACA,YACA,UAAU,EAAE,EACZ,aACA,cACA,kBACA,aAAa,EAAE,EACf,yBAAyB,SAAS,EAAE,EACpC,iBACA,wBACA,sBACA,eACA,gBACA,iBAAiB,OACjB,oBAAoB,YAChB;CACJ,MAAM,CAAC,uBAAuB,4BAA4B,SAAS,MAAM;AAEzE,iBAAgB;AACd,MAAI,OAAO,WAAW,YACpB;AAGF,MAAI,mBAAmB,KAErB,0BAAyB,KAAK;WACrB,mBAAmB,OAG5B,KADuB,IAAI,IAAI,CAAC,aAAa,YAAY,CAAC,CACvC,IAAI,OAAO,SAAS,SAAS,CAC9C,0BAAyB,KAAK;MAE9B,0BAAyB,MAAM;MAIjC,0BAAyB,MAAM;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AKjC,MAAa,sBAA8C;CACzD,MAAM,UAAU,WAAW,kBAAkB;CAC7C,MAAM,GAAG,eAAe,YAAY,MAAM,IAAI,GAAG,EAAE;AAEnD,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,uDAAuD;AAEzE,iBAAgB;EACd,MAAM,eAAe,QAAQ,WAAW,UAAU,EAChD,wCAAwC;AACtC,gBAAa;KAEhB,CAAC;AACF,eAAa;AACX,gBAAa,aAAa;;IAG3B,EAAE,CAAC;AAEN,QAAO"}
|
|
1
|
+
{"version":3,"file":"CopilotKitProvider.mjs","names":[],"sources":["../../src/providers/CopilotKitProvider.tsx"],"sourcesContent":["\"use client\";\n\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { FrontendTool } from \"@copilotkitnext/core\";\nimport type React from \"react\";\nimport {\n createContext,\n useContext,\n type ReactNode,\n useMemo,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from \"react\";\nimport { z } from \"zod\";\nimport { CopilotKitInspector } from \"../components/CopilotKitInspector\";\nimport {\n MCPAppsActivityContentSchema,\n MCPAppsActivityRenderer,\n MCPAppsActivityType,\n} from \"../components/MCPAppsActivityRenderer\";\nimport { CopilotKitCoreReact } from \"../lib/react-core\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\n\nconst HEADER_NAME = \"X-CopilotCloud-Public-Api-Key\";\nconst COPILOT_CLOUD_CHAT_URL = \"https://api.cloud.copilotkit.ai/copilotkit/v1\";\n\n// Define the context value interface - idiomatic React naming\nexport interface CopilotKitContextValue {\n copilotkit: CopilotKitCoreReact;\n /**\n * Set of tool call IDs currently being executed.\n * This is tracked at the provider level to ensure tool execution events\n * are captured even before child components mount.\n */\n executingToolCallIds: ReadonlySet<string>;\n}\n\n// Empty set for default context value\nconst EMPTY_SET: ReadonlySet<string> = new Set();\n\n// Create the CopilotKit context\nconst CopilotKitContext = createContext<CopilotKitContextValue>({\n copilotkit: null!,\n executingToolCallIds: EMPTY_SET,\n});\n\n// Provider props interface\nexport interface CopilotKitProviderProps {\n children: ReactNode;\n runtimeUrl?: string;\n headers?: Record<string, string>;\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /**\n * The Copilot Cloud public API key.\n */\n publicApiKey?: string;\n /**\n * Alias for `publicApiKey`\n **/\n publicLicenseKey?: string;\n properties?: Record<string, unknown>;\n useSingleEndpoint?: boolean;\n agents__unsafe_dev_only?: Record<string, AbstractAgent>;\n selfManagedAgents?: Record<string, AbstractAgent>;\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n renderCustomMessages?: ReactCustomMessageRenderer[];\n frontendTools?: ReactFrontendTool[];\n humanInTheLoop?: ReactHumanInTheLoop[];\n showDevConsole?: boolean | \"auto\";\n}\n\n// Small helper to normalize array props to a stable reference and warn\nfunction useStableArrayProp<T>(\n prop: T[] | undefined,\n warningMessage?: string,\n isMeaningfulChange?: (initial: T[], next: T[]) => boolean,\n): T[] {\n const empty = useMemo<T[]>(() => [], []);\n const value = prop ?? empty;\n const initial = useRef(value);\n\n useEffect(() => {\n if (\n warningMessage &&\n value !== initial.current &&\n (isMeaningfulChange ? isMeaningfulChange(initial.current, value) : true)\n ) {\n console.error(warningMessage);\n }\n }, [value, warningMessage]);\n\n return value;\n}\n\n// Provider component\nexport const CopilotKitProvider: React.FC<CopilotKitProviderProps> = ({\n children,\n runtimeUrl,\n headers = {},\n credentials,\n publicApiKey,\n publicLicenseKey,\n properties = {},\n agents__unsafe_dev_only: agents = {},\n selfManagedAgents = {},\n renderToolCalls,\n renderActivityMessages,\n renderCustomMessages,\n frontendTools,\n humanInTheLoop,\n showDevConsole = false,\n useSingleEndpoint = false,\n}) => {\n const [shouldRenderInspector, setShouldRenderInspector] = useState(false);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n return;\n }\n\n if (showDevConsole === true) {\n // Explicitly show the inspector\n setShouldRenderInspector(true);\n } else if (showDevConsole === \"auto\") {\n // Show on localhost or 127.0.0.1 only\n const localhostHosts = new Set([\"localhost\", \"127.0.0.1\"]);\n if (localhostHosts.has(window.location.hostname)) {\n setShouldRenderInspector(true);\n } else {\n setShouldRenderInspector(false);\n }\n } else {\n // showDevConsole is false or undefined (default false)\n setShouldRenderInspector(false);\n }\n }, [showDevConsole]);\n\n // Normalize array props to stable references with clear dev warnings\n const renderToolCallsList = useStableArrayProp<ReactToolCallRenderer<any>>(\n renderToolCalls,\n \"renderToolCalls must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n (initial, next) => {\n // Only warn if the shape (names+agentId) changed. Allow identity changes\n // to support updated closures from parents (e.g., Storybook state).\n const key = (rc?: ReactToolCallRenderer<unknown>) =>\n `${rc?.agentId ?? \"\"}:${rc?.name ?? \"\"}`;\n const setFrom = (arr: ReactToolCallRenderer<unknown>[]) =>\n new Set(arr.map(key));\n const a = setFrom(initial);\n const b = setFrom(next);\n if (a.size !== b.size) return true;\n for (const k of a) if (!b.has(k)) return true;\n return false;\n },\n );\n\n const renderCustomMessagesList =\n useStableArrayProp<ReactCustomMessageRenderer>(\n renderCustomMessages,\n \"renderCustomMessages must be a stable array.\",\n );\n\n const renderActivityMessagesList = useStableArrayProp<\n ReactActivityMessageRenderer<any>\n >(renderActivityMessages, \"renderActivityMessages must be a stable array.\");\n\n // Built-in activity renderers that are always included\n const builtInActivityRenderers = useMemo<ReactActivityMessageRenderer<any>[]>(\n () => [\n {\n activityType: MCPAppsActivityType,\n content: MCPAppsActivityContentSchema,\n render: MCPAppsActivityRenderer,\n },\n ],\n [],\n );\n\n // Combine user-provided activity renderers with built-in ones\n // User-provided renderers take precedence (come first) so they can override built-ins\n const allActivityRenderers = useMemo(() => {\n return [...renderActivityMessagesList, ...builtInActivityRenderers];\n }, [renderActivityMessagesList, builtInActivityRenderers]);\n\n const resolvedPublicKey = publicApiKey ?? publicLicenseKey;\n const mergedAgents = useMemo(\n () => ({ ...agents, ...selfManagedAgents }),\n [agents, selfManagedAgents],\n );\n const hasLocalAgents = mergedAgents && Object.keys(mergedAgents).length > 0;\n\n // Merge a provided publicApiKey into headers (without overwriting an explicit header).\n const mergedHeaders = useMemo(() => {\n if (!resolvedPublicKey) return headers;\n if (headers[HEADER_NAME]) return headers;\n return {\n ...headers,\n [HEADER_NAME]: resolvedPublicKey,\n };\n }, [headers, resolvedPublicKey]);\n\n if (!runtimeUrl && !resolvedPublicKey && !hasLocalAgents) {\n const message =\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\";\n if (process.env.NODE_ENV === \"production\") {\n throw new Error(message);\n } else {\n // In dev/test we warn but allow to facilitate local agents and unit tests.\n console.warn(message);\n }\n }\n\n const chatApiEndpoint =\n runtimeUrl ?? (resolvedPublicKey ? COPILOT_CLOUD_CHAT_URL : undefined);\n\n const frontendToolsList = useStableArrayProp<ReactFrontendTool>(\n frontendTools,\n \"frontendTools must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.\",\n );\n const humanInTheLoopList = useStableArrayProp<ReactHumanInTheLoop>(\n humanInTheLoop,\n \"humanInTheLoop must be a stable array. If you want to dynamically add or remove human-in-the-loop tools, use `useHumanInTheLoop` instead.\",\n );\n\n // Note: warnings for array identity changes are handled by useStableArrayProp\n\n // Process humanInTheLoop tools to create handlers and add render components\n const processedHumanInTheLoopTools = useMemo(() => {\n const processedTools: FrontendTool[] = [];\n const processedRenderToolCalls: ReactToolCallRenderer<unknown>[] = [];\n\n humanInTheLoopList.forEach((tool) => {\n // Create a promise-based handler for each human-in-the-loop tool\n const frontendTool: FrontendTool = {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n followUp: tool.followUp,\n ...(tool.agentId && { agentId: tool.agentId }),\n handler: async () => {\n // This handler will be replaced by the hook when it runs\n // For provider-level tools, we create a basic handler that waits for user interaction\n return new Promise((resolve) => {\n // The actual implementation will be handled by the render component\n // This is a placeholder that the hook will override\n console.warn(\n `Human-in-the-loop tool '${tool.name}' called but no interactive handler is set up.`,\n );\n resolve(undefined);\n });\n },\n };\n processedTools.push(frontendTool);\n\n // Add the render component to renderToolCalls\n if (tool.render) {\n processedRenderToolCalls.push({\n name: tool.name,\n args: tool.parameters!,\n render: tool.render,\n ...(tool.agentId && { agentId: tool.agentId }),\n } as ReactToolCallRenderer<unknown>);\n }\n });\n\n return { tools: processedTools, renderToolCalls: processedRenderToolCalls };\n }, [humanInTheLoopList]);\n\n // Combine all tools for CopilotKitCore\n const allTools = useMemo(() => {\n const tools: FrontendTool[] = [];\n\n // Add frontend tools\n tools.push(...frontendToolsList);\n\n // Add processed human-in-the-loop tools\n tools.push(...processedHumanInTheLoopTools.tools);\n\n return tools;\n }, [frontendToolsList, processedHumanInTheLoopTools]);\n\n // Combine all render tool calls\n const allRenderToolCalls = useMemo(() => {\n const combined: ReactToolCallRenderer<unknown>[] = [...renderToolCallsList];\n\n // Add render components from frontend tools\n frontendToolsList.forEach((tool) => {\n if (tool.render) {\n // For wildcard tools without parameters, default to z.any()\n const args =\n tool.parameters || (tool.name === \"*\" ? z.any() : undefined);\n if (args) {\n combined.push({\n name: tool.name,\n args: args,\n render: tool.render,\n } as ReactToolCallRenderer<unknown>);\n }\n }\n });\n\n // Add render components from human-in-the-loop tools\n combined.push(...processedHumanInTheLoopTools.renderToolCalls);\n\n return combined;\n }, [renderToolCallsList, frontendToolsList, processedHumanInTheLoopTools]);\n\n const copilotkit = useMemo(() => {\n const copilotkit = new CopilotKitCoreReact({\n runtimeUrl: chatApiEndpoint,\n runtimeTransport: useSingleEndpoint ? \"single\" : \"rest\",\n headers: mergedHeaders,\n credentials,\n properties,\n agents__unsafe_dev_only: mergedAgents,\n tools: allTools,\n renderToolCalls: allRenderToolCalls,\n renderActivityMessages: allActivityRenderers,\n renderCustomMessages: renderCustomMessagesList,\n });\n\n return copilotkit;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n allTools,\n allRenderToolCalls,\n allActivityRenderers,\n renderCustomMessagesList,\n useSingleEndpoint,\n ]);\n\n // Subscribe to render tool calls changes to force re-renders\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onRenderToolCallsChanged: () => {\n forceUpdate();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // Track executing tool call IDs at the provider level.\n // This is critical for HITL reconnection: when connecting to a thread with\n // pending tool calls, the onToolExecutionStart event fires before child components\n // (like CopilotChatToolCallsView) mount. By tracking at the provider level,\n // we ensure the executing state is captured and available when children mount.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n useEffect(() => {\n copilotkit.setRuntimeUrl(chatApiEndpoint);\n copilotkit.setRuntimeTransport(useSingleEndpoint ? \"single\" : \"rest\");\n copilotkit.setHeaders(mergedHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(properties);\n copilotkit.setAgents__unsafe_dev_only(mergedAgents);\n }, [\n chatApiEndpoint,\n mergedHeaders,\n credentials,\n properties,\n mergedAgents,\n useSingleEndpoint,\n ]);\n\n return (\n <CopilotKitContext.Provider\n value={{\n copilotkit,\n executingToolCallIds,\n }}\n >\n {children}\n {shouldRenderInspector ? <CopilotKitInspector core={copilotkit} /> : null}\n </CopilotKitContext.Provider>\n );\n};\n\n// Hook to use the CopilotKit instance - returns the full context value\nexport const useCopilotKit = (): CopilotKitContextValue => {\n const context = useContext(CopilotKitContext);\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n if (!context) {\n throw new Error(\"useCopilotKit must be used within CopilotKitProvider\");\n }\n useEffect(() => {\n const subscription = context.copilotkit.subscribe({\n onRuntimeConnectionStatusChanged: () => {\n forceUpdate();\n },\n });\n return () => {\n subscription.unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return context;\n};\n"],"mappings":";;;;;;;;;;AA+BA,MAAM,cAAc;AACpB,MAAM,yBAAyB;AAiB/B,MAAM,oBAAoB,cAAsC;CAC9D,YAAY;CACZ,sCALqC,IAAI,KAAK;CAM/C,CAAC;AAgCF,SAAS,mBACP,MACA,gBACA,oBACK;CACL,MAAM,QAAQ,cAAmB,EAAE,EAAE,EAAE,CAAC;CACxC,MAAM,QAAQ,QAAQ;CACtB,MAAM,UAAU,OAAO,MAAM;AAE7B,iBAAgB;AACd,MACE,kBACA,UAAU,QAAQ,YACjB,qBAAqB,mBAAmB,QAAQ,SAAS,MAAM,GAAG,MAEnE,SAAQ,MAAM,eAAe;IAE9B,CAAC,OAAO,eAAe,CAAC;AAE3B,QAAO;;AAIT,MAAa,sBAAyD,EACpE,UACA,YACA,UAAU,EAAE,EACZ,aACA,cACA,kBACA,aAAa,EAAE,EACf,yBAAyB,SAAS,EAAE,EACpC,oBAAoB,EAAE,EACtB,iBACA,wBACA,sBACA,eACA,gBACA,iBAAiB,OACjB,oBAAoB,YAChB;CACJ,MAAM,CAAC,uBAAuB,4BAA4B,SAAS,MAAM;AAEzE,iBAAgB;AACd,MAAI,OAAO,WAAW,YACpB;AAGF,MAAI,mBAAmB,KAErB,0BAAyB,KAAK;WACrB,mBAAmB,OAG5B,KADuB,IAAI,IAAI,CAAC,aA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AW,cAAc,WAAW;AACpC,aAAW,2BAA2B,aAAa;IAClD;EACD;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAEF,QACE,qBAAC,kBAAkB;EACjB,OAAO;GACL;GACA;GACD;aAEA,UACA,wBAAwB,oBAAC,uBAAoB,MAAM,aAAc,GAAG;GAC1C;;AAKjC,MAAa,sBAA8C;CACzD,MAAM,UAAU,WAAW,kBAAkB;CAC7C,MAAM,GAAG,eAAe,YAAY,MAAM,IAAI,GAAG,EAAE;AAEnD,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,uDAAuD;AAEzE,iBAAgB;EACd,MAAM,eAAe,QAAQ,WAAW,UAAU,EAChD,wCAAwC;AACtC,gBAAa;KAEhB,CAAC;AACF,eAAa;AACX,gBAAa,aAAa;;IAG3B,EAAE,CAAC;AAEN,QAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copilotkitnext/react",
|
|
3
|
-
"version": "1.52.
|
|
3
|
+
"version": "1.52.1-next.1",
|
|
4
4
|
"description": "React components for CopilotKit2",
|
|
5
5
|
"main": "./dist/index.cjs",
|
|
6
6
|
"types": "./dist/index.d.cts",
|
|
@@ -38,8 +38,8 @@
|
|
|
38
38
|
"tsdown": "^0.20.3",
|
|
39
39
|
"typescript": "5.8.2",
|
|
40
40
|
"vitest": "^3.2.4",
|
|
41
|
-
"@copilotkitnext/eslint-config": "1.52.
|
|
42
|
-
"@copilotkitnext/typescript-config": "1.52.
|
|
41
|
+
"@copilotkitnext/eslint-config": "1.52.1-next.1",
|
|
42
|
+
"@copilotkitnext/typescript-config": "1.52.1-next.1"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@ag-ui/client": "0.0.45",
|
|
@@ -58,9 +58,9 @@
|
|
|
58
58
|
"tw-animate-css": "^1.3.5",
|
|
59
59
|
"use-stick-to-bottom": "^1.1.1",
|
|
60
60
|
"zod": "^3.25.75",
|
|
61
|
-
"@copilotkitnext/
|
|
62
|
-
"@copilotkitnext/
|
|
63
|
-
"@copilotkitnext/web-inspector": "1.52.
|
|
61
|
+
"@copilotkitnext/shared": "1.52.1-next.1",
|
|
62
|
+
"@copilotkitnext/core": "1.52.1-next.1",
|
|
63
|
+
"@copilotkitnext/web-inspector": "1.52.1-next.1"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|
|
66
66
|
"react": ">=16.8.0",
|