@copilotkit/react-native 1.67.1 → 1.68.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 (56) hide show
  1. package/dist/chunk-C0xms8kb.cjs +34 -0
  2. package/dist/components/index.cjs +146 -33
  3. package/dist/components/index.cjs.map +1 -1
  4. package/dist/components/index.mjs +144 -32
  5. package/dist/components/index.mjs.map +1 -1
  6. package/dist/headless.cjs +40 -4
  7. package/dist/headless.d.cts +3 -3
  8. package/dist/headless.d.mts +3 -3
  9. package/dist/headless.mjs +5 -4
  10. package/dist/index.cjs +43 -7
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +3 -3
  13. package/dist/index.d.mts +4 -4
  14. package/dist/index.mjs +3 -4
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/polyfills/encoding.cjs +1 -1
  17. package/dist/polyfills/streams.cjs +1 -1
  18. package/dist/useRenderTool-BBxnOOeJ.d.mts +161 -0
  19. package/dist/useRenderTool-BWo11PCL.d.cts +161 -0
  20. package/dist/{useRenderTool-DLavcsVB.cjs → useRenderTool-CKEPq7MQ.cjs} +20 -34
  21. package/dist/useRenderTool-CKEPq7MQ.cjs.map +1 -0
  22. package/dist/{useRenderTool-DUqpS97B.mjs → useRenderTool-l7M-I8rT.mjs} +18 -33
  23. package/dist/useRenderTool-l7M-I8rT.mjs.map +1 -0
  24. package/package.json +9 -6
  25. package/scripts/__tests__/fixtures/stray-react-dom-headless.js +16 -0
  26. package/scripts/__tests__/fixtures/tiny-headless.js +10 -0
  27. package/scripts/__tests__/fixtures/warning-headless.js +13 -0
  28. package/scripts/__tests__/measure-headless.test.mjs +275 -0
  29. package/scripts/measure-headless.mjs +310 -0
  30. package/src/CopilotKitProvider.tsx +1 -2
  31. package/src/__mocks__/test-copilotkit.tsx +116 -0
  32. package/src/__mocks__/tool-fixtures.ts +50 -0
  33. package/src/__tests__/headless-entry-surface.test.ts +464 -46
  34. package/src/__tests__/headless-integration.test.tsx +12 -1
  35. package/src/__tests__/headless-value-exports.test.ts +369 -0
  36. package/src/components/CopilotChat.tsx +218 -32
  37. package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -126
  38. package/src/components/__tests__/CopilotChat.test.tsx +5 -49
  39. package/src/components/__tests__/CopilotChatToolCalls.test.tsx +468 -0
  40. package/src/headless.ts +36 -14
  41. package/src/hooks/__tests__/render-tool-call.integration.test.tsx +181 -0
  42. package/src/hooks/__tests__/useRenderTool.test.tsx +232 -267
  43. package/src/hooks/index.ts +1 -7
  44. package/src/hooks/render-tool-types.ts +55 -0
  45. package/src/hooks/useRenderTool.ts +29 -57
  46. package/src/index.ts +13 -5
  47. package/dist/RenderToolContext-CBNKcJqz.cjs +0 -126
  48. package/dist/RenderToolContext-CBNKcJqz.cjs.map +0 -1
  49. package/dist/RenderToolContext-D8M-JhD1.mjs +0 -75
  50. package/dist/RenderToolContext-D8M-JhD1.mjs.map +0 -1
  51. package/dist/useRenderTool-9YDIfZ0D.d.mts +0 -164
  52. package/dist/useRenderTool-BugVTDoM.d.cts +0 -164
  53. package/dist/useRenderTool-DLavcsVB.cjs.map +0 -1
  54. package/dist/useRenderTool-DUqpS97B.mjs.map +0 -1
  55. package/src/hooks/RenderToolContext.tsx +0 -150
  56. package/src/hooks/__tests__/RenderToolContext.test.tsx +0 -264
@@ -1,8 +1,6 @@
1
- import { useEffect, useRef } from "react";
2
1
  import { useFrontendTool } from "@copilotkit/react-core/v2/headless";
3
2
  import type { StandardSchemaV1 } from "@copilotkit/shared";
4
- import type { RenderToolFunction } from "./RenderToolContext";
5
- import { useRenderToolContext } from "./RenderToolContext";
3
+ import type { RenderToolFunction } from "./render-tool-types";
6
4
 
7
5
  /**
8
6
  * Options for the useRenderTool hook.
@@ -12,63 +10,45 @@ export interface UseRenderToolOptions<T extends Record<string, unknown>> {
12
10
  name: string;
13
11
  /** Human-readable description shown to the agent. */
14
12
  description: string;
15
- /**
16
- * Schema describing the tool's parameters.
17
- * Accepts any StandardSchemaV1-compatible schema (Zod, Valibot, ArkType, etc.).
18
- */
13
+ /** Schema describing the tool's parameters (any StandardSchemaV1 library). */
19
14
  parameters: StandardSchemaV1<unknown, T>;
20
15
  /**
21
- * Render function that returns a React Native element for the tool call.
22
- * Called by CopilotChat when it encounters a tool call message for this tool.
16
+ * Render function returning a React Native element for the tool call.
17
+ * Rendered by `CopilotChat` inline, and by `useRenderToolCall()` anywhere else.
23
18
  *
24
- * Returns ReactElement | null (not ReactNode) because React Native's
25
- * FlatList cannot render strings or portals.
19
+ * Arguments STREAM: on `status: "inProgress"` the props are partial, because
20
+ * the model has not finished writing the JSON. Write renderers that tolerate
21
+ * missing fields — that is what makes UI build progressively.
26
22
  */
27
23
  render: RenderToolFunction<T>;
28
- /**
29
- * Optional handler executed when the tool is called.
30
- * If omitted, the tool is render-only (the render function shows UI
31
- * but the tool returns no result to the agent).
32
- */
24
+ /** Optional handler. Omit for render-only (display IS the effect). */
33
25
  handler?: (args: T) => Promise<unknown>;
34
- /**
35
- * Optional agent ID to scope this tool to a specific agent.
36
- */
26
+ /** Scope this tool to a single agent. */
37
27
  agentId?: string;
38
28
  }
39
29
 
40
30
  /**
41
- * Hook that registers a frontend tool AND a render function for it.
42
- *
43
- * This bridges `useFrontendTool` (which handles tool registration and
44
- * handler execution) with a render registry so that CopilotChat can
45
- * render React Native elements inline when it encounters tool call messages.
31
+ * Registers a frontend tool AND its renderer.
46
32
  *
47
- * @example
48
- * ```tsx
49
- * useRenderTool({
50
- * name: "showWeather",
51
- * description: "Display weather information",
52
- * parameters: z.object({ city: z.string(), temp: z.number() }),
53
- * render: ({ args, status }) => (
54
- * <View>
55
- * <Text>{args.city}: {args.temp}</Text>
56
- * {status === "executing" && <ActivityIndicator />}
57
- * </View>
58
- * ),
59
- * handler: async ({ city }) => {
60
- * return { forecast: "sunny" };
61
- * },
62
- * });
63
- * ```
33
+ * Registration goes through react-core's `useFrontendTool`, which writes the
34
+ * renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry
35
+ * that RN's provider already instantiates. There is deliberately NO React
36
+ * Native-local registry: this package previously kept its own Map, which meant
37
+ * `useComponent` (registering into core's) rendered nowhere on RN, and renderers
38
+ * were dropped from chat history on unmount.
39
+ */
40
+ /**
41
+ * @param deps Optional dependency array. The `render` function is captured at
42
+ * registration and only refreshed when `deps` change — it does NOT re-read the
43
+ * latest closure on every render. If your `render` closes over component state
44
+ * or props that change over time, you MUST pass those values in `deps`, or the
45
+ * chat will keep painting with the stale closure.
64
46
  */
65
47
  export function useRenderTool<
66
48
  T extends Record<string, unknown> = Record<string, unknown>,
67
49
  >(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void {
68
50
  const { name, description, parameters, render, handler, agentId } = options;
69
- const { register } = useRenderToolContext();
70
51
 
71
- // Register the tool with the core system via useFrontendTool
72
52
  useFrontendTool<T>(
73
53
  {
74
54
  name,
@@ -76,21 +56,13 @@ export function useRenderTool<
76
56
  parameters,
77
57
  handler,
78
58
  agentId,
59
+ // No cast needed: ReactFrontendTool.render is ReactToolCallRenderer<T>["render"],
60
+ // and RenderToolFunction is derived from exactly that props type, returning
61
+ // ReactElement | null (assignable to ComponentType's ReactNode).
62
+ render,
79
63
  },
80
64
  deps,
81
65
  );
82
-
83
- // Use a ref so the effect cleanup always has the latest render function
84
- const renderRef = useRef(render);
85
- renderRef.current = render;
86
-
87
- // Register the render function in the RenderToolContext
88
- useEffect(() => {
89
- // Wrap in a stable function that delegates to the ref
90
- const stableRender: RenderToolFunction<T> = (props) =>
91
- renderRef.current(props);
92
-
93
- const unregister = register(name, stableRender as RenderToolFunction);
94
- return unregister;
95
- }, [name, register]);
96
66
  }
67
+
68
+ export type { RenderToolProps, RenderToolFunction } from "./render-tool-types";
package/src/index.ts CHANGED
@@ -49,10 +49,18 @@ export { CopilotPopup } from "./CopilotPopup";
49
49
  export type { CopilotPopupProps, CopilotPopupHandle } from "./CopilotPopup";
50
50
 
51
51
  // The provider, platform-agnostic hooks (useAgent / useFrontendTool / ...),
52
- // core + AG-UI types, and the render-tool registry are re-exported from
53
- // "./headless" above (`export * from "./headless"`).
52
+ // core + AG-UI types, and the render-tool hooks are re-exported from "./headless"
53
+ // above (`export * from "./headless"`).
54
54
  //
55
- // Deliberately NOT re-exported (web-specific, from @copilotkit/react-core/v2):
56
- // useRenderToolCall — depends on DOM elements via DefaultToolCallRenderer
57
- // useRenderCustomMessages / useRenderActivityMessage — web chat UI pipeline
55
+ // Deliberately NOT re-exported — these genuinely render host DOM or link the
56
+ // web chat-message stack, from @copilotkit/react-core/v2 (the fat entry):
58
57
  // useDefaultRenderTool — DefaultToolCallRenderer uses <div>, <svg>, etc.
58
+ // useRenderCustomMessages / useRenderActivityMessage — link @copilotkit/a2ui-renderer
59
+ //
60
+ // NOTE: useRenderToolCall is NOT in this list. It was excluded until 2026-07-23
61
+ // on the stated grounds that it "depends on DOM via DefaultToolCallRenderer" —
62
+ // which was never true of the hook itself; it was only reachable through the fat
63
+ // /v2 entry, whose weight is the real hazard (#4893). PR #5883 moved it into
64
+ // /v2/headless, and we consume it from there. Never import from bare
65
+ // "@copilotkit/react-core/v2" in this package — the import-graph guard in
66
+ // src/__tests__/headless-entry-surface.test.ts fails the build if you do.
@@ -1,126 +0,0 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) {
13
- __defProp(to, key, {
14
- get: ((k) => from[k]).bind(null, key),
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- }
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
-
27
- //#endregion
28
- let react = require("react");
29
- react = __toESM(react);
30
- let react_jsx_runtime = require("react/jsx-runtime");
31
-
32
- //#region src/hooks/RenderToolContext.tsx
33
- function createRegistryStore() {
34
- return {
35
- registry: /* @__PURE__ */ new Map(),
36
- version: 0,
37
- listeners: /* @__PURE__ */ new Set()
38
- };
39
- }
40
- function emitChange(store) {
41
- store.version++;
42
- store.registry = new Map(store.registry);
43
- for (const listener of store.listeners) listener();
44
- }
45
- const RenderToolCtx = (0, react.createContext)(null);
46
- /**
47
- * Provider that maintains the render tool registry.
48
- * Should be nested inside CopilotKitProvider.
49
- */
50
- function RenderToolProvider({ children }) {
51
- const storeRef = (0, react.useRef)(createRegistryStore());
52
- const register = (0, react.useCallback)((name, render) => {
53
- const store = storeRef.current;
54
- store.registry.set(name, render);
55
- emitChange(store);
56
- return () => {
57
- if (store.registry.get(name) === render) {
58
- store.registry.delete(name);
59
- emitChange(store);
60
- }
61
- };
62
- }, []);
63
- const value = (0, react.useMemo)(() => ({
64
- store: storeRef.current,
65
- register
66
- }), [register]);
67
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderToolCtx.Provider, {
68
- value,
69
- children
70
- });
71
- }
72
- /**
73
- * Returns the current render tool registry (a Map of tool name to render function).
74
- * Re-renders when the registry changes.
75
- *
76
- * @throws if called outside of RenderToolProvider
77
- */
78
- function useRenderToolRegistry() {
79
- const ctx = (0, react.useContext)(RenderToolCtx);
80
- if (!ctx) throw new Error("useRenderToolRegistry must be used within a RenderToolProvider");
81
- const { store } = ctx;
82
- return (0, react.useSyncExternalStore)((onStoreChange) => {
83
- store.listeners.add(onStoreChange);
84
- return () => {
85
- store.listeners.delete(onStoreChange);
86
- };
87
- }, () => store.registry, () => store.registry);
88
- }
89
- /**
90
- * Internal hook used by useRenderTool to register a render function.
91
- * Not exported from the package — consumers use useRenderTool instead.
92
- *
93
- * @throws if called outside of RenderToolProvider
94
- */
95
- function useRenderToolContext() {
96
- const ctx = (0, react.useContext)(RenderToolCtx);
97
- if (!ctx) throw new Error("useRenderTool must be used within a RenderToolProvider (inside CopilotKitProvider)");
98
- return ctx;
99
- }
100
-
101
- //#endregion
102
- Object.defineProperty(exports, 'RenderToolProvider', {
103
- enumerable: true,
104
- get: function () {
105
- return RenderToolProvider;
106
- }
107
- });
108
- Object.defineProperty(exports, '__toESM', {
109
- enumerable: true,
110
- get: function () {
111
- return __toESM;
112
- }
113
- });
114
- Object.defineProperty(exports, 'useRenderToolContext', {
115
- enumerable: true,
116
- get: function () {
117
- return useRenderToolContext;
118
- }
119
- });
120
- Object.defineProperty(exports, 'useRenderToolRegistry', {
121
- enumerable: true,
122
- get: function () {
123
- return useRenderToolRegistry;
124
- }
125
- });
126
- //# sourceMappingURL=RenderToolContext-CBNKcJqz.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"RenderToolContext-CBNKcJqz.cjs","names":[],"sources":["../src/hooks/RenderToolContext.tsx"],"sourcesContent":["import React, {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\n\n/**\n * Props passed to a render tool function.\n */\nexport interface RenderToolProps<T = Record<string, unknown>> {\n args: T;\n status: \"executing\" | \"complete\";\n result?: string;\n}\n\n/**\n * A render function that returns a React Native element for a tool call.\n * Returns `ReactElement | null` (not ReactNode) because React Native's\n * FlatList cannot render strings or portals.\n */\nexport type RenderToolFunction<T = Record<string, unknown>> = (\n props: RenderToolProps<T>,\n) => React.ReactElement | null;\n\n/**\n * The registry maps tool names to their render functions.\n */\nexport type RenderToolRegistry = Map<string, RenderToolFunction>;\n\n/**\n * Internal store that notifies subscribers when the registry changes.\n * This avoids unnecessary re-renders of the entire tree when a single\n * tool's render function is registered or removed.\n */\ninterface RegistryStore {\n registry: RenderToolRegistry;\n version: number;\n listeners: Set<() => void>;\n}\n\nfunction createRegistryStore(): RegistryStore {\n return {\n registry: new Map(),\n version: 0,\n listeners: new Set(),\n };\n}\n\nfunction emitChange(store: RegistryStore) {\n store.version++;\n // Create a new Map so useSyncExternalStore detects the reference change\n store.registry = new Map(store.registry);\n for (const listener of store.listeners) {\n listener();\n }\n}\n\ninterface RenderToolContextValue {\n store: RegistryStore;\n register: (name: string, render: RenderToolFunction) => () => void;\n}\n\nconst RenderToolCtx = createContext<RenderToolContextValue | null>(null);\n\n/**\n * Provider that maintains the render tool registry.\n * Should be nested inside CopilotKitProvider.\n */\nexport function RenderToolProvider({\n children,\n}: {\n children: React.ReactNode;\n}) {\n const storeRef = useRef<RegistryStore>(createRegistryStore());\n\n const register = useCallback(\n (name: string, render: RenderToolFunction): (() => void) => {\n const store = storeRef.current;\n store.registry.set(name, render);\n emitChange(store);\n\n // Return unregister function\n return () => {\n // Only delete if the current render function is the one we registered\n if (store.registry.get(name) === render) {\n store.registry.delete(name);\n emitChange(store);\n }\n };\n },\n [],\n );\n\n const value = useMemo<RenderToolContextValue>(\n () => ({ store: storeRef.current, register }),\n [register],\n );\n\n return (\n <RenderToolCtx.Provider value={value}>{children}</RenderToolCtx.Provider>\n );\n}\n\n/**\n * Returns the current render tool registry (a Map of tool name to render function).\n * Re-renders when the registry changes.\n *\n * @throws if called outside of RenderToolProvider\n */\nexport function useRenderToolRegistry(): RenderToolRegistry {\n const ctx = useContext(RenderToolCtx);\n if (!ctx) {\n throw new Error(\n \"useRenderToolRegistry must be used within a RenderToolProvider\",\n );\n }\n\n const { store } = ctx;\n\n // Subscribe to registry changes via useSyncExternalStore for tear-safe reads\n return useSyncExternalStore(\n (onStoreChange) => {\n store.listeners.add(onStoreChange);\n return () => {\n store.listeners.delete(onStoreChange);\n };\n },\n () => store.registry,\n () => store.registry,\n );\n}\n\n/**\n * Internal hook used by useRenderTool to register a render function.\n * Not exported from the package — consumers use useRenderTool instead.\n *\n * @throws if called outside of RenderToolProvider\n */\nexport function useRenderToolContext() {\n const ctx = useContext(RenderToolCtx);\n if (!ctx) {\n throw new Error(\n \"useRenderTool must be used within a RenderToolProvider (inside CopilotKitProvider)\",\n );\n }\n return ctx;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAS,sBAAqC;AAC5C,QAAO;EACL,0BAAU,IAAI,KAAK;EACnB,SAAS;EACT,2BAAW,IAAI,KAAK;EACrB;;AAGH,SAAS,WAAW,OAAsB;AACxC,OAAM;AAEN,OAAM,WAAW,IAAI,IAAI,MAAM,SAAS;AACxC,MAAK,MAAM,YAAY,MAAM,UAC3B,WAAU;;AASd,MAAM,yCAA6D,KAAK;;;;;AAMxE,SAAgB,mBAAmB,EACjC,YAGC;CACD,MAAM,6BAAiC,qBAAqB,CAAC;CAE7D,MAAM,mCACH,MAAc,WAA6C;EAC1D,MAAM,QAAQ,SAAS;AACvB,QAAM,SAAS,IAAI,MAAM,OAAO;AAChC,aAAW,MAAM;AAGjB,eAAa;AAEX,OAAI,MAAM,SAAS,IAAI,KAAK,KAAK,QAAQ;AACvC,UAAM,SAAS,OAAO,KAAK;AAC3B,eAAW,MAAM;;;IAIvB,EAAE,CACH;CAED,MAAM,kCACG;EAAE,OAAO,SAAS;EAAS;EAAU,GAC5C,CAAC,SAAS,CACX;AAED,QACE,2CAAC,cAAc;EAAgB;EAAQ;GAAkC;;;;;;;;AAU7E,SAAgB,wBAA4C;CAC1D,MAAM,4BAAiB,cAAc;AACrC,KAAI,CAAC,IACH,OAAM,IAAI,MACR,iEACD;CAGH,MAAM,EAAE,UAAU;AAGlB,yCACG,kBAAkB;AACjB,QAAM,UAAU,IAAI,cAAc;AAClC,eAAa;AACX,SAAM,UAAU,OAAO,cAAc;;UAGnC,MAAM,gBACN,MAAM,SACb;;;;;;;;AASH,SAAgB,uBAAuB;CACrC,MAAM,4BAAiB,cAAc;AACrC,KAAI,CAAC,IACH,OAAM,IAAI,MACR,qFACD;AAEH,QAAO"}
@@ -1,75 +0,0 @@
1
- import React, { createContext, useCallback, useContext, useMemo, useRef, useSyncExternalStore } from "react";
2
- import { jsx } from "react/jsx-runtime";
3
-
4
- //#region src/hooks/RenderToolContext.tsx
5
- function createRegistryStore() {
6
- return {
7
- registry: /* @__PURE__ */ new Map(),
8
- version: 0,
9
- listeners: /* @__PURE__ */ new Set()
10
- };
11
- }
12
- function emitChange(store) {
13
- store.version++;
14
- store.registry = new Map(store.registry);
15
- for (const listener of store.listeners) listener();
16
- }
17
- const RenderToolCtx = createContext(null);
18
- /**
19
- * Provider that maintains the render tool registry.
20
- * Should be nested inside CopilotKitProvider.
21
- */
22
- function RenderToolProvider({ children }) {
23
- const storeRef = useRef(createRegistryStore());
24
- const register = useCallback((name, render) => {
25
- const store = storeRef.current;
26
- store.registry.set(name, render);
27
- emitChange(store);
28
- return () => {
29
- if (store.registry.get(name) === render) {
30
- store.registry.delete(name);
31
- emitChange(store);
32
- }
33
- };
34
- }, []);
35
- const value = useMemo(() => ({
36
- store: storeRef.current,
37
- register
38
- }), [register]);
39
- return /* @__PURE__ */ jsx(RenderToolCtx.Provider, {
40
- value,
41
- children
42
- });
43
- }
44
- /**
45
- * Returns the current render tool registry (a Map of tool name to render function).
46
- * Re-renders when the registry changes.
47
- *
48
- * @throws if called outside of RenderToolProvider
49
- */
50
- function useRenderToolRegistry() {
51
- const ctx = useContext(RenderToolCtx);
52
- if (!ctx) throw new Error("useRenderToolRegistry must be used within a RenderToolProvider");
53
- const { store } = ctx;
54
- return useSyncExternalStore((onStoreChange) => {
55
- store.listeners.add(onStoreChange);
56
- return () => {
57
- store.listeners.delete(onStoreChange);
58
- };
59
- }, () => store.registry, () => store.registry);
60
- }
61
- /**
62
- * Internal hook used by useRenderTool to register a render function.
63
- * Not exported from the package — consumers use useRenderTool instead.
64
- *
65
- * @throws if called outside of RenderToolProvider
66
- */
67
- function useRenderToolContext() {
68
- const ctx = useContext(RenderToolCtx);
69
- if (!ctx) throw new Error("useRenderTool must be used within a RenderToolProvider (inside CopilotKitProvider)");
70
- return ctx;
71
- }
72
-
73
- //#endregion
74
- export { useRenderToolContext as n, useRenderToolRegistry as r, RenderToolProvider as t };
75
- //# sourceMappingURL=RenderToolContext-D8M-JhD1.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"RenderToolContext-D8M-JhD1.mjs","names":[],"sources":["../src/hooks/RenderToolContext.tsx"],"sourcesContent":["import React, {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\n\n/**\n * Props passed to a render tool function.\n */\nexport interface RenderToolProps<T = Record<string, unknown>> {\n args: T;\n status: \"executing\" | \"complete\";\n result?: string;\n}\n\n/**\n * A render function that returns a React Native element for a tool call.\n * Returns `ReactElement | null` (not ReactNode) because React Native's\n * FlatList cannot render strings or portals.\n */\nexport type RenderToolFunction<T = Record<string, unknown>> = (\n props: RenderToolProps<T>,\n) => React.ReactElement | null;\n\n/**\n * The registry maps tool names to their render functions.\n */\nexport type RenderToolRegistry = Map<string, RenderToolFunction>;\n\n/**\n * Internal store that notifies subscribers when the registry changes.\n * This avoids unnecessary re-renders of the entire tree when a single\n * tool's render function is registered or removed.\n */\ninterface RegistryStore {\n registry: RenderToolRegistry;\n version: number;\n listeners: Set<() => void>;\n}\n\nfunction createRegistryStore(): RegistryStore {\n return {\n registry: new Map(),\n version: 0,\n listeners: new Set(),\n };\n}\n\nfunction emitChange(store: RegistryStore) {\n store.version++;\n // Create a new Map so useSyncExternalStore detects the reference change\n store.registry = new Map(store.registry);\n for (const listener of store.listeners) {\n listener();\n }\n}\n\ninterface RenderToolContextValue {\n store: RegistryStore;\n register: (name: string, render: RenderToolFunction) => () => void;\n}\n\nconst RenderToolCtx = createContext<RenderToolContextValue | null>(null);\n\n/**\n * Provider that maintains the render tool registry.\n * Should be nested inside CopilotKitProvider.\n */\nexport function RenderToolProvider({\n children,\n}: {\n children: React.ReactNode;\n}) {\n const storeRef = useRef<RegistryStore>(createRegistryStore());\n\n const register = useCallback(\n (name: string, render: RenderToolFunction): (() => void) => {\n const store = storeRef.current;\n store.registry.set(name, render);\n emitChange(store);\n\n // Return unregister function\n return () => {\n // Only delete if the current render function is the one we registered\n if (store.registry.get(name) === render) {\n store.registry.delete(name);\n emitChange(store);\n }\n };\n },\n [],\n );\n\n const value = useMemo<RenderToolContextValue>(\n () => ({ store: storeRef.current, register }),\n [register],\n );\n\n return (\n <RenderToolCtx.Provider value={value}>{children}</RenderToolCtx.Provider>\n );\n}\n\n/**\n * Returns the current render tool registry (a Map of tool name to render function).\n * Re-renders when the registry changes.\n *\n * @throws if called outside of RenderToolProvider\n */\nexport function useRenderToolRegistry(): RenderToolRegistry {\n const ctx = useContext(RenderToolCtx);\n if (!ctx) {\n throw new Error(\n \"useRenderToolRegistry must be used within a RenderToolProvider\",\n );\n }\n\n const { store } = ctx;\n\n // Subscribe to registry changes via useSyncExternalStore for tear-safe reads\n return useSyncExternalStore(\n (onStoreChange) => {\n store.listeners.add(onStoreChange);\n return () => {\n store.listeners.delete(onStoreChange);\n };\n },\n () => store.registry,\n () => store.registry,\n );\n}\n\n/**\n * Internal hook used by useRenderTool to register a render function.\n * Not exported from the package — consumers use useRenderTool instead.\n *\n * @throws if called outside of RenderToolProvider\n */\nexport function useRenderToolContext() {\n const ctx = useContext(RenderToolCtx);\n if (!ctx) {\n throw new Error(\n \"useRenderTool must be used within a RenderToolProvider (inside CopilotKitProvider)\",\n );\n }\n return ctx;\n}\n"],"mappings":";;;;AA2CA,SAAS,sBAAqC;AAC5C,QAAO;EACL,0BAAU,IAAI,KAAK;EACnB,SAAS;EACT,2BAAW,IAAI,KAAK;EACrB;;AAGH,SAAS,WAAW,OAAsB;AACxC,OAAM;AAEN,OAAM,WAAW,IAAI,IAAI,MAAM,SAAS;AACxC,MAAK,MAAM,YAAY,MAAM,UAC3B,WAAU;;AASd,MAAM,gBAAgB,cAA6C,KAAK;;;;;AAMxE,SAAgB,mBAAmB,EACjC,YAGC;CACD,MAAM,WAAW,OAAsB,qBAAqB,CAAC;CAE7D,MAAM,WAAW,aACd,MAAc,WAA6C;EAC1D,MAAM,QAAQ,SAAS;AACvB,QAAM,SAAS,IAAI,MAAM,OAAO;AAChC,aAAW,MAAM;AAGjB,eAAa;AAEX,OAAI,MAAM,SAAS,IAAI,KAAK,KAAK,QAAQ;AACvC,UAAM,SAAS,OAAO,KAAK;AAC3B,eAAW,MAAM;;;IAIvB,EAAE,CACH;CAED,MAAM,QAAQ,eACL;EAAE,OAAO,SAAS;EAAS;EAAU,GAC5C,CAAC,SAAS,CACX;AAED,QACE,oBAAC,cAAc;EAAgB;EAAQ;GAAkC;;;;;;;;AAU7E,SAAgB,wBAA4C;CAC1D,MAAM,MAAM,WAAW,cAAc;AACrC,KAAI,CAAC,IACH,OAAM,IAAI,MACR,iEACD;CAGH,MAAM,EAAE,UAAU;AAGlB,QAAO,sBACJ,kBAAkB;AACjB,QAAM,UAAU,IAAI,cAAc;AAClC,eAAa;AACX,SAAM,UAAU,OAAO,cAAc;;UAGnC,MAAM,gBACN,MAAM,SACb;;;;;;;;AASH,SAAgB,uBAAuB;CACrC,MAAM,MAAM,WAAW,cAAc;AACrC,KAAI,CAAC,IACH,OAAM,IAAI,MACR,qFACD;AAEH,QAAO"}
@@ -1,164 +0,0 @@
1
- import React, { ReactNode } from "react";
2
- import { DebugConfig, StandardSchemaV1 } from "@copilotkit/shared";
3
- import * as react_jsx_runtime0 from "react/jsx-runtime";
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/RenderToolContext.d.ts
68
- /**
69
- * Props passed to a render tool function.
70
- */
71
- interface RenderToolProps<T = Record<string, unknown>> {
72
- args: T;
73
- status: "executing" | "complete";
74
- result?: string;
75
- }
76
- /**
77
- * A render function that returns a React Native element for a tool call.
78
- * Returns `ReactElement | null` (not ReactNode) because React Native's
79
- * FlatList cannot render strings or portals.
80
- */
81
- type RenderToolFunction<T = Record<string, unknown>> = (props: RenderToolProps<T>) => React.ReactElement | null;
82
- /**
83
- * The registry maps tool names to their render functions.
84
- */
85
- type RenderToolRegistry = Map<string, RenderToolFunction>;
86
- /**
87
- * Provider that maintains the render tool registry.
88
- * Should be nested inside CopilotKitProvider.
89
- */
90
- declare function RenderToolProvider({
91
- children
92
- }: {
93
- children: React.ReactNode;
94
- }): react_jsx_runtime0.JSX.Element;
95
- /**
96
- * Returns the current render tool registry (a Map of tool name to render function).
97
- * Re-renders when the registry changes.
98
- *
99
- * @throws if called outside of RenderToolProvider
100
- */
101
- declare function useRenderToolRegistry(): RenderToolRegistry;
102
- //#endregion
103
- //#region src/hooks/useRenderTool.d.ts
104
- /**
105
- * Options for the useRenderTool hook.
106
- */
107
- interface UseRenderToolOptions<T extends Record<string, unknown>> {
108
- /** Unique name for the tool. Must match what the agent calls. */
109
- name: string;
110
- /** Human-readable description shown to the agent. */
111
- description: string;
112
- /**
113
- * Schema describing the tool's parameters.
114
- * Accepts any StandardSchemaV1-compatible schema (Zod, Valibot, ArkType, etc.).
115
- */
116
- parameters: StandardSchemaV1<unknown, T>;
117
- /**
118
- * Render function that returns a React Native element for the tool call.
119
- * Called by CopilotChat when it encounters a tool call message for this tool.
120
- *
121
- * Returns ReactElement | null (not ReactNode) because React Native's
122
- * FlatList cannot render strings or portals.
123
- */
124
- render: RenderToolFunction<T>;
125
- /**
126
- * Optional handler executed when the tool is called.
127
- * If omitted, the tool is render-only (the render function shows UI
128
- * but the tool returns no result to the agent).
129
- */
130
- handler?: (args: T) => Promise<unknown>;
131
- /**
132
- * Optional agent ID to scope this tool to a specific agent.
133
- */
134
- agentId?: string;
135
- }
136
- /**
137
- * Hook that registers a frontend tool AND a render function for it.
138
- *
139
- * This bridges `useFrontendTool` (which handles tool registration and
140
- * handler execution) with a render registry so that CopilotChat can
141
- * render React Native elements inline when it encounters tool call messages.
142
- *
143
- * @example
144
- * ```tsx
145
- * useRenderTool({
146
- * name: "showWeather",
147
- * description: "Display weather information",
148
- * parameters: z.object({ city: z.string(), temp: z.number() }),
149
- * render: ({ args, status }) => (
150
- * <View>
151
- * <Text>{args.city}: {args.temp}</Text>
152
- * {status === "executing" && <ActivityIndicator />}
153
- * </View>
154
- * ),
155
- * handler: async ({ city }) => {
156
- * return { forecast: "sunny" };
157
- * },
158
- * });
159
- * ```
160
- */
161
- declare function useRenderTool<T extends Record<string, unknown> = Record<string, unknown>>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void;
162
- //#endregion
163
- export { useRenderToolRegistry as a, RenderToolProvider as i, useRenderTool as n, CopilotKitNativeProviderProps as o, RenderToolProps as r, CopilotKitProvider as s, UseRenderToolOptions as t };
164
- //# sourceMappingURL=useRenderTool-9YDIfZ0D.d.mts.map