@copilotkit/react-native 1.63.2-canary.1784918757 → 1.63.3-canary.rc-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.
@@ -0,0 +1,176 @@
1
+ const require_RenderToolContext = require('./RenderToolContext-CBNKcJqz.cjs');
2
+ let react = require("react");
3
+ react = require_RenderToolContext.__toESM(react);
4
+ let _copilotkit_react_core_v2_context = require("@copilotkit/react-core/v2/context");
5
+ let _copilotkit_react_core_v2_headless = require("@copilotkit/react-core/v2/headless");
6
+ let _copilotkit_shared = require("@copilotkit/shared");
7
+ let react_jsx_runtime = require("react/jsx-runtime");
8
+
9
+ //#region src/CopilotKitProvider.tsx
10
+ /**
11
+ * CopilotKit provider for React Native.
12
+ *
13
+ * A lightweight alternative to the web CopilotKitProvider that avoids
14
+ * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).
15
+ *
16
+ * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,
17
+ * so a separate `import "@copilotkit/react-native/polyfills"` is no longer
18
+ * required (though it remains available for advanced use).
19
+ *
20
+ * Usage:
21
+ * ```tsx
22
+ * import { CopilotKitProvider } from "@copilotkit/react-native";
23
+ *
24
+ * function App() {
25
+ * return (
26
+ * <CopilotKitProvider runtimeUrl="https://your-runtime/api/copilotkit">
27
+ * <ChatScreen />
28
+ * </CopilotKitProvider>
29
+ * );
30
+ * }
31
+ * ```
32
+ */
33
+ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp, credentials, useSingleEndpoint, properties, onError, debug, defaultThrottleMs }) => {
34
+ const resolvedHeaders = typeof headersProp === "function" ? headersProp() : headersProp;
35
+ const stableHeaders = (0, react.useMemo)(() => resolvedHeaders ?? {}, [JSON.stringify(resolvedHeaders)]);
36
+ const stableProperties = (0, react.useMemo)(() => properties ?? {}, [JSON.stringify(properties)]);
37
+ const copilotkitRef = (0, react.useRef)(null);
38
+ if (copilotkitRef.current === null) {
39
+ const instance = new _copilotkit_react_core_v2_headless.CopilotKitCoreReact({
40
+ runtimeUrl,
41
+ runtimeTransport: useSingleEndpoint === true ? "single" : useSingleEndpoint === false ? "rest" : "auto",
42
+ headers: stableHeaders,
43
+ credentials,
44
+ properties: stableProperties,
45
+ debug
46
+ });
47
+ if (defaultThrottleMs !== void 0) instance.setDefaultThrottleMs(defaultThrottleMs);
48
+ copilotkitRef.current = instance;
49
+ }
50
+ const copilotkit = copilotkitRef.current;
51
+ (0, react.useEffect)(() => {
52
+ copilotkit.setRuntimeUrl(runtimeUrl);
53
+ copilotkit.setRuntimeTransport(useSingleEndpoint === true ? "single" : useSingleEndpoint === false ? "rest" : "auto");
54
+ copilotkit.setHeaders(stableHeaders);
55
+ copilotkit.setCredentials(credentials);
56
+ copilotkit.setProperties(stableProperties);
57
+ copilotkit.setDebug(debug);
58
+ }, [
59
+ runtimeUrl,
60
+ useSingleEndpoint,
61
+ stableHeaders,
62
+ credentials,
63
+ stableProperties,
64
+ debug,
65
+ copilotkit
66
+ ]);
67
+ (0, react.useEffect)(() => {
68
+ copilotkit.setDefaultThrottleMs(defaultThrottleMs);
69
+ }, [copilotkit, defaultThrottleMs]);
70
+ const [executingToolCallIds, setExecutingToolCallIds] = (0, react.useState)(() => /* @__PURE__ */ new Set());
71
+ const [runtimeLicenseStatus, setRuntimeLicenseStatus] = (0, react.useState)(void 0);
72
+ const onErrorRef = (0, react.useRef)(onError);
73
+ (0, react.useEffect)(() => {
74
+ onErrorRef.current = onError;
75
+ }, [onError]);
76
+ (0, react.useEffect)(() => {
77
+ const subscription = copilotkit.subscribe({
78
+ onToolExecutionStart: ({ toolCallId }) => {
79
+ setExecutingToolCallIds((prev) => {
80
+ if (prev.has(toolCallId)) return prev;
81
+ const next = new Set(prev);
82
+ next.add(toolCallId);
83
+ return next;
84
+ });
85
+ },
86
+ onToolExecutionEnd: ({ toolCallId }) => {
87
+ setExecutingToolCallIds((prev) => {
88
+ if (!prev.has(toolCallId)) return prev;
89
+ const next = new Set(prev);
90
+ next.delete(toolCallId);
91
+ return next;
92
+ });
93
+ },
94
+ onError: (event) => {
95
+ if (onErrorRef.current) onErrorRef.current(event);
96
+ else console.error(`[CopilotKit] Error (${event.code}):`, event.error, event.context ?? {});
97
+ },
98
+ onRuntimeConnectionStatusChanged: () => {
99
+ setRuntimeLicenseStatus(copilotkit.licenseStatus);
100
+ }
101
+ });
102
+ return () => subscription.unsubscribe();
103
+ }, [copilotkit]);
104
+ const contextValue = (0, react.useMemo)(() => ({
105
+ copilotkit,
106
+ executingToolCallIds
107
+ }), [copilotkit, executingToolCallIds]);
108
+ const licenseContextValue = (0, react.useMemo)(() => (0, _copilotkit_shared.createLicenseContextValue)(runtimeLicenseStatus), [runtimeLicenseStatus]);
109
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkit_react_core_v2_context.CopilotKitContext.Provider, {
110
+ value: contextValue,
111
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkit_react_core_v2_context.LicenseContext.Provider, {
112
+ value: licenseContextValue,
113
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_RenderToolContext.RenderToolProvider, { children })
114
+ })
115
+ });
116
+ };
117
+
118
+ //#endregion
119
+ //#region src/hooks/useRenderTool.ts
120
+ /**
121
+ * Hook that registers a frontend tool AND a render function for it.
122
+ *
123
+ * This bridges `useFrontendTool` (which handles tool registration and
124
+ * handler execution) with a render registry so that CopilotChat can
125
+ * render React Native elements inline when it encounters tool call messages.
126
+ *
127
+ * @example
128
+ * ```tsx
129
+ * useRenderTool({
130
+ * name: "showWeather",
131
+ * description: "Display weather information",
132
+ * parameters: z.object({ city: z.string(), temp: z.number() }),
133
+ * render: ({ args, status }) => (
134
+ * <View>
135
+ * <Text>{args.city}: {args.temp}</Text>
136
+ * {status === "executing" && <ActivityIndicator />}
137
+ * </View>
138
+ * ),
139
+ * handler: async ({ city }) => {
140
+ * return { forecast: "sunny" };
141
+ * },
142
+ * });
143
+ * ```
144
+ */
145
+ function useRenderTool(options, deps) {
146
+ const { name, description, parameters, render, handler, agentId } = options;
147
+ const { register } = require_RenderToolContext.useRenderToolContext();
148
+ (0, _copilotkit_react_core_v2_headless.useFrontendTool)({
149
+ name,
150
+ description,
151
+ parameters,
152
+ handler,
153
+ agentId
154
+ }, deps);
155
+ const renderRef = (0, react.useRef)(render);
156
+ renderRef.current = render;
157
+ (0, react.useEffect)(() => {
158
+ const stableRender = (props) => renderRef.current(props);
159
+ return register(name, stableRender);
160
+ }, [name, register]);
161
+ }
162
+
163
+ //#endregion
164
+ Object.defineProperty(exports, 'CopilotKitProvider', {
165
+ enumerable: true,
166
+ get: function () {
167
+ return CopilotKitProvider;
168
+ }
169
+ });
170
+ Object.defineProperty(exports, 'useRenderTool', {
171
+ enumerable: true,
172
+ get: function () {
173
+ return useRenderTool;
174
+ }
175
+ });
176
+ //# sourceMappingURL=useRenderTool-DLavcsVB.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRenderTool-DLavcsVB.cjs","names":["CopilotKitCoreReact","CopilotKitContext","LicenseContext","RenderToolProvider","useRenderToolContext"],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/useRenderTool.ts"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotKitContext,\n LicenseContext,\n} from \"@copilotkit/react-core/v2/context\";\nimport type {\n CopilotKitContextValue,\n CopilotKitCoreReact as CopilotKitCoreReactInstance,\n} from \"@copilotkit/react-core/v2/context\";\nimport { CopilotKitCoreReact } from \"@copilotkit/react-core/v2/headless\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\nimport { RenderToolProvider } from \"./hooks/RenderToolContext\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => 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 /** Whether the runtime uses a single-route endpoint */\n useSingleEndpoint?: boolean;\n /** Custom properties forwarded to agents */\n properties?: Record<string, unknown>;\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n * If not provided, errors are logged to console.error.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Enable debug logging for the client-side event pipeline.\n * When `true`, enables verbose logging from the core instance.\n */\n debug?: DebugConfig;\n /**\n * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`\n * subscriptions. Individual subscriptions can override with their own `throttleMs`.\n */\n defaultThrottleMs?: number;\n // Cloud features (publicApiKey, licenseToken) — not yet supported on React Native\n}\n\n/**\n * CopilotKit provider for React Native.\n *\n * A lightweight alternative to the web CopilotKitProvider that avoids\n * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).\n *\n * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,\n * so a separate `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required (though it remains available for advanced use).\n *\n * Usage:\n * ```tsx\n * import { CopilotKitProvider } from \"@copilotkit/react-native\";\n *\n * function App() {\n * return (\n * <CopilotKitProvider runtimeUrl=\"https://your-runtime/api/copilotkit\">\n * <ChatScreen />\n * </CopilotKitProvider>\n * );\n * }\n * ```\n */\nexport const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp,\n credentials,\n useSingleEndpoint,\n properties,\n onError,\n debug,\n defaultThrottleMs,\n}) => {\n // Resolve headers from function or static object (matches web provider pattern)\n const resolvedHeaders =\n typeof headersProp === \"function\" ? headersProp() : headersProp;\n\n // Stabilize headers/properties references to avoid effect churn when callers\n // pass inline object literals (e.g. headers={{}} or the undefined default).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableHeaders = useMemo(\n () => resolvedHeaders ?? {},\n [JSON.stringify(resolvedHeaders)],\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableProperties = useMemo(\n () => properties ?? {},\n [JSON.stringify(properties)],\n );\n\n const copilotkitRef = useRef<CopilotKitCoreReactInstance | null>(null);\n\n if (copilotkitRef.current === null) {\n const instance: CopilotKitCoreReactInstance = new CopilotKitCoreReact({\n runtimeUrl,\n runtimeTransport:\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n headers: stableHeaders,\n credentials,\n properties: stableProperties,\n debug,\n });\n // Set initial defaultThrottleMs synchronously so child hooks see the\n // correct value on their first render (before useEffect fires).\n if (defaultThrottleMs !== undefined) {\n instance.setDefaultThrottleMs(defaultThrottleMs);\n }\n copilotkitRef.current = instance;\n }\n\n const copilotkit = copilotkitRef.current;\n\n // Sync props to core instance\n useEffect(() => {\n copilotkit.setRuntimeUrl(runtimeUrl);\n copilotkit.setRuntimeTransport(\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n );\n copilotkit.setHeaders(stableHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\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 onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n <RenderToolProvider>{children}</RenderToolProvider>\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./RenderToolContext\";\nimport { useRenderToolContext } from \"./RenderToolContext\";\n\n/**\n * Options for the useRenderTool hook.\n */\nexport interface UseRenderToolOptions<T extends Record<string, unknown>> {\n /** Unique name for the tool. Must match what the agent calls. */\n name: string;\n /** Human-readable description shown to the agent. */\n description: string;\n /**\n * Schema describing the tool's parameters.\n * Accepts any StandardSchemaV1-compatible schema (Zod, Valibot, ArkType, etc.).\n */\n parameters: StandardSchemaV1<unknown, T>;\n /**\n * Render function that returns a React Native element for the tool call.\n * Called by CopilotChat when it encounters a tool call message for this tool.\n *\n * Returns ReactElement | null (not ReactNode) because React Native's\n * FlatList cannot render strings or portals.\n */\n render: RenderToolFunction<T>;\n /**\n * Optional handler executed when the tool is called.\n * If omitted, the tool is render-only (the render function shows UI\n * but the tool returns no result to the agent).\n */\n handler?: (args: T) => Promise<unknown>;\n /**\n * Optional agent ID to scope this tool to a specific agent.\n */\n agentId?: string;\n}\n\n/**\n * Hook that registers a frontend tool AND a render function for it.\n *\n * This bridges `useFrontendTool` (which handles tool registration and\n * handler execution) with a render registry so that CopilotChat can\n * render React Native elements inline when it encounters tool call messages.\n *\n * @example\n * ```tsx\n * useRenderTool({\n * name: \"showWeather\",\n * description: \"Display weather information\",\n * parameters: z.object({ city: z.string(), temp: z.number() }),\n * render: ({ args, status }) => (\n * <View>\n * <Text>{args.city}: {args.temp}</Text>\n * {status === \"executing\" && <ActivityIndicator />}\n * </View>\n * ),\n * handler: async ({ city }) => {\n * return { forecast: \"sunny\" };\n * },\n * });\n * ```\n */\nexport function useRenderTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void {\n const { name, description, parameters, render, handler, agentId } = options;\n const { register } = useRenderToolContext();\n\n // Register the tool with the core system via useFrontendTool\n useFrontendTool<T>(\n {\n name,\n description,\n parameters,\n handler,\n agentId,\n },\n deps,\n );\n\n // Use a ref so the effect cleanup always has the latest render function\n const renderRef = useRef(render);\n renderRef.current = render;\n\n // Register the render function in the RenderToolContext\n useEffect(() => {\n // Wrap in a stable function that delegates to the ref\n const stableRender: RenderToolFunction<T> = (props) =>\n renderRef.current(props);\n\n const unregister = register(name, stableRender as RenderToolFunction);\n return unregister;\n }, [name, register]);\n}\n"],"mappings":"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"}
@@ -0,0 +1,164 @@
1
+ import { n as useRenderToolContext, t as RenderToolProvider } from "./RenderToolContext-D8M-JhD1.mjs";
2
+ import React, { useEffect, useMemo, useRef, useState } from "react";
3
+ import { CopilotKitContext, LicenseContext } from "@copilotkit/react-core/v2/context";
4
+ import { CopilotKitCoreReact, useFrontendTool } from "@copilotkit/react-core/v2/headless";
5
+ import { createLicenseContextValue } from "@copilotkit/shared";
6
+ import { jsx } from "react/jsx-runtime";
7
+
8
+ //#region src/CopilotKitProvider.tsx
9
+ /**
10
+ * CopilotKit provider for React Native.
11
+ *
12
+ * A lightweight alternative to the web CopilotKitProvider that avoids
13
+ * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).
14
+ *
15
+ * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,
16
+ * so a separate `import "@copilotkit/react-native/polyfills"` is no longer
17
+ * required (though it remains available for advanced use).
18
+ *
19
+ * Usage:
20
+ * ```tsx
21
+ * import { CopilotKitProvider } from "@copilotkit/react-native";
22
+ *
23
+ * function App() {
24
+ * return (
25
+ * <CopilotKitProvider runtimeUrl="https://your-runtime/api/copilotkit">
26
+ * <ChatScreen />
27
+ * </CopilotKitProvider>
28
+ * );
29
+ * }
30
+ * ```
31
+ */
32
+ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp, credentials, useSingleEndpoint, properties, onError, debug, defaultThrottleMs }) => {
33
+ const resolvedHeaders = typeof headersProp === "function" ? headersProp() : headersProp;
34
+ const stableHeaders = useMemo(() => resolvedHeaders ?? {}, [JSON.stringify(resolvedHeaders)]);
35
+ const stableProperties = useMemo(() => properties ?? {}, [JSON.stringify(properties)]);
36
+ const copilotkitRef = useRef(null);
37
+ if (copilotkitRef.current === null) {
38
+ const instance = new CopilotKitCoreReact({
39
+ runtimeUrl,
40
+ runtimeTransport: useSingleEndpoint === true ? "single" : useSingleEndpoint === false ? "rest" : "auto",
41
+ headers: stableHeaders,
42
+ credentials,
43
+ properties: stableProperties,
44
+ debug
45
+ });
46
+ if (defaultThrottleMs !== void 0) instance.setDefaultThrottleMs(defaultThrottleMs);
47
+ copilotkitRef.current = instance;
48
+ }
49
+ const copilotkit = copilotkitRef.current;
50
+ useEffect(() => {
51
+ copilotkit.setRuntimeUrl(runtimeUrl);
52
+ copilotkit.setRuntimeTransport(useSingleEndpoint === true ? "single" : useSingleEndpoint === false ? "rest" : "auto");
53
+ copilotkit.setHeaders(stableHeaders);
54
+ copilotkit.setCredentials(credentials);
55
+ copilotkit.setProperties(stableProperties);
56
+ copilotkit.setDebug(debug);
57
+ }, [
58
+ runtimeUrl,
59
+ useSingleEndpoint,
60
+ stableHeaders,
61
+ credentials,
62
+ stableProperties,
63
+ debug,
64
+ copilotkit
65
+ ]);
66
+ useEffect(() => {
67
+ copilotkit.setDefaultThrottleMs(defaultThrottleMs);
68
+ }, [copilotkit, defaultThrottleMs]);
69
+ const [executingToolCallIds, setExecutingToolCallIds] = useState(() => /* @__PURE__ */ new Set());
70
+ const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState(void 0);
71
+ const onErrorRef = useRef(onError);
72
+ useEffect(() => {
73
+ onErrorRef.current = onError;
74
+ }, [onError]);
75
+ useEffect(() => {
76
+ const subscription = copilotkit.subscribe({
77
+ onToolExecutionStart: ({ toolCallId }) => {
78
+ setExecutingToolCallIds((prev) => {
79
+ if (prev.has(toolCallId)) return prev;
80
+ const next = new Set(prev);
81
+ next.add(toolCallId);
82
+ return next;
83
+ });
84
+ },
85
+ onToolExecutionEnd: ({ toolCallId }) => {
86
+ setExecutingToolCallIds((prev) => {
87
+ if (!prev.has(toolCallId)) return prev;
88
+ const next = new Set(prev);
89
+ next.delete(toolCallId);
90
+ return next;
91
+ });
92
+ },
93
+ onError: (event) => {
94
+ if (onErrorRef.current) onErrorRef.current(event);
95
+ else console.error(`[CopilotKit] Error (${event.code}):`, event.error, event.context ?? {});
96
+ },
97
+ onRuntimeConnectionStatusChanged: () => {
98
+ setRuntimeLicenseStatus(copilotkit.licenseStatus);
99
+ }
100
+ });
101
+ return () => subscription.unsubscribe();
102
+ }, [copilotkit]);
103
+ const contextValue = useMemo(() => ({
104
+ copilotkit,
105
+ executingToolCallIds
106
+ }), [copilotkit, executingToolCallIds]);
107
+ const licenseContextValue = useMemo(() => createLicenseContextValue(runtimeLicenseStatus), [runtimeLicenseStatus]);
108
+ return /* @__PURE__ */ jsx(CopilotKitContext.Provider, {
109
+ value: contextValue,
110
+ children: /* @__PURE__ */ jsx(LicenseContext.Provider, {
111
+ value: licenseContextValue,
112
+ children: /* @__PURE__ */ jsx(RenderToolProvider, { children })
113
+ })
114
+ });
115
+ };
116
+
117
+ //#endregion
118
+ //#region src/hooks/useRenderTool.ts
119
+ /**
120
+ * Hook that registers a frontend tool AND a render function for it.
121
+ *
122
+ * This bridges `useFrontendTool` (which handles tool registration and
123
+ * handler execution) with a render registry so that CopilotChat can
124
+ * render React Native elements inline when it encounters tool call messages.
125
+ *
126
+ * @example
127
+ * ```tsx
128
+ * useRenderTool({
129
+ * name: "showWeather",
130
+ * description: "Display weather information",
131
+ * parameters: z.object({ city: z.string(), temp: z.number() }),
132
+ * render: ({ args, status }) => (
133
+ * <View>
134
+ * <Text>{args.city}: {args.temp}</Text>
135
+ * {status === "executing" && <ActivityIndicator />}
136
+ * </View>
137
+ * ),
138
+ * handler: async ({ city }) => {
139
+ * return { forecast: "sunny" };
140
+ * },
141
+ * });
142
+ * ```
143
+ */
144
+ function useRenderTool(options, deps) {
145
+ const { name, description, parameters, render, handler, agentId } = options;
146
+ const { register } = useRenderToolContext();
147
+ useFrontendTool({
148
+ name,
149
+ description,
150
+ parameters,
151
+ handler,
152
+ agentId
153
+ }, deps);
154
+ const renderRef = useRef(render);
155
+ renderRef.current = render;
156
+ useEffect(() => {
157
+ const stableRender = (props) => renderRef.current(props);
158
+ return register(name, stableRender);
159
+ }, [name, register]);
160
+ }
161
+
162
+ //#endregion
163
+ export { CopilotKitProvider as n, useRenderTool as t };
164
+ //# sourceMappingURL=useRenderTool-DUqpS97B.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRenderTool-DUqpS97B.mjs","names":[],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/useRenderTool.ts"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotKitContext,\n LicenseContext,\n} from \"@copilotkit/react-core/v2/context\";\nimport type {\n CopilotKitContextValue,\n CopilotKitCoreReact as CopilotKitCoreReactInstance,\n} from \"@copilotkit/react-core/v2/context\";\nimport { CopilotKitCoreReact } from \"@copilotkit/react-core/v2/headless\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\nimport { RenderToolProvider } from \"./hooks/RenderToolContext\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => 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 /** Whether the runtime uses a single-route endpoint */\n useSingleEndpoint?: boolean;\n /** Custom properties forwarded to agents */\n properties?: Record<string, unknown>;\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n * If not provided, errors are logged to console.error.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Enable debug logging for the client-side event pipeline.\n * When `true`, enables verbose logging from the core instance.\n */\n debug?: DebugConfig;\n /**\n * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`\n * subscriptions. Individual subscriptions can override with their own `throttleMs`.\n */\n defaultThrottleMs?: number;\n // Cloud features (publicApiKey, licenseToken) — not yet supported on React Native\n}\n\n/**\n * CopilotKit provider for React Native.\n *\n * A lightweight alternative to the web CopilotKitProvider that avoids\n * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).\n *\n * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,\n * so a separate `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required (though it remains available for advanced use).\n *\n * Usage:\n * ```tsx\n * import { CopilotKitProvider } from \"@copilotkit/react-native\";\n *\n * function App() {\n * return (\n * <CopilotKitProvider runtimeUrl=\"https://your-runtime/api/copilotkit\">\n * <ChatScreen />\n * </CopilotKitProvider>\n * );\n * }\n * ```\n */\nexport const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp,\n credentials,\n useSingleEndpoint,\n properties,\n onError,\n debug,\n defaultThrottleMs,\n}) => {\n // Resolve headers from function or static object (matches web provider pattern)\n const resolvedHeaders =\n typeof headersProp === \"function\" ? headersProp() : headersProp;\n\n // Stabilize headers/properties references to avoid effect churn when callers\n // pass inline object literals (e.g. headers={{}} or the undefined default).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableHeaders = useMemo(\n () => resolvedHeaders ?? {},\n [JSON.stringify(resolvedHeaders)],\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableProperties = useMemo(\n () => properties ?? {},\n [JSON.stringify(properties)],\n );\n\n const copilotkitRef = useRef<CopilotKitCoreReactInstance | null>(null);\n\n if (copilotkitRef.current === null) {\n const instance: CopilotKitCoreReactInstance = new CopilotKitCoreReact({\n runtimeUrl,\n runtimeTransport:\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n headers: stableHeaders,\n credentials,\n properties: stableProperties,\n debug,\n });\n // Set initial defaultThrottleMs synchronously so child hooks see the\n // correct value on their first render (before useEffect fires).\n if (defaultThrottleMs !== undefined) {\n instance.setDefaultThrottleMs(defaultThrottleMs);\n }\n copilotkitRef.current = instance;\n }\n\n const copilotkit = copilotkitRef.current;\n\n // Sync props to core instance\n useEffect(() => {\n copilotkit.setRuntimeUrl(runtimeUrl);\n copilotkit.setRuntimeTransport(\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n );\n copilotkit.setHeaders(stableHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\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 onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n <RenderToolProvider>{children}</RenderToolProvider>\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./RenderToolContext\";\nimport { useRenderToolContext } from \"./RenderToolContext\";\n\n/**\n * Options for the useRenderTool hook.\n */\nexport interface UseRenderToolOptions<T extends Record<string, unknown>> {\n /** Unique name for the tool. Must match what the agent calls. */\n name: string;\n /** Human-readable description shown to the agent. */\n description: string;\n /**\n * Schema describing the tool's parameters.\n * Accepts any StandardSchemaV1-compatible schema (Zod, Valibot, ArkType, etc.).\n */\n parameters: StandardSchemaV1<unknown, T>;\n /**\n * Render function that returns a React Native element for the tool call.\n * Called by CopilotChat when it encounters a tool call message for this tool.\n *\n * Returns ReactElement | null (not ReactNode) because React Native's\n * FlatList cannot render strings or portals.\n */\n render: RenderToolFunction<T>;\n /**\n * Optional handler executed when the tool is called.\n * If omitted, the tool is render-only (the render function shows UI\n * but the tool returns no result to the agent).\n */\n handler?: (args: T) => Promise<unknown>;\n /**\n * Optional agent ID to scope this tool to a specific agent.\n */\n agentId?: string;\n}\n\n/**\n * Hook that registers a frontend tool AND a render function for it.\n *\n * This bridges `useFrontendTool` (which handles tool registration and\n * handler execution) with a render registry so that CopilotChat can\n * render React Native elements inline when it encounters tool call messages.\n *\n * @example\n * ```tsx\n * useRenderTool({\n * name: \"showWeather\",\n * description: \"Display weather information\",\n * parameters: z.object({ city: z.string(), temp: z.number() }),\n * render: ({ args, status }) => (\n * <View>\n * <Text>{args.city}: {args.temp}</Text>\n * {status === \"executing\" && <ActivityIndicator />}\n * </View>\n * ),\n * handler: async ({ city }) => {\n * return { forecast: \"sunny\" };\n * },\n * });\n * ```\n */\nexport function useRenderTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void {\n const { name, description, parameters, render, handler, agentId } = options;\n const { register } = useRenderToolContext();\n\n // Register the tool with the core system via useFrontendTool\n useFrontendTool<T>(\n {\n name,\n description,\n parameters,\n handler,\n agentId,\n },\n deps,\n );\n\n // Use a ref so the effect cleanup always has the latest render function\n const renderRef = useRef(render);\n renderRef.current = render;\n\n // Register the render function in the RenderToolContext\n useEffect(() => {\n // Wrap in a stable function that delegates to the ref\n const stableRender: RenderToolFunction<T> = (props) =>\n renderRef.current(props);\n\n const unregister = register(name, stableRender as RenderToolFunction);\n return unregister;\n }, [name, register]);\n}\n"],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkit/react-native",
3
- "version": "1.63.2-canary.1784918757",
3
+ "version": "1.63.3-canary.rc-1",
4
4
  "private": false,
5
5
  "keywords": [
6
6
  "ai",
@@ -19,6 +19,7 @@
19
19
  "type": "module",
20
20
  "sideEffects": [
21
21
  "./dist/index.*",
22
+ "./dist/headless.*",
22
23
  "./dist/polyfills.*",
23
24
  "./dist/polyfills/**/*"
24
25
  ],
@@ -30,6 +31,10 @@
30
31
  "import": "./dist/index.mjs",
31
32
  "require": "./dist/index.cjs"
32
33
  },
34
+ "./headless": {
35
+ "import": "./dist/headless.mjs",
36
+ "require": "./dist/headless.cjs"
37
+ },
33
38
  "./polyfills": {
34
39
  "import": "./dist/polyfills.mjs",
35
40
  "require": "./dist/polyfills.cjs"
@@ -67,9 +72,9 @@
67
72
  "@ag-ui/client": "0.0.57",
68
73
  "text-encoding": "^0.7.0",
69
74
  "web-streams-polyfill": "^4.2.0",
70
- "@copilotkit/core": "1.63.2-canary.1784918757",
71
- "@copilotkit/react-core": "1.63.2-canary.1784918757",
72
- "@copilotkit/shared": "1.63.2-canary.1784918757"
75
+ "@copilotkit/core": "1.63.3-canary.rc-1",
76
+ "@copilotkit/shared": "1.63.3-canary.rc-1",
77
+ "@copilotkit/react-core": "1.63.3-canary.rc-1"
73
78
  },
74
79
  "devDependencies": {
75
80
  "@testing-library/react": "^16.3.0",
@@ -0,0 +1,151 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ /**
6
+ * Guards the `@copilotkit/react-native/headless` entry (src/headless.ts).
7
+ *
8
+ * The whole point of the headless entry is that a consumer using only the
9
+ * provider + agent/tool hooks does NOT have to install (or Metro-stub) the
10
+ * chat/attachment native peer deps. That guarantee lives in the *static import
11
+ * graph*: if any module reachable from src/headless.ts imports the chat
12
+ * components or `useAttachments` — which pull `@gorhom/bottom-sheet`,
13
+ * `expo-document-picker`, `expo-file-system` — the guarantee is silently broken
14
+ * (nothing in a normal typecheck/test catches it, because those are optional
15
+ * peers). This walks the relative-import graph and fails if that happens.
16
+ *
17
+ * Mirrors the export-surface guard added for @copilotkit/react-core/v2/headless
18
+ * (PR #5883).
19
+ */
20
+
21
+ const srcDir = path.resolve(__dirname, "..");
22
+ const headlessEntry = path.join(srcDir, "headless.ts");
23
+
24
+ // Bare module specifiers a headless consumer must NOT be forced to resolve.
25
+ const FORBIDDEN_BARE = [
26
+ "@gorhom/bottom-sheet",
27
+ "expo-document-picker",
28
+ "expo-file-system",
29
+ "react-native-streamdown",
30
+ ];
31
+
32
+ // Local modules that carry the chat UI / native-attachment stack.
33
+ const FORBIDDEN_LOCAL = [
34
+ "CopilotChat",
35
+ "CopilotModal",
36
+ "CopilotSidebar",
37
+ "CopilotPopup",
38
+ "use-attachments",
39
+ ];
40
+
41
+ const importRe =
42
+ /(?:import|export)\s+(?:type\s+)?[^"']*?from\s+["']([^"']+)["']|import\s+["']([^"']+)["']/g;
43
+
44
+ function resolveLocal(fromFile: string, spec: string): string | null {
45
+ if (!spec.startsWith(".")) return null;
46
+ const base = path.resolve(path.dirname(fromFile), spec);
47
+ const candidates = [
48
+ base,
49
+ `${base}.ts`,
50
+ `${base}.tsx`,
51
+ path.join(base, "index.ts"),
52
+ path.join(base, "index.tsx"),
53
+ ];
54
+ for (const c of candidates) {
55
+ if (fs.existsSync(c) && fs.statSync(c).isFile()) return c;
56
+ }
57
+ return null;
58
+ }
59
+
60
+ function walkGraph(entry: string) {
61
+ const seen = new Set<string>();
62
+ const bareSpecs = new Set<string>();
63
+ const localFiles = new Set<string>();
64
+ const stack = [entry];
65
+
66
+ while (stack.length) {
67
+ const file = stack.pop()!;
68
+ if (seen.has(file)) continue;
69
+ seen.add(file);
70
+
71
+ const code = fs.readFileSync(file, "utf8");
72
+ for (const m of code.matchAll(importRe)) {
73
+ const spec = m[1] ?? m[2];
74
+ if (!spec) continue;
75
+ if (spec.startsWith(".")) {
76
+ const resolved = resolveLocal(file, spec);
77
+ if (resolved) {
78
+ localFiles.add(resolved);
79
+ stack.push(resolved);
80
+ }
81
+ } else {
82
+ bareSpecs.add(spec);
83
+ }
84
+ }
85
+ }
86
+ return { seen, bareSpecs, localFiles };
87
+ }
88
+
89
+ describe("@copilotkit/react-native/headless entry", () => {
90
+ it("has a headless entry file", () => {
91
+ expect(fs.existsSync(headlessEntry)).toBe(true);
92
+ });
93
+
94
+ const { seen, bareSpecs } = walkGraph(headlessEntry);
95
+
96
+ it("does not pull chat/attachment native peer deps into its import graph", () => {
97
+ const leaked = FORBIDDEN_BARE.filter((dep) =>
98
+ [...bareSpecs].some((s) => s === dep || s.startsWith(`${dep}/`)),
99
+ );
100
+ expect(
101
+ leaked,
102
+ `headless graph must not import: ${leaked.join(", ")}`,
103
+ ).toEqual([]);
104
+ });
105
+
106
+ it("does not reach the chat UI / useAttachments modules", () => {
107
+ const reached = [...seen].filter((f) =>
108
+ FORBIDDEN_LOCAL.some((name) =>
109
+ path
110
+ .basename(f)
111
+ .replace(/\.tsx?$/, "")
112
+ .includes(name),
113
+ ),
114
+ );
115
+ expect(
116
+ reached,
117
+ `headless graph must not reach: ${reached
118
+ .map((f) => path.relative(srcDir, f))
119
+ .join(", ")}`,
120
+ ).toEqual([]);
121
+ });
122
+
123
+ it("does export the provider + core headless hooks", async () => {
124
+ const mod = await import("../headless");
125
+ for (const name of [
126
+ "CopilotKitProvider",
127
+ "useCopilotKit",
128
+ "useAgent",
129
+ "useFrontendTool",
130
+ "useRenderTool",
131
+ "RenderToolProvider",
132
+ ]) {
133
+ expect(mod, `missing export: ${name}`).toHaveProperty(name);
134
+ }
135
+ });
136
+
137
+ it("does NOT re-export chat components or useAttachments from the headless entry", async () => {
138
+ const mod = await import("../headless");
139
+ for (const name of [
140
+ "CopilotChat",
141
+ "CopilotModal",
142
+ "CopilotSidebar",
143
+ "CopilotPopup",
144
+ "useAttachments",
145
+ ]) {
146
+ expect(mod, `headless entry must not export: ${name}`).not.toHaveProperty(
147
+ name,
148
+ );
149
+ }
150
+ });
151
+ });