@copilotkit/react-native 1.66.1-canary.rn-tool-render → 1.66.2-canary.1785866877

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.
@@ -1,8 +1,8 @@
1
- import { n as useRenderToolContext, r as useRenderToolRegistry, t as RenderToolProvider } from "./RenderToolContext-D8M-JhD1.mjs";
2
- import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
1
+ import { n as useRenderToolContext, t as RenderToolProvider } from "./RenderToolContext-D8M-JhD1.mjs";
2
+ import React, { useEffect, useMemo, useRef, useState } from "react";
3
3
  import { CopilotKitContext, LicenseContext } from "@copilotkit/react-core/v2/context";
4
- import { CopilotKitCoreReact, useCopilotKit as useCopilotKit$1, useFrontendTool } from "@copilotkit/react-core/v2/headless";
5
- import { createLicenseContextValue, partialJSONParse } from "@copilotkit/shared";
4
+ import { CopilotKitCoreReact, useFrontendTool } from "@copilotkit/react-core/v2/headless";
5
+ import { createLicenseContextValue } from "@copilotkit/shared";
6
6
  import { jsx } from "react/jsx-runtime";
7
7
 
8
8
  //#region src/CopilotKitProvider.tsx
@@ -160,90 +160,5 @@ function useRenderTool(options, deps) {
160
160
  }
161
161
 
162
162
  //#endregion
163
- //#region src/hooks/useComponent.tsx
164
- /**
165
- * Register a component the agent can choose to display — the controlled generative-UI primitive,
166
- * for React Native.
167
- *
168
- * `@copilotkit/react-core` has a `useComponent` of the same shape, but it registers into react-core's
169
- * own render registry, which this package's renderers do not read. On React Native that meant a
170
- * component registered with it rendered nowhere: not in `CopilotChat`, and not on a custom surface.
171
- * This version registers into THIS package's registry, so one registration renders in the chat and
172
- * anywhere you call `useRenderToolCall()`.
173
- *
174
- * Like react-core's, it is render-only: there is no handler, because displaying the component IS the
175
- * effect. Props are the tool arguments, spread directly, so a component can be used as-is.
176
- *
177
- * Arguments stream, so props may be INCOMPLETE on early renders (see `RenderToolProps.args`). Write
178
- * components that tolerate missing fields — that is what lets UI build as the agent writes it.
179
- *
180
- * @example
181
- * ```tsx
182
- * useComponent({
183
- * name: "showWeatherCard",
184
- * description: "Show the weather for a city.",
185
- * parameters: z.object({ city: z.string() }),
186
- * render: ({ city }) => <Text>{city}</Text>,
187
- * });
188
- * ```
189
- */
190
- function useComponent(config, deps) {
191
- const prefix = `Use this tool to display the "${config.name}" component to the user. This tool renders a visual UI component.`;
192
- const description = config.description ? `${prefix}\n\n${config.description}` : prefix;
193
- const Component = config.render;
194
- useRenderTool({
195
- name: config.name,
196
- description,
197
- parameters: config.parameters,
198
- render: ({ args }) => /* @__PURE__ */ jsx(Component, { ...args }),
199
- agentId: config.agentId
200
- }, deps);
201
- }
202
-
203
- //#endregion
204
- //#region src/hooks/useRenderToolCall.ts
205
- /**
206
- * Render a tool call using the render function registered for it, ANYWHERE in your app.
207
- *
208
- * `CopilotChat` renders tool calls inline in its own message list, which is the right default for a
209
- * chat. But plenty of React Native surfaces are not chats — an in-car stage, a kiosk, a dashboard —
210
- * and they still want the agent to drive the UI. Without this hook there was no public way to render
211
- * a registered component outside the chat, which also made `useComponent` unusable on those surfaces.
212
- *
213
- * Arguments are partial-JSON-parsed, so a component paints as the agent writes the call
214
- * (`status: "inProgress"`) and fills in as more arrives — the same progressive behaviour the web
215
- * renderer has. Renderers therefore need to tolerate incomplete `args`.
216
- *
217
- * @example
218
- * ```tsx
219
- * const renderToolCall = useRenderToolCall();
220
- *
221
- * // panels the agent has called this turn, laid out however you like
222
- * return <View>{toolCalls.map((tc) => renderToolCall({ toolCall: tc }))}</View>;
223
- * ```
224
- */
225
- function useRenderToolCall() {
226
- const toolRenderers = useRenderToolRegistry();
227
- const { executingToolCallIds } = useCopilotKit$1();
228
- return useCallback(({ toolCall, toolMessage }) => {
229
- const renderer = toolRenderers.get(toolCall.function.name);
230
- if (!renderer) return null;
231
- const raw = toolCall.function.arguments || "{}";
232
- const args = partialJSONParse(raw);
233
- let argsComplete = true;
234
- try {
235
- JSON.parse(raw);
236
- } catch {
237
- argsComplete = false;
238
- }
239
- return renderer({
240
- args,
241
- status: !argsComplete ? "inProgress" : toolMessage !== void 0 ? "complete" : executingToolCallIds?.has(toolCall.id) ? "executing" : "complete",
242
- result: toolMessage?.content
243
- });
244
- }, [toolRenderers, executingToolCallIds]);
245
- }
246
-
247
- //#endregion
248
- export { CopilotKitProvider as i, useComponent as n, useRenderTool as r, useRenderToolCall as t };
249
- //# sourceMappingURL=useRenderToolCall-DjhQb8Ki.mjs.map
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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,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J,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,eAAuC,eACpC;EACL;EACA;EACD,GACD,CAAC,YAAY,qBAAqB,CACnC;CAGD,MAAM,sBAAsB,cACpB,0BAA0B,qBAAqB,EACrD,CAAC,qBAAqB,CACvB;AAED,QACE,oBAAC,kBAAkB;EAAS,OAAO;YACjC,oBAAC,eAAe;GAAS,OAAO;aAC9B,oBAAC,sBAAoB,WAA8B;IAC3B;GACC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC5KjC,SAAgB,cAEd,SAAkC,MAAqC;CACvE,MAAM,EAAE,MAAM,aAAa,YAAY,QAAQ,SAAS,YAAY;CACpE,MAAM,EAAE,aAAa,sBAAsB;AAG3C,iBACE;EACE;EACA;EACA;EACA;EACA;EACD,EACD,KACD;CAGD,MAAM,YAAY,OAAO,OAAO;AAChC,WAAU,UAAU;AAGpB,iBAAgB;EAEd,MAAM,gBAAuC,UAC3C,UAAU,QAAQ,MAAM;AAG1B,SADmB,SAAS,MAAM,aAAmC;IAEpE,CAAC,MAAM,SAAS,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkit/react-native",
3
- "version": "1.66.1-canary.rn-tool-render",
3
+ "version": "1.66.2-canary.1785866877",
4
4
  "private": false,
5
5
  "keywords": [
6
6
  "ai",
@@ -70,9 +70,9 @@
70
70
  },
71
71
  "dependencies": {
72
72
  "@ag-ui/client": "0.0.57",
73
- "@copilotkit/core": "1.66.1-canary.rn-tool-render",
74
- "@copilotkit/react-core": "1.66.1-canary.rn-tool-render",
75
- "@copilotkit/shared": "1.66.1-canary.rn-tool-render",
73
+ "@copilotkit/core": "1.66.2-canary.1785866877",
74
+ "@copilotkit/react-core": "1.66.2-canary.1785866877",
75
+ "@copilotkit/shared": "1.66.2-canary.1785866877",
76
76
  "text-encoding": "^0.7.0",
77
77
  "web-streams-polyfill": "^4.2.0"
78
78
  },
@@ -9,15 +9,15 @@ import {
9
9
  TextInput,
10
10
  TouchableOpacity,
11
11
  View,
12
+ type ListRenderItemInfo,
13
+ type ViewStyle,
12
14
  } from "react-native";
13
- import type { ListRenderItemInfo, ViewStyle } from "react-native";
14
15
  import { useAgent } from "@copilotkit/react-core/v2/headless";
15
16
  import { useCopilotKit } from "@copilotkit/react-core/v2/context";
16
17
  import { AssistantMessage } from "./messages/AssistantMessage";
17
18
  import { UserMessage } from "./messages/UserMessage";
18
19
  import { useRenderToolRegistry } from "../hooks/RenderToolContext";
19
20
  import type { Message } from "@copilotkit/shared";
20
- import { partialJSONParse } from "@copilotkit/shared";
21
21
 
22
22
  /** Shape of an assistant message with optional tool calls. */
23
23
  interface AssistantMessageShape {
@@ -232,25 +232,18 @@ export function CopilotChat({
232
232
  const tc = item.toolCalls[0];
233
233
  const renderer = toolRenderers.get(tc.function.name);
234
234
  if (renderer) {
235
- // Partial parse, NOT JSON.parse: while the model is still writing the call, the argument
236
- // string is incomplete JSON. JSON.parse threw on every streamed delta, warned, and fell
237
- // back to {} — so a registered component rendered nothing until the call finished. Partial
238
- // parsing lets it paint as the arguments arrive, which is what the web renderer does.
239
- const raw = tc.function.arguments || "{}";
240
- const args = partialJSONParse(raw);
241
- // Incomplete JSON IS the signal that the model is still writing this call — no extra
242
- // stream state needed. Once it parses strictly, fall back to the previous semantics.
243
- let argsComplete = true;
235
+ let args: Record<string, unknown> = {};
244
236
  try {
245
- JSON.parse(raw);
246
- } catch {
247
- argsComplete = false;
237
+ args = JSON.parse(tc.function.arguments || "{}");
238
+ } catch (e) {
239
+ console.warn(
240
+ `[CopilotChat] Failed to parse tool call arguments for ${tc.function.name}:`,
241
+ e,
242
+ );
248
243
  }
249
- const status = !argsComplete
250
- ? "inProgress"
251
- : executingToolCallIds.has(tc.id)
252
- ? "executing"
253
- : "complete";
244
+ const status = executingToolCallIds.has(tc.id)
245
+ ? "executing"
246
+ : "complete";
254
247
  return renderer({ args, status });
255
248
  }
256
249
  // Subtle indicator for unregistered tool calls
package/src/headless.ts CHANGED
@@ -48,9 +48,7 @@ export {
48
48
  export {
49
49
  useAgent,
50
50
  useFrontendTool,
51
- // NOT react-core's useComponent — it registers into react-core's render registry, which this
52
- // package's renderers do not read, so components registered with it rendered nowhere on RN.
53
- // Our own is exported below and registers into this package's registry.
51
+ useComponent,
54
52
  useHumanInTheLoop,
55
53
  useInterrupt,
56
54
  useSuggestions,
@@ -104,14 +102,6 @@ export type {
104
102
  // Render tool hook (React Native version with render registry integration).
105
103
  // No DOM and no chat-UI stack: the app supplies the renderers.
106
104
  export { useRenderTool } from "./hooks/useRenderTool";
107
- // RN-native useComponent: registers into THIS package's render registry. react-core's version
108
- // registers into its own, which RN renderers do not read, so it rendered nowhere here.
109
- export { useComponent } from "./hooks/useComponent";
110
- export { useRenderToolCall } from "./hooks/useRenderToolCall";
111
- export type {
112
- RenderToolCallInput,
113
- RenderableToolCall,
114
- } from "./hooks/useRenderToolCall";
115
105
  export type { UseRenderToolOptions } from "./hooks/useRenderTool";
116
106
  export {
117
107
  RenderToolProvider,
@@ -11,21 +11,8 @@ import React, {
11
11
  * Props passed to a render tool function.
12
12
  */
13
13
  export interface RenderToolProps<T = Record<string, unknown>> {
14
- /**
15
- * The tool call arguments.
16
- *
17
- * While the call is still streaming (`status: "inProgress"`) these are PARTIAL: the model has not
18
- * finished writing the JSON, so fields arrive progressively and arrays fill in. Renderers must
19
- * tolerate missing fields — that is what allows UI to build as the agent writes it rather than
20
- * appearing all at once when the call completes.
21
- */
22
- args: Partial<T> & Record<string, unknown>;
23
- /**
24
- * "inProgress" — arguments are still streaming; `args` is incomplete.
25
- * "executing" — arguments are complete and the handler (if any) is running.
26
- * "complete" — the handler finished; `result` is populated.
27
- */
28
- status: "inProgress" | "executing" | "complete";
14
+ args: T;
15
+ status: "executing" | "complete";
29
16
  result?: string;
30
17
  }
31
18
 
@@ -1,10 +1,4 @@
1
1
  export { useRenderTool } from "./useRenderTool";
2
- export { useComponent } from "./useComponent";
3
- export { useRenderToolCall } from "./useRenderToolCall";
4
- export type {
5
- RenderToolCallInput,
6
- RenderableToolCall,
7
- } from "./useRenderToolCall";
8
2
  export type { UseRenderToolOptions } from "./useRenderTool";
9
3
 
10
4
  export { RenderToolProvider, useRenderToolRegistry } from "./RenderToolContext";
package/src/index.ts CHANGED
@@ -53,9 +53,6 @@ export type { CopilotPopupProps, CopilotPopupHandle } from "./CopilotPopup";
53
53
  // "./headless" above (`export * from "./headless"`).
54
54
  //
55
55
  // Deliberately NOT re-exported (web-specific, from @copilotkit/react-core/v2):
56
- // (react-core's useRenderToolCall) — depends on DOM via DefaultToolCallRenderer. We export our
57
- // OWN React Native useRenderToolCall from "./headless" instead: same job, no DOM, backed by this
58
- // package's render-tool registry. Excluding the web one had also dropped the capability, which
59
- // left non-chat RN surfaces with no way to render a registered component at all.
56
+ // useRenderToolCall — depends on DOM elements via DefaultToolCallRenderer
60
57
  // useRenderCustomMessages / useRenderActivityMessage — web chat UI pipeline
61
58
  // useDefaultRenderTool — DefaultToolCallRenderer uses <div>, <svg>, etc.
@@ -1 +0,0 @@
1
- {"version":3,"file":"useRenderToolCall-DawGeFfu.cjs","names":["CopilotKitCoreReact","CopilotKitContext","LicenseContext","RenderToolProvider","useRenderToolContext","useRenderToolRegistry"],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/useRenderTool.ts","../src/hooks/useComponent.tsx","../src/hooks/useRenderToolCall.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","import React from \"react\";\nimport type { ComponentType } from \"react\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport { useRenderTool } from \"./useRenderTool\";\n\n/**\n * Register a component the agent can choose to display — the controlled generative-UI primitive,\n * for React Native.\n *\n * `@copilotkit/react-core` has a `useComponent` of the same shape, but it registers into react-core's\n * own render registry, which this package's renderers do not read. On React Native that meant a\n * component registered with it rendered nowhere: not in `CopilotChat`, and not on a custom surface.\n * This version registers into THIS package's registry, so one registration renders in the chat and\n * anywhere you call `useRenderToolCall()`.\n *\n * Like react-core's, it is render-only: there is no handler, because displaying the component IS the\n * effect. Props are the tool arguments, spread directly, so a component can be used as-is.\n *\n * Arguments stream, so props may be INCOMPLETE on early renders (see `RenderToolProps.args`). Write\n * components that tolerate missing fields — that is what lets UI build as the agent writes it.\n *\n * @example\n * ```tsx\n * useComponent({\n * name: \"showWeatherCard\",\n * description: \"Show the weather for a city.\",\n * parameters: z.object({ city: z.string() }),\n * render: ({ city }) => <Text>{city}</Text>,\n * });\n * ```\n */\nexport function useComponent<\n TSchema extends StandardSchemaV1<unknown, Record<string, unknown>>,\n>(\n config: {\n /** Tool name the agent calls. */\n name: string;\n /** What this component shows, and when the agent should choose it. */\n description?: string;\n /** Schema for the component's props. */\n parameters: TSchema;\n /** The component to render. Receives the tool arguments as props. */\n render: ComponentType<any>;\n /** Scope to a single agent. */\n agentId?: string;\n },\n deps?: ReadonlyArray<unknown>,\n): void {\n const prefix = `Use this tool to display the \"${config.name}\" component to the user. This tool renders a visual UI component.`;\n const description = config.description\n ? `${prefix}\\n\\n${config.description}`\n : prefix;\n\n const Component = config.render;\n\n useRenderTool(\n {\n name: config.name,\n description,\n parameters: config.parameters,\n // Props are the arguments, spread — the component needs no knowledge of CopilotKit.\n render: ({ args }) => (\n <Component {...(args as Record<string, unknown>)} />\n ),\n agentId: config.agentId,\n },\n deps,\n );\n}\n","import { useCallback } from \"react\";\nimport type { ReactElement } from \"react\";\nimport { partialJSONParse } from \"@copilotkit/shared\";\nimport { useCopilotKit } from \"@copilotkit/react-core/v2/headless\";\nimport { useRenderToolRegistry } from \"./RenderToolContext\";\n\n/** A tool call as it appears on an assistant message. */\nexport interface RenderableToolCall {\n id: string;\n function: { name: string; arguments?: string };\n}\n\nexport interface RenderToolCallInput {\n toolCall: RenderableToolCall;\n /** The matching tool result message, when the call has produced one. */\n toolMessage?: { content?: string } | undefined;\n}\n\n/**\n * Render a tool call using the render function registered for it, ANYWHERE in your app.\n *\n * `CopilotChat` renders tool calls inline in its own message list, which is the right default for a\n * chat. But plenty of React Native surfaces are not chats — an in-car stage, a kiosk, a dashboard —\n * and they still want the agent to drive the UI. Without this hook there was no public way to render\n * a registered component outside the chat, which also made `useComponent` unusable on those surfaces.\n *\n * Arguments are partial-JSON-parsed, so a component paints as the agent writes the call\n * (`status: \"inProgress\"`) and fills in as more arrives — the same progressive behaviour the web\n * renderer has. Renderers therefore need to tolerate incomplete `args`.\n *\n * @example\n * ```tsx\n * const renderToolCall = useRenderToolCall();\n *\n * // panels the agent has called this turn, laid out however you like\n * return <View>{toolCalls.map((tc) => renderToolCall({ toolCall: tc }))}</View>;\n * ```\n */\nexport function useRenderToolCall(): (\n input: RenderToolCallInput,\n) => ReactElement | null {\n // The registry Map, same source CopilotChat renders from — so a component registered once\n // works in the chat and on a custom surface without registering twice.\n const toolRenderers = useRenderToolRegistry();\n const { executingToolCallIds } = useCopilotKit();\n\n return useCallback(\n ({ toolCall, toolMessage }: RenderToolCallInput) => {\n const renderer = toolRenderers.get(toolCall.function.name);\n if (!renderer) return null;\n\n const raw = toolCall.function.arguments || \"{}\";\n const args = partialJSONParse(raw);\n\n // Incomplete JSON means the model is still writing this call.\n let argsComplete = true;\n try {\n JSON.parse(raw);\n } catch {\n argsComplete = false;\n }\n\n const status = !argsComplete\n ? \"inProgress\"\n : toolMessage !== undefined\n ? \"complete\"\n : executingToolCallIds?.has(toolCall.id)\n ? \"executing\"\n : \"complete\";\n\n return renderer({ args, status, result: toolMessage?.content });\n },\n [toolRenderers, executingToolCallIds],\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,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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I;AACF,QAAK,MAAM,IAAI;UACT;AACN,kBAAe;;AAWjB,SAAO,SAAS;GAAE;GAAM,QART,CAAC,eACZ,eACA,gBAAgB,SACd,aACA,sBAAsB,IAAI,SAAS,GAAG,GACpC,cACA;GAEwB,QAAQ,aAAa;GAAS,CAAC;IAEjE,CAAC,eAAe,qBAAqB,CACtC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"useRenderToolCall-DjhQb8Ki.mjs","names":["useCopilotKit"],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/useRenderTool.ts","../src/hooks/useComponent.tsx","../src/hooks/useRenderToolCall.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","import React from \"react\";\nimport type { ComponentType } from \"react\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport { useRenderTool } from \"./useRenderTool\";\n\n/**\n * Register a component the agent can choose to display — the controlled generative-UI primitive,\n * for React Native.\n *\n * `@copilotkit/react-core` has a `useComponent` of the same shape, but it registers into react-core's\n * own render registry, which this package's renderers do not read. On React Native that meant a\n * component registered with it rendered nowhere: not in `CopilotChat`, and not on a custom surface.\n * This version registers into THIS package's registry, so one registration renders in the chat and\n * anywhere you call `useRenderToolCall()`.\n *\n * Like react-core's, it is render-only: there is no handler, because displaying the component IS the\n * effect. Props are the tool arguments, spread directly, so a component can be used as-is.\n *\n * Arguments stream, so props may be INCOMPLETE on early renders (see `RenderToolProps.args`). Write\n * components that tolerate missing fields — that is what lets UI build as the agent writes it.\n *\n * @example\n * ```tsx\n * useComponent({\n * name: \"showWeatherCard\",\n * description: \"Show the weather for a city.\",\n * parameters: z.object({ city: z.string() }),\n * render: ({ city }) => <Text>{city}</Text>,\n * });\n * ```\n */\nexport function useComponent<\n TSchema extends StandardSchemaV1<unknown, Record<string, unknown>>,\n>(\n config: {\n /** Tool name the agent calls. */\n name: string;\n /** What this component shows, and when the agent should choose it. */\n description?: string;\n /** Schema for the component's props. */\n parameters: TSchema;\n /** The component to render. Receives the tool arguments as props. */\n render: ComponentType<any>;\n /** Scope to a single agent. */\n agentId?: string;\n },\n deps?: ReadonlyArray<unknown>,\n): void {\n const prefix = `Use this tool to display the \"${config.name}\" component to the user. This tool renders a visual UI component.`;\n const description = config.description\n ? `${prefix}\\n\\n${config.description}`\n : prefix;\n\n const Component = config.render;\n\n useRenderTool(\n {\n name: config.name,\n description,\n parameters: config.parameters,\n // Props are the arguments, spread — the component needs no knowledge of CopilotKit.\n render: ({ args }) => (\n <Component {...(args as Record<string, unknown>)} />\n ),\n agentId: config.agentId,\n },\n deps,\n );\n}\n","import { useCallback } from \"react\";\nimport type { ReactElement } from \"react\";\nimport { partialJSONParse } from \"@copilotkit/shared\";\nimport { useCopilotKit } from \"@copilotkit/react-core/v2/headless\";\nimport { useRenderToolRegistry } from \"./RenderToolContext\";\n\n/** A tool call as it appears on an assistant message. */\nexport interface RenderableToolCall {\n id: string;\n function: { name: string; arguments?: string };\n}\n\nexport interface RenderToolCallInput {\n toolCall: RenderableToolCall;\n /** The matching tool result message, when the call has produced one. */\n toolMessage?: { content?: string } | undefined;\n}\n\n/**\n * Render a tool call using the render function registered for it, ANYWHERE in your app.\n *\n * `CopilotChat` renders tool calls inline in its own message list, which is the right default for a\n * chat. But plenty of React Native surfaces are not chats — an in-car stage, a kiosk, a dashboard —\n * and they still want the agent to drive the UI. Without this hook there was no public way to render\n * a registered component outside the chat, which also made `useComponent` unusable on those surfaces.\n *\n * Arguments are partial-JSON-parsed, so a component paints as the agent writes the call\n * (`status: \"inProgress\"`) and fills in as more arrives — the same progressive behaviour the web\n * renderer has. Renderers therefore need to tolerate incomplete `args`.\n *\n * @example\n * ```tsx\n * const renderToolCall = useRenderToolCall();\n *\n * // panels the agent has called this turn, laid out however you like\n * return <View>{toolCalls.map((tc) => renderToolCall({ toolCall: tc }))}</View>;\n * ```\n */\nexport function useRenderToolCall(): (\n input: RenderToolCallInput,\n) => ReactElement | null {\n // The registry Map, same source CopilotChat renders from — so a component registered once\n // works in the chat and on a custom surface without registering twice.\n const toolRenderers = useRenderToolRegistry();\n const { executingToolCallIds } = useCopilotKit();\n\n return useCallback(\n ({ toolCall, toolMessage }: RenderToolCallInput) => {\n const renderer = toolRenderers.get(toolCall.function.name);\n if (!renderer) return null;\n\n const raw = toolCall.function.arguments || \"{}\";\n const args = partialJSONParse(raw);\n\n // Incomplete JSON means the model is still writing this call.\n let argsComplete = true;\n try {\n JSON.parse(raw);\n } catch {\n argsComplete = false;\n }\n\n const status = !argsComplete\n ? \"inProgress\"\n : toolMessage !== undefined\n ? \"complete\"\n : executingToolCallIds?.has(toolCall.id)\n ? \"executing\"\n : \"complete\";\n\n return renderer({ args, status, result: toolMessage?.content });\n },\n [toolRenderers, executingToolCallIds],\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,OAAO,gBAAgB,aAAa,aAAa,GAAG;CAKtD,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M,OAAO;EACb;EACA,YAAY,OAAO;EAEnB,SAAS,EAAE,WACT,oBAAC,aAAU,GAAK,OAAoC;EAEtD,SAAS,OAAO;EACjB,EACD,KACD;;;;;;;;;;;;;;;;;;;;;;;;;AC7BH,SAAgB,oBAES;CAGvB,MAAM,gBAAgB,uBAAuB;CAC7C,MAAM,EAAE,yBAAyBA,iBAAe;AAEhD,QAAO,aACJ,EAAE,UAAU,kBAAuC;EAClD,MAAM,WAAW,cAAc,IAAI,SAAS,SAAS,KAAK;AAC1D,MAAI,CAAC,SAAU,QAAO;EAEtB,MAAM,MAAM,SAAS,SAAS,aAAa;EAC3C,MAAM,OAAO,iBAAiB,IAAI;EAGlC,IAAI,eAAe;AACnB,MAAI;AACF,QAAK,MAAM,IAAI;UACT;AACN,kBAAe;;AAWjB,SAAO,SAAS;GAAE;GAAM,QART,CAAC,eACZ,eACA,gBAAgB,SACd,aACA,sBAAsB,IAAI,SAAS,GAAG,GACpC,cACA;GAEwB,QAAQ,aAAa;GAAS,CAAC;IAEjE,CAAC,eAAe,qBAAqB,CACtC"}
@@ -1,160 +0,0 @@
1
- import React from "react";
2
- import { render } from "@testing-library/react";
3
- import { describe, it, expect, vi } from "vitest";
4
-
5
- // ─── Mocks ────────────────────────────────────────────────────────────────────
6
-
7
- const hoisted = vi.hoisted(() => ({
8
- executingToolCallIds: new Set<string>(),
9
- registry: new Map<string, any>(),
10
- lastConfig: null as any,
11
- }));
12
-
13
- vi.mock("@copilotkit/react-core/v2/headless", () => ({
14
- useCopilotKit: () => ({ executingToolCallIds: hoisted.executingToolCallIds }),
15
- }));
16
-
17
- vi.mock("../RenderToolContext", () => ({
18
- useRenderToolRegistry: () => hoisted.registry,
19
- }));
20
-
21
- import { useRenderToolCall } from "../useRenderToolCall";
22
-
23
- /** Renders one tool call and reports the props the registered renderer received. */
24
- function renderCall(toolCall: any, toolMessage?: any) {
25
- let seen: any = null;
26
- hoisted.registry.set("showAbout", (props: any) => {
27
- seen = props;
28
- return null;
29
- });
30
-
31
- function Probe() {
32
- const renderToolCall = useRenderToolCall();
33
- return <>{renderToolCall({ toolCall, toolMessage })}</>;
34
- }
35
- render(<Probe />);
36
- return seen;
37
- }
38
-
39
- const call = (args: string, id = "tc-1") => ({
40
- id,
41
- function: { name: "showAbout", arguments: args },
42
- });
43
-
44
- describe("useRenderToolCall", () => {
45
- it("renders a registered component for a tool call", () => {
46
- const props = renderCall(call('{"dataId":"zosch"}'));
47
- expect(props).not.toBeNull();
48
- expect(props.args).toEqual({ dataId: "zosch" });
49
- });
50
-
51
- it("returns null for a tool with no registered renderer", () => {
52
- let out: unknown = "unset";
53
- function Probe() {
54
- const renderToolCall = useRenderToolCall();
55
- out = renderToolCall({
56
- toolCall: {
57
- id: "x",
58
- function: { name: "notRegistered", arguments: "{}" },
59
- },
60
- });
61
- return null;
62
- }
63
- render(<Probe />);
64
- expect(out).toBeNull();
65
- });
66
-
67
- // The point of the hook: paint while the model is still writing the call.
68
- it("exposes PARTIAL args with status inProgress while arguments are incomplete", () => {
69
- const props = renderCall(call('{"dataId":"neues-mus'));
70
- expect(props.status).toBe("inProgress");
71
- // partial JSON still yields the keys written so far
72
- expect(props.args).toEqual({ dataId: "neues-mus" });
73
- });
74
-
75
- it("does not throw on a fragment that has no complete key yet", () => {
76
- const props = renderCall(call('{"places":[{"title":"Roof'));
77
- expect(props.status).toBe("inProgress");
78
- expect(props.args).toBeTypeOf("object");
79
- });
80
-
81
- it("reports executing once arguments are complete and the handler is running", () => {
82
- hoisted.executingToolCallIds.add("tc-run");
83
- const props = renderCall(call('{"dataId":"zosch"}', "tc-run"), undefined);
84
- expect(props.status).toBe("executing");
85
- hoisted.executingToolCallIds.delete("tc-run");
86
- });
87
-
88
- it("reports complete and passes the result through when a tool message exists", () => {
89
- const props = renderCall(call('{"dataId":"zosch"}'), { content: "ok" });
90
- expect(props.status).toBe("complete");
91
- expect(props.result).toBe("ok");
92
- });
93
-
94
- it("treats absent arguments as an empty object, not a crash", () => {
95
- const props = renderCall({
96
- id: "tc-2",
97
- function: { name: "showAbout" },
98
- } as any);
99
- expect(props.args).toEqual({});
100
- expect(props.status).toBe("complete");
101
- });
102
- });
103
-
104
- // ─── useComponent (RN) ────────────────────────────────────────────────────────
105
-
106
- vi.mock("../useRenderTool", () => ({
107
- useRenderTool: (config: any) => {
108
- hoisted.registry.set(config.name, config.render);
109
- hoisted.lastConfig = config;
110
- },
111
- }));
112
-
113
- import { useComponent } from "../useComponent";
114
-
115
- describe("useComponent (React Native)", () => {
116
- it("registers into THIS package's registry so a custom surface can render it", () => {
117
- function Probe() {
118
- useComponent({
119
- name: "showCity",
120
- parameters: {} as any,
121
- render: ({ city }: { city?: string }) => <>{city ?? null}</>,
122
- });
123
- return null;
124
- }
125
- render(<Probe />);
126
- expect(hoisted.registry.has("showCity")).toBe(true);
127
- });
128
-
129
- it("spreads the tool arguments as props, so components need no CopilotKit knowledge", () => {
130
- let received: any = null;
131
- function Probe() {
132
- useComponent({
133
- name: "showCity2",
134
- parameters: {} as any,
135
- render: (props: any) => {
136
- received = props;
137
- return null;
138
- },
139
- });
140
- return null;
141
- }
142
- render(<Probe />);
143
- const renderFn = hoisted.registry.get("showCity2");
144
- render(<>{renderFn({ args: { city: "Berlin" }, status: "inProgress" })}</>);
145
- expect(received).toEqual({ city: "Berlin" });
146
- });
147
-
148
- it("is render-only: it registers no handler", () => {
149
- function Probe() {
150
- useComponent({
151
- name: "showCity3",
152
- parameters: {} as any,
153
- render: () => null,
154
- });
155
- return null;
156
- }
157
- render(<Probe />);
158
- expect(hoisted.lastConfig.handler).toBeUndefined();
159
- });
160
- });
@@ -1,69 +0,0 @@
1
- import React from "react";
2
- import type { ComponentType } from "react";
3
- import type { StandardSchemaV1 } from "@copilotkit/shared";
4
- import { useRenderTool } from "./useRenderTool";
5
-
6
- /**
7
- * Register a component the agent can choose to display — the controlled generative-UI primitive,
8
- * for React Native.
9
- *
10
- * `@copilotkit/react-core` has a `useComponent` of the same shape, but it registers into react-core's
11
- * own render registry, which this package's renderers do not read. On React Native that meant a
12
- * component registered with it rendered nowhere: not in `CopilotChat`, and not on a custom surface.
13
- * This version registers into THIS package's registry, so one registration renders in the chat and
14
- * anywhere you call `useRenderToolCall()`.
15
- *
16
- * Like react-core's, it is render-only: there is no handler, because displaying the component IS the
17
- * effect. Props are the tool arguments, spread directly, so a component can be used as-is.
18
- *
19
- * Arguments stream, so props may be INCOMPLETE on early renders (see `RenderToolProps.args`). Write
20
- * components that tolerate missing fields — that is what lets UI build as the agent writes it.
21
- *
22
- * @example
23
- * ```tsx
24
- * useComponent({
25
- * name: "showWeatherCard",
26
- * description: "Show the weather for a city.",
27
- * parameters: z.object({ city: z.string() }),
28
- * render: ({ city }) => <Text>{city}</Text>,
29
- * });
30
- * ```
31
- */
32
- export function useComponent<
33
- TSchema extends StandardSchemaV1<unknown, Record<string, unknown>>,
34
- >(
35
- config: {
36
- /** Tool name the agent calls. */
37
- name: string;
38
- /** What this component shows, and when the agent should choose it. */
39
- description?: string;
40
- /** Schema for the component's props. */
41
- parameters: TSchema;
42
- /** The component to render. Receives the tool arguments as props. */
43
- render: ComponentType<any>;
44
- /** Scope to a single agent. */
45
- agentId?: string;
46
- },
47
- deps?: ReadonlyArray<unknown>,
48
- ): void {
49
- const prefix = `Use this tool to display the "${config.name}" component to the user. This tool renders a visual UI component.`;
50
- const description = config.description
51
- ? `${prefix}\n\n${config.description}`
52
- : prefix;
53
-
54
- const Component = config.render;
55
-
56
- useRenderTool(
57
- {
58
- name: config.name,
59
- description,
60
- parameters: config.parameters,
61
- // Props are the arguments, spread — the component needs no knowledge of CopilotKit.
62
- render: ({ args }) => (
63
- <Component {...(args as Record<string, unknown>)} />
64
- ),
65
- agentId: config.agentId,
66
- },
67
- deps,
68
- );
69
- }