@copilotkit/react-native 1.70.2 → 1.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/USAGE.md +76 -5
  2. package/dist/headless.cjs +1 -1
  3. package/dist/headless.d.cts +59 -3
  4. package/dist/headless.d.mts +59 -3
  5. package/dist/headless.mjs +1 -1
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +3 -3
  8. package/dist/index.d.mts +3 -3
  9. package/dist/index.mjs +1 -1
  10. package/dist/useRenderTool-DFz206nL.d.cts +149 -0
  11. package/dist/useRenderTool-DsCxzyAP.d.mts +149 -0
  12. package/dist/useRenderTool-L3Rw6SYD.cjs +298 -0
  13. package/dist/useRenderTool-L3Rw6SYD.cjs.map +1 -0
  14. package/dist/useRenderTool-pLM3upcs.mjs +285 -0
  15. package/dist/useRenderTool-pLM3upcs.mjs.map +1 -0
  16. package/package.json +4 -4
  17. package/src/__mocks__/test-copilotkit.tsx +14 -2
  18. package/src/__tests__/frontend-tool-render.test-d.tsx +148 -0
  19. package/src/__tests__/headless-entry-surface.test.ts +232 -2
  20. package/src/__tests__/headless-value-exports.test.ts +16 -5
  21. package/src/components/__tests__/CopilotChatToolCalls.test.tsx +26 -22
  22. package/src/headless.ts +79 -7
  23. package/src/hooks/__tests__/render-tool-call.integration.test.tsx +17 -15
  24. package/src/hooks/__tests__/useRenderTool.test.tsx +733 -202
  25. package/src/hooks/useRenderTool.ts +482 -49
  26. package/dist/useRenderTool-BBxnOOeJ.d.mts +0 -161
  27. package/dist/useRenderTool-BWo11PCL.d.cts +0 -161
  28. package/dist/useRenderTool-CKEPq7MQ.cjs +0 -162
  29. package/dist/useRenderTool-CKEPq7MQ.cjs.map +0 -1
  30. package/dist/useRenderTool-l7M-I8rT.mjs +0 -149
  31. package/dist/useRenderTool-l7M-I8rT.mjs.map +0 -1
  32. package/src/hooks/index.ts +0 -3
  33. package/src/hooks/render-tool-types.ts +0 -55
@@ -1,161 +0,0 @@
1
- import React, { ReactNode } from "react";
2
- import { ReactToolCallRenderer } from "@copilotkit/react-core/v2/headless";
3
- import { DebugConfig, StandardSchemaV1 } from "@copilotkit/shared";
4
- import { CopilotKitCoreErrorCode } from "@copilotkit/core";
5
-
6
- //#region src/CopilotKitProvider.d.ts
7
- interface CopilotKitNativeProviderProps {
8
- children: ReactNode;
9
- /** URL of the CopilotKit runtime endpoint */
10
- runtimeUrl: string;
11
- /** Custom headers sent with every request */
12
- headers?: Record<string, string> | (() => Record<string, string>);
13
- /**
14
- * Credentials mode for fetch requests (e.g., "include" for HTTP-only cookies in cross-origin requests).
15
- */
16
- credentials?: RequestCredentials;
17
- /** Whether the runtime uses a single-route endpoint */
18
- useSingleEndpoint?: boolean;
19
- /** Custom properties forwarded to agents */
20
- properties?: Record<string, unknown>;
21
- /**
22
- * Error handler called when CopilotKit encounters an error.
23
- * Fires for all error types (runtime connection failures, agent errors, tool errors).
24
- * If not provided, errors are logged to console.error.
25
- */
26
- onError?: (event: {
27
- error: Error;
28
- code: CopilotKitCoreErrorCode;
29
- context: Record<string, any>;
30
- }) => void | Promise<void>;
31
- /**
32
- * Enable debug logging for the client-side event pipeline.
33
- * When `true`, enables verbose logging from the core instance.
34
- */
35
- debug?: DebugConfig;
36
- /**
37
- * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`
38
- * subscriptions. Individual subscriptions can override with their own `throttleMs`.
39
- */
40
- defaultThrottleMs?: number;
41
- }
42
- /**
43
- * CopilotKit provider for React Native.
44
- *
45
- * A lightweight alternative to the web CopilotKitProvider that avoids
46
- * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).
47
- *
48
- * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,
49
- * so a separate `import "@copilotkit/react-native/polyfills"` is no longer
50
- * required (though it remains available for advanced use).
51
- *
52
- * Usage:
53
- * ```tsx
54
- * import { CopilotKitProvider } from "@copilotkit/react-native";
55
- *
56
- * function App() {
57
- * return (
58
- * <CopilotKitProvider runtimeUrl="https://your-runtime/api/copilotkit">
59
- * <ChatScreen />
60
- * </CopilotKitProvider>
61
- * );
62
- * }
63
- * ```
64
- */
65
- declare const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps>;
66
- //#endregion
67
- //#region src/hooks/render-tool-types.d.ts
68
- /**
69
- * Props a React Native render function receives for a tool call.
70
- *
71
- * DERIVED from react-core's canonical `ReactToolCallRenderer` contract rather
72
- * than declared separately. This is deliberate: RN previously declared its own
73
- * shape and drifted from that contract — RN's `status` was a two-member
74
- * `"executing" | "complete"` union with no in-progress state, RN omitted
75
- * `name`/`toolCallId` entirely, and RN's `args` was unconditionally the full
76
- * `T`, promising complete arguments even before they had finished streaming.
77
- *
78
- * What the derivation buys, precisely: RN's props cannot drift from
79
- * `ReactToolCallRenderer` — the contract every registered renderer is
80
- * actually invoked against, and the type this alias reads through
81
- * `React.ComponentProps`. Change that contract and RN's public type changes
82
- * with it, so `check-types` names every RN renderer the change breaks.
83
- *
84
- * What it does NOT buy: parity with the type react-core *publicly exports*
85
- * under this same name. Web's `RenderToolProps<S>`
86
- * (react-core `src/v2/hooks/use-render-tool.tsx`) is a separate union, generic
87
- * over a schema rather than over the parsed args, carrying arguments under
88
- * `parameters` (not `args`) and declaring `status` as the string literals
89
- * `"inProgress"` / `"executing"` / `"complete"` rather than as `ToolCallStatus`
90
- * members. Both divergences are live today and nothing type-checks them shut:
91
- * the two types share no structural relation, and the one place they meet —
92
- * react-core's own bridge, which spreads the enum-typed renderer props into
93
- * the literal-typed slot — compiles because a string-enum member is
94
- * assignable to its own literal type (not the reverse). Web's `status` is a
95
- * widening of the canonical contract, not a derivation from it. RN's entry
96
- * point also re-exports web's three `RenderTool*Props` arms, so both shapes
97
- * ship under confusingly similar names.
98
- *
99
- * `status` is the discriminant of a three-arm union, typed as the
100
- * `ToolCallStatus` enum (`@copilotkit/core`), so narrow with the enum members
101
- * rather than the raw strings: `args` is `Partial<T>` only on
102
- * `ToolCallStatus.InProgress`, and `result` is a string only on
103
- * `ToolCallStatus.Complete`.
104
- */
105
- type RenderToolProps<T = Record<string, unknown>> = React.ComponentProps<ReactToolCallRenderer<T>["render"]>;
106
- /**
107
- * A render function returning a React Native element.
108
- *
109
- * This is the one place RN legitimately narrows `ReactToolCallRenderer`:
110
- * `FlatList`'s `renderItem` cannot render strings or portals, so RN requires
111
- * `ReactElement | null` where that contract permits any `ReactNode`. The PROPS
112
- * come from it unchanged; only the return type is platform-specific.
113
- */
114
- type RenderToolFunction<T = Record<string, unknown>> = (props: RenderToolProps<T>) => React.ReactElement | null;
115
- //#endregion
116
- //#region src/hooks/useRenderTool.d.ts
117
- /**
118
- * Options for the useRenderTool hook.
119
- */
120
- interface UseRenderToolOptions<T extends Record<string, unknown>> {
121
- /** Unique name for the tool. Must match what the agent calls. */
122
- name: string;
123
- /** Human-readable description shown to the agent. */
124
- description: string;
125
- /** Schema describing the tool's parameters (any StandardSchemaV1 library). */
126
- parameters: StandardSchemaV1<unknown, T>;
127
- /**
128
- * Render function returning a React Native element for the tool call.
129
- * Rendered by `CopilotChat` inline, and by `useRenderToolCall()` anywhere else.
130
- *
131
- * Arguments STREAM: on `status: "inProgress"` the props are partial, because
132
- * the model has not finished writing the JSON. Write renderers that tolerate
133
- * missing fields — that is what makes UI build progressively.
134
- */
135
- render: RenderToolFunction<T>;
136
- /** Optional handler. Omit for render-only (display IS the effect). */
137
- handler?: (args: T) => Promise<unknown>;
138
- /** Scope this tool to a single agent. */
139
- agentId?: string;
140
- }
141
- /**
142
- * Registers a frontend tool AND its renderer.
143
- *
144
- * Registration goes through react-core's `useFrontendTool`, which writes the
145
- * renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry
146
- * that RN's provider already instantiates. There is deliberately NO React
147
- * Native-local registry: this package previously kept its own Map, which meant
148
- * `useComponent` (registering into core's) rendered nowhere on RN, and renderers
149
- * were dropped from chat history on unmount.
150
- */
151
- /**
152
- * @param deps Optional dependency array. The `render` function is captured at
153
- * registration and only refreshed when `deps` change — it does NOT re-read the
154
- * latest closure on every render. If your `render` closes over component state
155
- * or props that change over time, you MUST pass those values in `deps`, or the
156
- * chat will keep painting with the stale closure.
157
- */
158
- declare function useRenderTool<T extends Record<string, unknown> = Record<string, unknown>>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void;
159
- //#endregion
160
- export { CopilotKitNativeProviderProps as a, RenderToolProps as i, useRenderTool as n, CopilotKitProvider as o, RenderToolFunction as r, UseRenderToolOptions as t };
161
- //# sourceMappingURL=useRenderTool-BBxnOOeJ.d.mts.map
@@ -1,161 +0,0 @@
1
- import React, { ReactNode } from "react";
2
- import { CopilotKitCoreErrorCode } from "@copilotkit/core";
3
- import { DebugConfig, StandardSchemaV1 } from "@copilotkit/shared";
4
- import { ReactToolCallRenderer } from "@copilotkit/react-core/v2/headless";
5
-
6
- //#region src/CopilotKitProvider.d.ts
7
- interface CopilotKitNativeProviderProps {
8
- children: ReactNode;
9
- /** URL of the CopilotKit runtime endpoint */
10
- runtimeUrl: string;
11
- /** Custom headers sent with every request */
12
- headers?: Record<string, string> | (() => Record<string, string>);
13
- /**
14
- * Credentials mode for fetch requests (e.g., "include" for HTTP-only cookies in cross-origin requests).
15
- */
16
- credentials?: RequestCredentials;
17
- /** Whether the runtime uses a single-route endpoint */
18
- useSingleEndpoint?: boolean;
19
- /** Custom properties forwarded to agents */
20
- properties?: Record<string, unknown>;
21
- /**
22
- * Error handler called when CopilotKit encounters an error.
23
- * Fires for all error types (runtime connection failures, agent errors, tool errors).
24
- * If not provided, errors are logged to console.error.
25
- */
26
- onError?: (event: {
27
- error: Error;
28
- code: CopilotKitCoreErrorCode;
29
- context: Record<string, any>;
30
- }) => void | Promise<void>;
31
- /**
32
- * Enable debug logging for the client-side event pipeline.
33
- * When `true`, enables verbose logging from the core instance.
34
- */
35
- debug?: DebugConfig;
36
- /**
37
- * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`
38
- * subscriptions. Individual subscriptions can override with their own `throttleMs`.
39
- */
40
- defaultThrottleMs?: number;
41
- }
42
- /**
43
- * CopilotKit provider for React Native.
44
- *
45
- * A lightweight alternative to the web CopilotKitProvider that avoids
46
- * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).
47
- *
48
- * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,
49
- * so a separate `import "@copilotkit/react-native/polyfills"` is no longer
50
- * required (though it remains available for advanced use).
51
- *
52
- * Usage:
53
- * ```tsx
54
- * import { CopilotKitProvider } from "@copilotkit/react-native";
55
- *
56
- * function App() {
57
- * return (
58
- * <CopilotKitProvider runtimeUrl="https://your-runtime/api/copilotkit">
59
- * <ChatScreen />
60
- * </CopilotKitProvider>
61
- * );
62
- * }
63
- * ```
64
- */
65
- declare const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps>;
66
- //#endregion
67
- //#region src/hooks/render-tool-types.d.ts
68
- /**
69
- * Props a React Native render function receives for a tool call.
70
- *
71
- * DERIVED from react-core's canonical `ReactToolCallRenderer` contract rather
72
- * than declared separately. This is deliberate: RN previously declared its own
73
- * shape and drifted from that contract — RN's `status` was a two-member
74
- * `"executing" | "complete"` union with no in-progress state, RN omitted
75
- * `name`/`toolCallId` entirely, and RN's `args` was unconditionally the full
76
- * `T`, promising complete arguments even before they had finished streaming.
77
- *
78
- * What the derivation buys, precisely: RN's props cannot drift from
79
- * `ReactToolCallRenderer` — the contract every registered renderer is
80
- * actually invoked against, and the type this alias reads through
81
- * `React.ComponentProps`. Change that contract and RN's public type changes
82
- * with it, so `check-types` names every RN renderer the change breaks.
83
- *
84
- * What it does NOT buy: parity with the type react-core *publicly exports*
85
- * under this same name. Web's `RenderToolProps<S>`
86
- * (react-core `src/v2/hooks/use-render-tool.tsx`) is a separate union, generic
87
- * over a schema rather than over the parsed args, carrying arguments under
88
- * `parameters` (not `args`) and declaring `status` as the string literals
89
- * `"inProgress"` / `"executing"` / `"complete"` rather than as `ToolCallStatus`
90
- * members. Both divergences are live today and nothing type-checks them shut:
91
- * the two types share no structural relation, and the one place they meet —
92
- * react-core's own bridge, which spreads the enum-typed renderer props into
93
- * the literal-typed slot — compiles because a string-enum member is
94
- * assignable to its own literal type (not the reverse). Web's `status` is a
95
- * widening of the canonical contract, not a derivation from it. RN's entry
96
- * point also re-exports web's three `RenderTool*Props` arms, so both shapes
97
- * ship under confusingly similar names.
98
- *
99
- * `status` is the discriminant of a three-arm union, typed as the
100
- * `ToolCallStatus` enum (`@copilotkit/core`), so narrow with the enum members
101
- * rather than the raw strings: `args` is `Partial<T>` only on
102
- * `ToolCallStatus.InProgress`, and `result` is a string only on
103
- * `ToolCallStatus.Complete`.
104
- */
105
- type RenderToolProps<T = Record<string, unknown>> = React.ComponentProps<ReactToolCallRenderer<T>["render"]>;
106
- /**
107
- * A render function returning a React Native element.
108
- *
109
- * This is the one place RN legitimately narrows `ReactToolCallRenderer`:
110
- * `FlatList`'s `renderItem` cannot render strings or portals, so RN requires
111
- * `ReactElement | null` where that contract permits any `ReactNode`. The PROPS
112
- * come from it unchanged; only the return type is platform-specific.
113
- */
114
- type RenderToolFunction<T = Record<string, unknown>> = (props: RenderToolProps<T>) => React.ReactElement | null;
115
- //#endregion
116
- //#region src/hooks/useRenderTool.d.ts
117
- /**
118
- * Options for the useRenderTool hook.
119
- */
120
- interface UseRenderToolOptions<T extends Record<string, unknown>> {
121
- /** Unique name for the tool. Must match what the agent calls. */
122
- name: string;
123
- /** Human-readable description shown to the agent. */
124
- description: string;
125
- /** Schema describing the tool's parameters (any StandardSchemaV1 library). */
126
- parameters: StandardSchemaV1<unknown, T>;
127
- /**
128
- * Render function returning a React Native element for the tool call.
129
- * Rendered by `CopilotChat` inline, and by `useRenderToolCall()` anywhere else.
130
- *
131
- * Arguments STREAM: on `status: "inProgress"` the props are partial, because
132
- * the model has not finished writing the JSON. Write renderers that tolerate
133
- * missing fields — that is what makes UI build progressively.
134
- */
135
- render: RenderToolFunction<T>;
136
- /** Optional handler. Omit for render-only (display IS the effect). */
137
- handler?: (args: T) => Promise<unknown>;
138
- /** Scope this tool to a single agent. */
139
- agentId?: string;
140
- }
141
- /**
142
- * Registers a frontend tool AND its renderer.
143
- *
144
- * Registration goes through react-core's `useFrontendTool`, which writes the
145
- * renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry
146
- * that RN's provider already instantiates. There is deliberately NO React
147
- * Native-local registry: this package previously kept its own Map, which meant
148
- * `useComponent` (registering into core's) rendered nowhere on RN, and renderers
149
- * were dropped from chat history on unmount.
150
- */
151
- /**
152
- * @param deps Optional dependency array. The `render` function is captured at
153
- * registration and only refreshed when `deps` change — it does NOT re-read the
154
- * latest closure on every render. If your `render` closes over component state
155
- * or props that change over time, you MUST pass those values in `deps`, or the
156
- * chat will keep painting with the stale closure.
157
- */
158
- declare function useRenderTool<T extends Record<string, unknown> = Record<string, unknown>>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void;
159
- //#endregion
160
- export { CopilotKitNativeProviderProps as a, RenderToolProps as i, useRenderTool as n, CopilotKitProvider as o, RenderToolFunction as r, UseRenderToolOptions as t };
161
- //# sourceMappingURL=useRenderTool-BWo11PCL.d.cts.map
@@ -1,162 +0,0 @@
1
- const require_chunk = require('./chunk-C0xms8kb.cjs');
2
- let react = require("react");
3
- react = require_chunk.__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
114
- })
115
- });
116
- };
117
-
118
- //#endregion
119
- //#region src/hooks/useRenderTool.ts
120
- /**
121
- * Registers a frontend tool AND its renderer.
122
- *
123
- * Registration goes through react-core's `useFrontendTool`, which writes the
124
- * renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry
125
- * that RN's provider already instantiates. There is deliberately NO React
126
- * Native-local registry: this package previously kept its own Map, which meant
127
- * `useComponent` (registering into core's) rendered nowhere on RN, and renderers
128
- * were dropped from chat history on unmount.
129
- */
130
- /**
131
- * @param deps Optional dependency array. The `render` function is captured at
132
- * registration and only refreshed when `deps` change — it does NOT re-read the
133
- * latest closure on every render. If your `render` closes over component state
134
- * or props that change over time, you MUST pass those values in `deps`, or the
135
- * chat will keep painting with the stale closure.
136
- */
137
- function useRenderTool(options, deps) {
138
- const { name, description, parameters, render, handler, agentId } = options;
139
- (0, _copilotkit_react_core_v2_headless.useFrontendTool)({
140
- name,
141
- description,
142
- parameters,
143
- handler,
144
- agentId,
145
- render
146
- }, deps);
147
- }
148
-
149
- //#endregion
150
- Object.defineProperty(exports, 'CopilotKitProvider', {
151
- enumerable: true,
152
- get: function () {
153
- return CopilotKitProvider;
154
- }
155
- });
156
- Object.defineProperty(exports, 'useRenderTool', {
157
- enumerable: true,
158
- get: function () {
159
- return useRenderTool;
160
- }
161
- });
162
- //# sourceMappingURL=useRenderTool-CKEPq7MQ.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useRenderTool-CKEPq7MQ.cjs","names":["CopilotKitCoreReact","CopilotKitContext","LicenseContext"],"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\";\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 {children}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","import { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./render-tool-types\";\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 /** Schema describing the tool's parameters (any StandardSchemaV1 library). */\n parameters: StandardSchemaV1<unknown, T>;\n /**\n * Render function returning a React Native element for the tool call.\n * Rendered by `CopilotChat` inline, and by `useRenderToolCall()` anywhere else.\n *\n * Arguments STREAM: on `status: \"inProgress\"` the props are partial, because\n * the model has not finished writing the JSON. Write renderers that tolerate\n * missing fields — that is what makes UI build progressively.\n */\n render: RenderToolFunction<T>;\n /** Optional handler. Omit for render-only (display IS the effect). */\n handler?: (args: T) => Promise<unknown>;\n /** Scope this tool to a single agent. */\n agentId?: string;\n}\n\n/**\n * Registers a frontend tool AND its renderer.\n *\n * Registration goes through react-core's `useFrontendTool`, which writes the\n * renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry\n * that RN's provider already instantiates. There is deliberately NO React\n * Native-local registry: this package previously kept its own Map, which meant\n * `useComponent` (registering into core's) rendered nowhere on RN, and renderers\n * were dropped from chat history on unmount.\n */\n/**\n * @param deps Optional dependency array. The `render` function is captured at\n * registration and only refreshed when `deps` change — it does NOT re-read the\n * latest closure on every render. If your `render` closes over component state\n * or props that change over time, you MUST pass those values in `deps`, or the\n * chat will keep painting with the stale closure.\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\n useFrontendTool<T>(\n {\n name,\n description,\n parameters,\n handler,\n agentId,\n // No cast needed: ReactFrontendTool.render is ReactToolCallRenderer<T>[\"render\"],\n // and RenderToolFunction is derived from exactly that props type, returning\n // ReactElement | null (assignable to ComponentType's ReactNode).\n render,\n },\n deps,\n );\n}\n\nexport type { RenderToolProps, RenderToolFunction } from \"./render-tool-types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,OAAO,gBAAgB,aAAa,aAAa,GAAG;CAKtD,MAAM,yCACE,mBAAmB,EAAE,EAC3B,CAAC,KAAK,UAAU,gBAAgB,CAAC,CAClC;CAED,MAAM,4CACE,cAAc,EAAE,EACtB,CAAC,KAAK,UAAU,WAAW,CAAC,CAC7B;CAED,MAAM,kCAA2D,KAAK;AAEtE,KAAI,cAAc,YAAY,MAAM;EAClC,MAAM,WAAwC,IAAIA,uDAAoB;GACpE;GACA,kBACE,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA;GACR,SAAS;GACT;GACA,YAAY;GACZ;GACD,CAAC;AAGF,MAAI,sBAAsB,OACxB,UAAS,qBAAqB,kBAAkB;AAElD,gBAAc,UAAU;;CAG1B,MAAM,aAAa,cAAc;AAGjC,4BAAgB;AACd,aAAW,cAAc,WAAW;AACpC,aAAW,oBACT,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA,OACP;AACD,aAAW,WAAW,cAAc;AACpC,aAAW,eAAe,YAAY;AACtC,aAAW,cAAc,iBAAiB;AAC1C,aAAW,SAAS,MAAM;IACzB;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAKF,4BAAgB;AACd,aAAW,qBAAqB,kBAAkB;IACjD,CAAC,YAAY,kBAAkB,CAAC;CAKnC,MAAM,CAAC,sBAAsB,qEAErB,IAAI,KAAK,CAAC;CAElB,MAAM,CAAC,sBAAsB,+CAE3B,OAAU;CAGZ,MAAM,+BAAoB,QAAQ;AAClC,4BAAgB;AACd,aAAW,UAAU;IACpB,CAAC,QAAQ,CAAC;AAKb,4BAAgB;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;;GAEJ,UAAU,UAAU;AAClB,QAAI,WAAW,QACb,YAAW,QAAQ,MAAM;QAEzB,SAAQ,MACN,uBAAuB,MAAM,KAAK,KAClC,MAAM,OACN,MAAM,WAAW,EAAE,CACpB;;GAGL,wCAAwC;AACtC,4BAAwB,WAAW,cAAc;;GAEpD,CAAC;AACF,eAAa,aAAa,aAAa;IACtC,CAAC,WAAW,CAAC;CAEhB,MAAM,yCACG;EACL;EACA;EACD,GACD,CAAC,YAAY,qBAAqB,CACnC;CAGD,MAAM,iGAC4B,qBAAqB,EACrD,CAAC,qBAAqB,CACvB;AAED,QACE,2CAACC,oDAAkB;EAAS,OAAO;YACjC,2CAACC,iDAAe;GAAS,OAAO;GAC7B;IACuB;GACC;;;;;;;;;;;;;;;;;;;;;;AC7LjC,SAAgB,cAEd,SAAkC,MAAqC;CACvE,MAAM,EAAE,MAAM,aAAa,YAAY,QAAQ,SAAS,YAAY;AAEpE,yDACE;EACE;EACA;EACA;EACA;EACA;EAIA;EACD,EACD,KACD"}
@@ -1,149 +0,0 @@
1
- import React, { useEffect, useMemo, useRef, useState } from "react";
2
- import { CopilotKitContext, LicenseContext } from "@copilotkit/react-core/v2/context";
3
- import { CopilotKitCoreReact, useFrontendTool } from "@copilotkit/react-core/v2/headless";
4
- import { createLicenseContextValue } from "@copilotkit/shared";
5
- import { jsx } from "react/jsx-runtime";
6
-
7
- //#region src/CopilotKitProvider.tsx
8
- /**
9
- * CopilotKit provider for React Native.
10
- *
11
- * A lightweight alternative to the web CopilotKitProvider that avoids
12
- * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).
13
- *
14
- * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,
15
- * so a separate `import "@copilotkit/react-native/polyfills"` is no longer
16
- * required (though it remains available for advanced use).
17
- *
18
- * Usage:
19
- * ```tsx
20
- * import { CopilotKitProvider } from "@copilotkit/react-native";
21
- *
22
- * function App() {
23
- * return (
24
- * <CopilotKitProvider runtimeUrl="https://your-runtime/api/copilotkit">
25
- * <ChatScreen />
26
- * </CopilotKitProvider>
27
- * );
28
- * }
29
- * ```
30
- */
31
- const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp, credentials, useSingleEndpoint, properties, onError, debug, defaultThrottleMs }) => {
32
- const resolvedHeaders = typeof headersProp === "function" ? headersProp() : headersProp;
33
- const stableHeaders = useMemo(() => resolvedHeaders ?? {}, [JSON.stringify(resolvedHeaders)]);
34
- const stableProperties = useMemo(() => properties ?? {}, [JSON.stringify(properties)]);
35
- const copilotkitRef = useRef(null);
36
- if (copilotkitRef.current === null) {
37
- const instance = new CopilotKitCoreReact({
38
- runtimeUrl,
39
- runtimeTransport: useSingleEndpoint === true ? "single" : useSingleEndpoint === false ? "rest" : "auto",
40
- headers: stableHeaders,
41
- credentials,
42
- properties: stableProperties,
43
- debug
44
- });
45
- if (defaultThrottleMs !== void 0) instance.setDefaultThrottleMs(defaultThrottleMs);
46
- copilotkitRef.current = instance;
47
- }
48
- const copilotkit = copilotkitRef.current;
49
- useEffect(() => {
50
- copilotkit.setRuntimeUrl(runtimeUrl);
51
- copilotkit.setRuntimeTransport(useSingleEndpoint === true ? "single" : useSingleEndpoint === false ? "rest" : "auto");
52
- copilotkit.setHeaders(stableHeaders);
53
- copilotkit.setCredentials(credentials);
54
- copilotkit.setProperties(stableProperties);
55
- copilotkit.setDebug(debug);
56
- }, [
57
- runtimeUrl,
58
- useSingleEndpoint,
59
- stableHeaders,
60
- credentials,
61
- stableProperties,
62
- debug,
63
- copilotkit
64
- ]);
65
- useEffect(() => {
66
- copilotkit.setDefaultThrottleMs(defaultThrottleMs);
67
- }, [copilotkit, defaultThrottleMs]);
68
- const [executingToolCallIds, setExecutingToolCallIds] = useState(() => /* @__PURE__ */ new Set());
69
- const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState(void 0);
70
- const onErrorRef = useRef(onError);
71
- useEffect(() => {
72
- onErrorRef.current = onError;
73
- }, [onError]);
74
- useEffect(() => {
75
- const subscription = copilotkit.subscribe({
76
- onToolExecutionStart: ({ toolCallId }) => {
77
- setExecutingToolCallIds((prev) => {
78
- if (prev.has(toolCallId)) return prev;
79
- const next = new Set(prev);
80
- next.add(toolCallId);
81
- return next;
82
- });
83
- },
84
- onToolExecutionEnd: ({ toolCallId }) => {
85
- setExecutingToolCallIds((prev) => {
86
- if (!prev.has(toolCallId)) return prev;
87
- const next = new Set(prev);
88
- next.delete(toolCallId);
89
- return next;
90
- });
91
- },
92
- onError: (event) => {
93
- if (onErrorRef.current) onErrorRef.current(event);
94
- else console.error(`[CopilotKit] Error (${event.code}):`, event.error, event.context ?? {});
95
- },
96
- onRuntimeConnectionStatusChanged: () => {
97
- setRuntimeLicenseStatus(copilotkit.licenseStatus);
98
- }
99
- });
100
- return () => subscription.unsubscribe();
101
- }, [copilotkit]);
102
- const contextValue = useMemo(() => ({
103
- copilotkit,
104
- executingToolCallIds
105
- }), [copilotkit, executingToolCallIds]);
106
- const licenseContextValue = useMemo(() => createLicenseContextValue(runtimeLicenseStatus), [runtimeLicenseStatus]);
107
- return /* @__PURE__ */ jsx(CopilotKitContext.Provider, {
108
- value: contextValue,
109
- children: /* @__PURE__ */ jsx(LicenseContext.Provider, {
110
- value: licenseContextValue,
111
- children
112
- })
113
- });
114
- };
115
-
116
- //#endregion
117
- //#region src/hooks/useRenderTool.ts
118
- /**
119
- * Registers a frontend tool AND its renderer.
120
- *
121
- * Registration goes through react-core's `useFrontendTool`, which writes the
122
- * renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry
123
- * that RN's provider already instantiates. There is deliberately NO React
124
- * Native-local registry: this package previously kept its own Map, which meant
125
- * `useComponent` (registering into core's) rendered nowhere on RN, and renderers
126
- * were dropped from chat history on unmount.
127
- */
128
- /**
129
- * @param deps Optional dependency array. The `render` function is captured at
130
- * registration and only refreshed when `deps` change — it does NOT re-read the
131
- * latest closure on every render. If your `render` closes over component state
132
- * or props that change over time, you MUST pass those values in `deps`, or the
133
- * chat will keep painting with the stale closure.
134
- */
135
- function useRenderTool(options, deps) {
136
- const { name, description, parameters, render, handler, agentId } = options;
137
- useFrontendTool({
138
- name,
139
- description,
140
- parameters,
141
- handler,
142
- agentId,
143
- render
144
- }, deps);
145
- }
146
-
147
- //#endregion
148
- export { CopilotKitProvider as n, useRenderTool as t };
149
- //# sourceMappingURL=useRenderTool-l7M-I8rT.mjs.map