@copilotkit/react-native 1.85.0 → 1.86.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 (55) hide show
  1. package/README.md +341 -2
  2. package/USAGE.md +388 -21
  3. package/dist/{CopilotKitProvider-DBq4AhRP.d.cts → CopilotKitProvider-CQ-DpvY1.d.cts} +2 -2
  4. package/dist/{CopilotKitProvider-D8sn7G_C.mjs → CopilotKitProvider-CXQGv39c.mjs} +1 -1
  5. package/dist/{CopilotKitProvider-D8sn7G_C.mjs.map → CopilotKitProvider-CXQGv39c.mjs.map} +1 -1
  6. package/dist/{CopilotKitProvider-fW21Gb7T.d.mts → CopilotKitProvider-Dc1Vbv7K.d.mts} +1 -1
  7. package/dist/{CopilotKitProvider-CjoPnabW.cjs → CopilotKitProvider-zSfbWwIg.cjs} +1 -1
  8. package/dist/{CopilotKitProvider-CjoPnabW.cjs.map → CopilotKitProvider-zSfbWwIg.cjs.map} +1 -1
  9. package/dist/components/index.cjs +1 -0
  10. package/dist/components/index.cjs.map +1 -1
  11. package/dist/components/index.mjs +1 -0
  12. package/dist/components/index.mjs.map +1 -1
  13. package/dist/generative-ui/index.cjs +612 -0
  14. package/dist/generative-ui/index.cjs.map +1 -0
  15. package/dist/generative-ui/index.d.cts +341 -0
  16. package/dist/generative-ui/index.d.mts +341 -0
  17. package/dist/generative-ui/index.mjs +549 -0
  18. package/dist/generative-ui/index.mjs.map +1 -0
  19. package/dist/headless.cjs +1 -1
  20. package/dist/headless.d.cts +1 -1
  21. package/dist/headless.d.mts +1 -1
  22. package/dist/headless.mjs +1 -1
  23. package/dist/index.cjs +2 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +2 -2
  26. package/dist/index.d.mts +1 -1
  27. package/dist/index.mjs +2 -1
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/polyfills.cjs +218 -2
  30. package/dist/polyfills.cjs.map +1 -1
  31. package/dist/polyfills.mjs +217 -1
  32. package/dist/polyfills.mjs.map +1 -1
  33. package/package.json +12 -4
  34. package/project.json +6 -1
  35. package/scripts/__tests__/verify-polyfill-barrel.test.mjs +150 -0
  36. package/scripts/verify-polyfill-barrel.mjs +154 -5
  37. package/src/__tests__/generative-ui-harness.tsx +243 -0
  38. package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
  39. package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
  40. package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
  41. package/src/__tests__/generative-ui.test.tsx +1000 -0
  42. package/src/__tests__/headless-entry-surface.test.ts +964 -34
  43. package/src/components/index.ts +6 -0
  44. package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
  45. package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
  46. package/src/generative-ui/GenerativeUISurface.tsx +303 -0
  47. package/src/generative-ui/host.tsx +138 -0
  48. package/src/generative-ui/index.ts +99 -0
  49. package/src/generative-ui/internal.ts +55 -0
  50. package/src/index.ts +8 -3
  51. package/tsdown.config.ts +1 -0
  52. package/dist/streaming-fetch-Bm91EsRc.cjs +0 -225
  53. package/dist/streaming-fetch-Bm91EsRc.cjs.map +0 -1
  54. package/dist/streaming-fetch-Dm1oN4f2.mjs +0 -219
  55. package/dist/streaming-fetch-Dm1oN4f2.mjs.map +0 -1
package/README.md CHANGED
@@ -5,9 +5,13 @@ Headless React Native bindings for CopilotKit. Provides a lightweight provider a
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- npm install @copilotkit/react-native
8
+ npm install @copilotkit/react-native "zod@^3.25"
9
9
  ```
10
10
 
11
+ Every entry needs `zod` 3.25 or later, a peer dependency of
12
+ `@copilotkit/react-core`. The command installs zod 3, which a generative UI
13
+ catalog that uses `child()` or `childList()` needs.
14
+
11
15
  ## Polyfills
12
16
 
13
17
  React Native's JS runtime (Hermes) lacks several Web APIs that CopilotKit depends on. Import the polyfills **before any other code** in your entry point:
@@ -40,7 +44,7 @@ import {
40
44
  CopilotKitProvider,
41
45
  useAgent,
42
46
  useCopilotKit,
43
- } from "@copilotkit/react-native";
47
+ } from "@copilotkit/react-native/headless";
44
48
 
45
49
  export default function App() {
46
50
  return (
@@ -53,12 +57,347 @@ export default function App() {
53
57
 
54
58
  Re-exports hooks from `@copilotkit/react-core`: `useAgent`, `useFrontendTool`, `useComponent`, `useHumanInTheLoop`, `useInterrupt`, `useSuggestions`, `useConfigureSuggestions`, `useAgentContext`, `useThreads`, and `useCopilotKit`.
55
59
 
60
+ ## Generative UI (experimental)
61
+
62
+ `@copilotkit/react-native/generative-ui` lets the agent render a catalog of your
63
+ own native components with the `render_ui` tool. Install `zod` 3.25 or later:
64
+ every entry of this package needs it, because `@copilotkit/react-core` requires
65
+ it as a peer dependency (`@copilotkit/react-native` declares `zod` an optional
66
+ peer at `>=3.0.0` only because narrowing that range would be a breaking
67
+ change). Install zod 3 (`npm install "zod@^3.25"`) for a catalog that uses
68
+ `child()` or `childList()`: they return zod 3 schemas, which a zod 4 schema
69
+ cannot hold. The runtime needs no change by default: `CopilotRuntime` adds the
70
+ tool when the app sends a catalog with at least one component, unless the
71
+ server sets `generativeUI: false` or limits it with
72
+ `generativeUI: { agents: [...] }`. This example needs a `home` agent on the
73
+ runtime: once the runtime has connected, `useAgent` throws without it. `/generative-ui` is not in 1.85.0 or any earlier version; it first
74
+ ships in the release after 1.85.0.
75
+
76
+ ```tsx
77
+ import { useCallback, useEffect, useRef, useState } from "react";
78
+ import {
79
+ ActivityIndicator,
80
+ Pressable,
81
+ ScrollView,
82
+ Text,
83
+ View,
84
+ } from "react-native";
85
+ import { z } from "zod";
86
+ import {
87
+ CopilotKitCoreErrorCode,
88
+ CopilotKitCoreRuntimeConnectionStatus,
89
+ CopilotKitProvider,
90
+ useAgent,
91
+ useAgentContext,
92
+ useCopilotKit,
93
+ } from "@copilotkit/react-native/headless";
94
+ import {
95
+ GenerativeUIActivity,
96
+ GenerativeUIProvider,
97
+ createGenerativeUI,
98
+ isGenerativeUIActivity,
99
+ useGenerativeUIRuntime,
100
+ type GenerativeUIActivityMessage,
101
+ } from "@copilotkit/react-native/generative-ui";
102
+
103
+ const ui = createGenerativeUI({
104
+ id: "acme/bank@1",
105
+ components: {
106
+ BalanceCard: {
107
+ component: ({ account, amount }: { account: string; amount: number }) => (
108
+ <View>
109
+ <Text>{account}</Text>
110
+ <Text>{amount}</Text>
111
+ </View>
112
+ ),
113
+ description:
114
+ "The balance of one account. Copy the values from the context.",
115
+ props: z.object({ account: z.string(), amount: z.number() }),
116
+ },
117
+ },
118
+ });
119
+
120
+ type CopilotKit = ReturnType<typeof useCopilotKit>["copilotkit"];
121
+ type Agent = ReturnType<typeof useAgent>["agent"];
122
+
123
+ /**
124
+ * The errors that end a run. A failed tool call is not one of them
125
+ * (TOOL_HANDLER_FAILED, TOOL_ARGUMENT_PARSE_FAILED): its error goes back to
126
+ * the model as the result of the call, and the run goes on.
127
+ */
128
+ const RUN_FAILURES: ReadonlySet<CopilotKitCoreErrorCode> = new Set([
129
+ CopilotKitCoreErrorCode.AGENT_RUN_FAILED,
130
+ CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT,
131
+ CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,
132
+ CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED,
133
+ ]);
134
+
135
+ // Date.now() alone repeats within a millisecond; with a counter, ids do not.
136
+ let sent = 0;
137
+
138
+ /**
139
+ * Sends one user message and runs the agent. Resolves with the run's error,
140
+ * or undefined; it never rejects. It counts every run failure of this agent
141
+ * while it waits, so start one run of an agent at a time.
142
+ */
143
+ async function runTurn(copilotkit: CopilotKit, agent: Agent, content: string) {
144
+ const before = agent.messages.map((message) => message.id);
145
+ const { threadId } = agent;
146
+ let failure: Error | undefined;
147
+ const subscription = copilotkit.subscribe({
148
+ onError: ({ error, code, context }) => {
149
+ if (context.agentId === agent.agentId && RUN_FAILURES.has(code)) {
150
+ failure ??= error;
151
+ }
152
+ },
153
+ });
154
+ try {
155
+ sent += 1;
156
+ agent.addMessage({
157
+ id: `user-${Date.now()}-${sent}`,
158
+ role: "user",
159
+ content,
160
+ });
161
+ await copilotkit.runAgent({ agent });
162
+ } catch (error) {
163
+ failure ??= error instanceof Error ? error : new Error(String(error));
164
+ } finally {
165
+ subscription.unsubscribe();
166
+ }
167
+ try {
168
+ if (failure) takeBack(agent, before, threadId);
169
+ } catch (error) {
170
+ console.error("Could not take the failed turn back:", error);
171
+ }
172
+ return failure;
173
+ }
174
+
175
+ /**
176
+ * Removes the messages added since `before` (their ids), such as the user
177
+ * message and a partial reply. It keeps the surfaces: the provider keeps
178
+ * every surface that a run rendered, and the model still sees it, so the
179
+ * screen shows it too.
180
+ */
181
+ function takeBack(
182
+ agent: Agent,
183
+ before: readonly string[],
184
+ threadId: string | undefined,
185
+ ) {
186
+ // The agent moved to another thread: those messages are not this turn's.
187
+ if (agent.threadId !== threadId) return;
188
+ const kept = new Set(before);
189
+ agent.setMessages(
190
+ agent.messages.filter(
191
+ (message) => kept.has(message.id) || isGenerativeUIActivity(message),
192
+ ),
193
+ );
194
+ }
195
+
196
+ /**
197
+ * An activity message that GenerativeUIActivity draws: its surface is aimed at
198
+ * the chat (the target it shows) and the agent has not deleted it.
199
+ */
200
+ function isChatSurface(message: GenerativeUIActivityMessage) {
201
+ if (!isGenerativeUIActivity(message)) return false;
202
+ const content = message.content as {
203
+ target?: unknown;
204
+ operations?: unknown;
205
+ } | null;
206
+ const operations = Array.isArray(content?.operations)
207
+ ? content.operations
208
+ : [];
209
+ return (
210
+ content?.target === "chat" &&
211
+ !operations.some(
212
+ (op) => typeof op === "object" && op !== null && "deleteSurface" in op,
213
+ )
214
+ );
215
+ }
216
+
217
+ /**
218
+ * The chat surfaces that this device built, each message id with its operations,
219
+ * to tell whether a run rendered or updated one here. The operations alone: each
220
+ * call of the agent also refills the list of rejected operations, so a call whose
221
+ * updates were all rejected changes the content but not the surface. A surface
222
+ * whose createSurface the app rejected (`failed`) does not count: the app checks
223
+ * the operations again, prop values included, and GenerativeUIActivity then shows
224
+ * only an error line.
225
+ */
226
+ function chatSurfaces(
227
+ messages: readonly GenerativeUIActivityMessage[],
228
+ failed: (surfaceId: string) => boolean,
229
+ ) {
230
+ const built = new Map<string | undefined, string>();
231
+ for (const message of messages.filter(isChatSurface)) {
232
+ const { surfaceId, operations } = message.content as {
233
+ surfaceId?: unknown;
234
+ operations?: unknown;
235
+ };
236
+ if (typeof surfaceId === "string" && failed(surfaceId)) continue;
237
+ built.set(message.id, JSON.stringify(operations));
238
+ }
239
+ return built;
240
+ }
241
+
242
+ // Your app's data. The agent sees only what you give it with useAgentContext.
243
+ const accounts = [
244
+ { account: "Chequing", amount: 3482.1 },
245
+ { account: "Savings", amount: 6150 },
246
+ ];
247
+
248
+ function Home() {
249
+ const { copilotkit } = useCopilotKit();
250
+ // Until the runtime connects, `agent` is a stand-in (`isReady` is false). The
251
+ // registered agent replaces it, so a run started on the stand-in is lost.
252
+ // Once the runtime has connected, useAgent throws if it has no `home` agent.
253
+ const { agent, isReady } = useAgent({ agentId: "home" });
254
+ const runtime = useGenerativeUIRuntime();
255
+ // The thread it last checked: a ref, so StrictMode's second effect run sees it.
256
+ const checkedThread = useRef<string | undefined>(undefined);
257
+ const composing = useRef(false); // a ref, so a second tap is ignored at once
258
+ const [checked, setChecked] = useState(false);
259
+ const [busy, setBusy] = useState(false);
260
+ const [error, setError] = useState<string>();
261
+
262
+ useAgentContext({
263
+ description:
264
+ "The user's accounts. Show only these, with these exact balances.",
265
+ value: accounts,
266
+ });
267
+
268
+ const failed = useCallback(
269
+ (surfaceId: string) =>
270
+ !!runtime?.manager.getFailedSurface(agent.threadId, surfaceId),
271
+ [runtime, agent],
272
+ );
273
+
274
+ const compose = useCallback(async () => {
275
+ // A stand-in agent (not ready) would lose the run.
276
+ if (composing.current || !isReady) return;
277
+ composing.current = true;
278
+ setBusy(true);
279
+ setError(undefined);
280
+ try {
281
+ const before = agent.messages.map((message) => message.id);
282
+ const { threadId } = agent;
283
+ const shownBefore = chatSurfaces(agent.messages, failed);
284
+ const failure = await runTurn(copilotkit, agent, "Show my balances.");
285
+ const shownAfter = chatSurfaces(agent.messages, failed);
286
+ if (failure) {
287
+ // runTurn took the prompt back, so a retry sends it once.
288
+ setError(failure.message);
289
+ } else if (
290
+ ![...shownAfter].some(
291
+ ([id, content]) => shownBefore.get(id) !== content,
292
+ )
293
+ ) {
294
+ // This run rendered or updated nothing here. Take its prompt back too.
295
+ takeBack(agent, before, threadId);
296
+ setError("The agent rendered nothing for this screen.");
297
+ }
298
+ } catch (reason) {
299
+ setError(reason instanceof Error ? reason.message : String(reason));
300
+ } finally {
301
+ composing.current = false;
302
+ setBusy(false);
303
+ }
304
+ }, [agent, copilotkit, failed, isReady]);
305
+
306
+ // The agent and its messages live in the core and outlive this screen. Run only
307
+ // when the registered agent has no surface here yet and is not running, so a
308
+ // screen that mounts again shows what it has instead of composing it again.
309
+ // Check again when the agent moves to another thread, once it is not running
310
+ // and no compose is under way (`busy` reruns this when one ends).
311
+ useEffect(() => {
312
+ if (
313
+ !isReady ||
314
+ busy ||
315
+ composing.current ||
316
+ agent.isRunning ||
317
+ checkedThread.current === agent.threadId
318
+ ) {
319
+ return;
320
+ }
321
+ checkedThread.current = agent.threadId;
322
+ setChecked(true);
323
+ setError(undefined);
324
+ if (chatSurfaces(agent.messages, failed).size === 0) {
325
+ void compose();
326
+ }
327
+ }, [isReady, busy, agent, agent.threadId, agent.isRunning, compose, failed]);
328
+
329
+ const surfaces = agent.messages.filter(isChatSurface);
330
+ const built = chatSurfaces(agent.messages, failed);
331
+ const unreachable =
332
+ copilotkit.runtimeConnectionStatus ===
333
+ CopilotKitCoreRuntimeConnectionStatus.Error;
334
+ const waiting = !isReady || !checked || busy || agent.isRunning;
335
+
336
+ return (
337
+ <ScrollView contentContainerStyle={{ padding: 16 }}>
338
+ {surfaces.map((message) => (
339
+ <GenerativeUIActivity
340
+ key={message.id}
341
+ message={message}
342
+ agent={agent}
343
+ />
344
+ ))}
345
+ {unreachable ? (
346
+ <Text accessibilityRole="alert">
347
+ Can't reach the agent. Check the runtime URL.
348
+ </Text>
349
+ ) : waiting ? (
350
+ <ActivityIndicator />
351
+ ) : error || built.size === 0 ? (
352
+ <Pressable accessibilityRole="button" onPress={() => void compose()}>
353
+ <Text>
354
+ Couldn't load your balances{error ? ` (${error})` : ""}. Tap to try
355
+ again.
356
+ </Text>
357
+ </Pressable>
358
+ ) : null}
359
+ </ScrollView>
360
+ );
361
+ }
362
+
363
+ export default function App() {
364
+ return (
365
+ <CopilotKitProvider runtimeUrl="https://your-server/api/copilotkit">
366
+ <GenerativeUIProvider ui={ui}>
367
+ <Home />
368
+ </GenerativeUIProvider>
369
+ </CopilotKitProvider>
370
+ );
371
+ }
372
+ ```
373
+
374
+ `GenerativeUIActivity` renders the surface of one activity message, in your own
375
+ message list or on a screen with no chat. Like the web chat, it shows only
376
+ surfaces aimed at the chat; pass `target` to show another target. It renders
377
+ nothing (and warns in development) without a `GenerativeUIProvider`, under a
378
+ provider without `ui`, or while the agent has no `threadId`. The example shows
379
+ a spinner, an unreachable runtime and a retry with the reason. A failed run's
380
+ prompt is taken back, but the surfaces it rendered stay: the provider and the
381
+ model keep them. The docs add a chat list.
382
+ `GenerativeUISurface` marks a named place in the app; `style` applies while its
383
+ fallback shows too. Tool transport only; there is no standard catalog, no
384
+ `theme` prop (a `theme` passed from JavaScript is dropped with a development
385
+ warning) and no `openUrl` (it fails with "openUrl is not available on this
386
+ platform"), and the prebuilt `CopilotChat` does not draw surfaces yet. See the
387
+ [React Native docs](https://docs.copilotkit.ai/react-native#generative-ui-with-your-own-components).
388
+
56
389
  ## API Surface
57
390
 
58
391
  The root import (`@copilotkit/react-native`) IS the v2 API.
59
392
  Unlike the web SDK which has `/v2` subpath, React Native exports
60
393
  the v2 API directly from the package root.
61
394
 
395
+ The root also re-exports the chat components and `useAttachments`, which
396
+ imports `expo-document-picker` and `expo-file-system`; Metro resolves them at
397
+ bundle time, so an app that imports from the root must install both.
398
+ `@copilotkit/react-native/headless` exports the provider and hooks without
399
+ them, which is why the Quick Start above uses it.
400
+
62
401
  ## Documentation
63
402
 
64
403
  For full setup instructions, usage examples, and troubleshooting, see the [React Native docs](https://docs.copilotkit.ai/react-native).