@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/USAGE.md CHANGED
@@ -2,23 +2,25 @@
2
2
 
3
3
  ## Prerequisites
4
4
 
5
- Install all required peer dependencies:
5
+ Install the peer dependencies the Quick Start below uses:
6
6
 
7
7
  ```bash
8
- npm install react react-native @gorhom/bottom-sheet react-native-gesture-handler react-native-reanimated react-native-streamdown
8
+ npm install react react-native "zod@^3.25" @gorhom/bottom-sheet react-native-gesture-handler react-native-reanimated react-native-streamdown expo-document-picker expo-file-system
9
9
  ```
10
10
 
11
- `@gorhom/bottom-sheet`, `react-native-gesture-handler`, `react-native-reanimated`, and `react-native-streamdown` are required peer dependencies for the UI components.
11
+ `zod` 3.25 or later is needed by every entry: `@copilotkit/react-core` requires it as a peer dependency. The command installs zod 3, which a generative UI catalog that uses `child()` or `childList()` needs.
12
+
13
+ The other packages are optional peer dependencies. The default entry (`@copilotkit/react-native`) re-exports `useAttachments`, which imports `expo-document-picker` and `expo-file-system`, so Metro needs both whenever an app imports from it. `@gorhom/bottom-sheet`, `react-native-gesture-handler`, `react-native-reanimated` and `react-native-streamdown` are used by the prebuilt components in `@copilotkit/react-native/components`. An app that only imports `@copilotkit/react-native/headless` or `/generative-ui` needs none of them (see "Headless Import Path" below).
12
14
 
13
15
  ## Quick Start
14
16
 
17
+ The provider and the hooks come from `@copilotkit/react-native`. The prebuilt
18
+ chat UI comes from `@copilotkit/react-native/components`.
19
+
15
20
  ```tsx
16
21
  import "@copilotkit/react-native/polyfills";
17
- import {
18
- CopilotKitProvider,
19
- CopilotChat,
20
- useFrontendTool,
21
- } from "@copilotkit/react-native";
22
+ import { CopilotKitProvider, useFrontendTool } from "@copilotkit/react-native";
23
+ import { CopilotChat } from "@copilotkit/react-native/components";
22
24
  import { z } from "zod";
23
25
 
24
26
  function App() {
@@ -35,7 +37,8 @@ function ChatScreen() {
35
37
  name: "showWeather",
36
38
  description: "Show weather info",
37
39
  parameters: z.object({ city: z.string() }),
38
- render: ({ args }) => <WeatherCard city={args.city} />,
40
+ // `args` is partial while the agent is still writing the call.
41
+ render: ({ args }) => <WeatherCard city={args.city ?? ""} />,
39
42
  });
40
43
 
41
44
  return <CopilotChat placeholder="Ask anything..." />;
@@ -44,22 +47,31 @@ function ChatScreen() {
44
47
 
45
48
  ## Available Components
46
49
 
50
+ The components in this section are the prebuilt UI, and they are exported only
51
+ by `@copilotkit/react-native/components`. The package root exports a
52
+ `CopilotChat` and a `CopilotModal` too, but those are headless: they render
53
+ no UI and take no `placeholder` or `headerTitle` (see
54
+ [Headless chat components](#headless-chat-components)).
55
+
47
56
  ### CopilotChat
48
57
 
49
58
  Inline chat panel. Renders a message list with an input bar.
50
59
 
51
60
  ```tsx
52
- import { CopilotChat } from "@copilotkit/react-native";
61
+ import { CopilotChat } from "@copilotkit/react-native/components";
53
62
 
54
63
  <CopilotChat placeholder="Type a message..." />;
55
64
  ```
56
65
 
57
66
  ### CopilotModal
58
67
 
59
- Modal chat overlay. Open/close programmatically via a ref.
68
+ Modal chat overlay (a bottom sheet). Open/close programmatically via a ref.
60
69
 
61
70
  ```tsx
62
- import { CopilotModal, type CopilotModalRef } from "@copilotkit/react-native";
71
+ import {
72
+ CopilotModal,
73
+ type CopilotModalRef,
74
+ } from "@copilotkit/react-native/components";
63
75
  import { useRef } from "react";
64
76
 
65
77
  const modalRef = useRef<CopilotModalRef>(null);
@@ -75,7 +87,7 @@ modalRef.current?.open();
75
87
  Renders Markdown text with sensible React Native styling.
76
88
 
77
89
  ```tsx
78
- import { CopilotMarkdown } from "@copilotkit/react-native";
90
+ import { CopilotMarkdown } from "@copilotkit/react-native/components";
79
91
 
80
92
  <CopilotMarkdown content="**Hello** from CopilotKit!" />;
81
93
  ```
@@ -85,7 +97,10 @@ import { CopilotMarkdown } from "@copilotkit/react-native";
85
97
  Individual message bubbles. Useful when building a custom chat UI.
86
98
 
87
99
  ```tsx
88
- import { AssistantMessage, UserMessage } from "@copilotkit/react-native";
100
+ import {
101
+ AssistantMessage,
102
+ UserMessage,
103
+ } from "@copilotkit/react-native/components";
89
104
 
90
105
  <UserMessage content="What's the weather?" />
91
106
  <AssistantMessage content="It's sunny!" isLoading={false} />
@@ -108,7 +123,7 @@ useFrontendTool({
108
123
  name: "showChart",
109
124
  description: "Display a chart",
110
125
  parameters: z.object({ data: z.record(z.unknown()) }),
111
- render: ({ args }) => <ChartView data={args.data} />,
126
+ render: ({ args }) => <ChartView data={args.data ?? {}} />,
112
127
  });
113
128
  ```
114
129
 
@@ -177,12 +192,34 @@ untyped, so it still compiles there).
177
192
  See the [`useRenderTool` reference](https://docs.copilotkit.ai/reference/react-native/hooks/useRenderTool)
178
193
  for the full migration table.
179
194
 
180
- ## Alternative Import Path
195
+ ## Headless chat components
181
196
 
182
- Components can also be imported from the `/components` subpath:
197
+ `CopilotChat` and `CopilotModal` from the package root render no UI. They wire
198
+ up the agent and render their children, which read the chat state with
199
+ `useCopilotChatContext()`:
183
200
 
184
201
  ```tsx
185
- import { CopilotChat, CopilotModal } from "@copilotkit/react-native/components";
202
+ import { Pressable, Text, View } from "react-native";
203
+ import { CopilotChat, useCopilotChatContext } from "@copilotkit/react-native";
204
+
205
+ function MyChatUI() {
206
+ const { messages, isRunning, submitMessage } = useCopilotChatContext();
207
+ return (
208
+ <View>
209
+ <Text>{`${messages.length} messages`}</Text>
210
+ <Pressable
211
+ disabled={isRunning}
212
+ onPress={() => void submitMessage("Hello!")}
213
+ >
214
+ <Text>Say hello</Text>
215
+ </Pressable>
216
+ </View>
217
+ );
218
+ }
219
+
220
+ <CopilotChat agentId="my-agent">
221
+ <MyChatUI />
222
+ </CopilotChat>;
186
223
  ```
187
224
 
188
225
  ## Headless Import Path (custom UI, no chat/attachment native deps)
@@ -200,9 +237,10 @@ import {
200
237
  ```
201
238
 
202
239
  The default barrel (`@copilotkit/react-native`) statically re-exports the
203
- prebuilt chat components (`CopilotChat` / `CopilotModal` / `CopilotSidebar` /
204
- `CopilotPopup`, which import `@gorhom/bottom-sheet`) and `useAttachments` (which
205
- imports `expo-document-picker` + `expo-file-system`). Even though those are
240
+ chat components (`CopilotChat` / `CopilotModal` / `CopilotSidebar` /
241
+ `CopilotPopup`) and `useAttachments` (which imports `expo-document-picker` +
242
+ `expo-file-system`). The bottom-sheet modal that needs `@gorhom/bottom-sheet`
243
+ lives in `@copilotkit/react-native/components`. Even though those are
206
244
  optional peer dependencies, the static re-export forces Metro to resolve them at
207
245
  bundle time — so a headless consumer previously had to install every chat and
208
246
  attachment native dep, or stub them in `metro.config.js`, to get past
@@ -214,3 +252,332 @@ the render-tool registry, and the core/AG-UI types — none of the chat UI or
214
252
  `metro.config.js` stub workaround is no longer needed. Polyfills are still
215
253
  auto-installed, so no separate `import "@copilotkit/react-native/polyfills"` is
216
254
  required.
255
+
256
+ ## Generative UI (experimental)
257
+
258
+ `@copilotkit/react-native/generative-ui` lets the agent render a catalog of your
259
+ own native components with the `render_ui` tool. Install `zod` 3.25 or later:
260
+ every entry of this package needs it, because `@copilotkit/react-core` requires
261
+ it as a peer dependency (`@copilotkit/react-native` declares `zod` an optional
262
+ peer at `>=3.0.0` only because narrowing that range would be a breaking
263
+ change). Install zod 3 (`npm install "zod@^3.25"`) for a catalog that uses
264
+ `child()` or `childList()`: they return zod 3 schemas, which a zod 4 schema
265
+ cannot hold. The runtime needs no change by default: `CopilotRuntime` adds the
266
+ tool when the app sends a catalog with at least one component, unless the
267
+ server sets `generativeUI: false` or limits it with
268
+ `generativeUI: { agents: [...] }`. This example needs a `home` agent on the
269
+ runtime: once the runtime has connected, `useAgent` throws without it. `/generative-ui` is not in 1.85.0 or any earlier version; it first
270
+ ships in the release after 1.85.0.
271
+
272
+ ```tsx
273
+ import { useCallback, useEffect, useRef, useState } from "react";
274
+ import {
275
+ ActivityIndicator,
276
+ Pressable,
277
+ ScrollView,
278
+ Text,
279
+ View,
280
+ } from "react-native";
281
+ import { z } from "zod";
282
+ import {
283
+ CopilotKitCoreErrorCode,
284
+ CopilotKitCoreRuntimeConnectionStatus,
285
+ CopilotKitProvider,
286
+ useAgent,
287
+ useAgentContext,
288
+ useCopilotKit,
289
+ } from "@copilotkit/react-native/headless";
290
+ import {
291
+ GenerativeUIActivity,
292
+ GenerativeUIProvider,
293
+ createGenerativeUI,
294
+ isGenerativeUIActivity,
295
+ useGenerativeUIRuntime,
296
+ type GenerativeUIActivityMessage,
297
+ } from "@copilotkit/react-native/generative-ui";
298
+
299
+ const ui = createGenerativeUI({
300
+ id: "acme/bank@1",
301
+ components: {
302
+ BalanceCard: {
303
+ component: ({ account, amount }: { account: string; amount: number }) => (
304
+ <View>
305
+ <Text>{account}</Text>
306
+ <Text>{amount}</Text>
307
+ </View>
308
+ ),
309
+ description:
310
+ "The balance of one account. Copy the values from the context.",
311
+ props: z.object({ account: z.string(), amount: z.number() }),
312
+ },
313
+ },
314
+ });
315
+
316
+ type CopilotKit = ReturnType<typeof useCopilotKit>["copilotkit"];
317
+ type Agent = ReturnType<typeof useAgent>["agent"];
318
+
319
+ /**
320
+ * The errors that end a run. A failed tool call is not one of them
321
+ * (TOOL_HANDLER_FAILED, TOOL_ARGUMENT_PARSE_FAILED): its error goes back to
322
+ * the model as the result of the call, and the run goes on.
323
+ */
324
+ const RUN_FAILURES: ReadonlySet<CopilotKitCoreErrorCode> = new Set([
325
+ CopilotKitCoreErrorCode.AGENT_RUN_FAILED,
326
+ CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT,
327
+ CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,
328
+ CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED,
329
+ ]);
330
+
331
+ // Date.now() alone repeats within a millisecond; with a counter, ids do not.
332
+ let sent = 0;
333
+
334
+ /**
335
+ * Sends one user message and runs the agent. Resolves with the run's error,
336
+ * or undefined; it never rejects. It counts every run failure of this agent
337
+ * while it waits, so start one run of an agent at a time.
338
+ */
339
+ async function runTurn(copilotkit: CopilotKit, agent: Agent, content: string) {
340
+ const before = agent.messages.map((message) => message.id);
341
+ const { threadId } = agent;
342
+ let failure: Error | undefined;
343
+ const subscription = copilotkit.subscribe({
344
+ onError: ({ error, code, context }) => {
345
+ if (context.agentId === agent.agentId && RUN_FAILURES.has(code)) {
346
+ failure ??= error;
347
+ }
348
+ },
349
+ });
350
+ try {
351
+ sent += 1;
352
+ agent.addMessage({
353
+ id: `user-${Date.now()}-${sent}`,
354
+ role: "user",
355
+ content,
356
+ });
357
+ await copilotkit.runAgent({ agent });
358
+ } catch (error) {
359
+ failure ??= error instanceof Error ? error : new Error(String(error));
360
+ } finally {
361
+ subscription.unsubscribe();
362
+ }
363
+ try {
364
+ if (failure) takeBack(agent, before, threadId);
365
+ } catch (error) {
366
+ console.error("Could not take the failed turn back:", error);
367
+ }
368
+ return failure;
369
+ }
370
+
371
+ /**
372
+ * Removes the messages added since `before` (their ids), such as the user
373
+ * message and a partial reply. It keeps the surfaces: the provider keeps
374
+ * every surface that a run rendered, and the model still sees it, so the
375
+ * screen shows it too.
376
+ */
377
+ function takeBack(
378
+ agent: Agent,
379
+ before: readonly string[],
380
+ threadId: string | undefined,
381
+ ) {
382
+ // The agent moved to another thread: those messages are not this turn's.
383
+ if (agent.threadId !== threadId) return;
384
+ const kept = new Set(before);
385
+ agent.setMessages(
386
+ agent.messages.filter(
387
+ (message) => kept.has(message.id) || isGenerativeUIActivity(message),
388
+ ),
389
+ );
390
+ }
391
+
392
+ /**
393
+ * An activity message that GenerativeUIActivity draws: its surface is aimed at
394
+ * the chat (the target it shows) and the agent has not deleted it.
395
+ */
396
+ function isChatSurface(message: GenerativeUIActivityMessage) {
397
+ if (!isGenerativeUIActivity(message)) return false;
398
+ const content = message.content as {
399
+ target?: unknown;
400
+ operations?: unknown;
401
+ } | null;
402
+ const operations = Array.isArray(content?.operations)
403
+ ? content.operations
404
+ : [];
405
+ return (
406
+ content?.target === "chat" &&
407
+ !operations.some(
408
+ (op) => typeof op === "object" && op !== null && "deleteSurface" in op,
409
+ )
410
+ );
411
+ }
412
+
413
+ /**
414
+ * The chat surfaces that this device built, each message id with its operations,
415
+ * to tell whether a run rendered or updated one here. The operations alone: each
416
+ * call of the agent also refills the list of rejected operations, so a call whose
417
+ * updates were all rejected changes the content but not the surface. A surface
418
+ * whose createSurface the app rejected (`failed`) does not count: the app checks
419
+ * the operations again, prop values included, and GenerativeUIActivity then shows
420
+ * only an error line.
421
+ */
422
+ function chatSurfaces(
423
+ messages: readonly GenerativeUIActivityMessage[],
424
+ failed: (surfaceId: string) => boolean,
425
+ ) {
426
+ const built = new Map<string | undefined, string>();
427
+ for (const message of messages.filter(isChatSurface)) {
428
+ const { surfaceId, operations } = message.content as {
429
+ surfaceId?: unknown;
430
+ operations?: unknown;
431
+ };
432
+ if (typeof surfaceId === "string" && failed(surfaceId)) continue;
433
+ built.set(message.id, JSON.stringify(operations));
434
+ }
435
+ return built;
436
+ }
437
+
438
+ // Your app's data. The agent sees only what you give it with useAgentContext.
439
+ const accounts = [
440
+ { account: "Chequing", amount: 3482.1 },
441
+ { account: "Savings", amount: 6150 },
442
+ ];
443
+
444
+ function Home() {
445
+ const { copilotkit } = useCopilotKit();
446
+ // Until the runtime connects, `agent` is a stand-in (`isReady` is false). The
447
+ // registered agent replaces it, so a run started on the stand-in is lost.
448
+ // Once the runtime has connected, useAgent throws if it has no `home` agent.
449
+ const { agent, isReady } = useAgent({ agentId: "home" });
450
+ const runtime = useGenerativeUIRuntime();
451
+ // The thread it last checked: a ref, so StrictMode's second effect run sees it.
452
+ const checkedThread = useRef<string | undefined>(undefined);
453
+ const composing = useRef(false); // a ref, so a second tap is ignored at once
454
+ const [checked, setChecked] = useState(false);
455
+ const [busy, setBusy] = useState(false);
456
+ const [error, setError] = useState<string>();
457
+
458
+ useAgentContext({
459
+ description:
460
+ "The user's accounts. Show only these, with these exact balances.",
461
+ value: accounts,
462
+ });
463
+
464
+ const failed = useCallback(
465
+ (surfaceId: string) =>
466
+ !!runtime?.manager.getFailedSurface(agent.threadId, surfaceId),
467
+ [runtime, agent],
468
+ );
469
+
470
+ const compose = useCallback(async () => {
471
+ // A stand-in agent (not ready) would lose the run.
472
+ if (composing.current || !isReady) return;
473
+ composing.current = true;
474
+ setBusy(true);
475
+ setError(undefined);
476
+ try {
477
+ const before = agent.messages.map((message) => message.id);
478
+ const { threadId } = agent;
479
+ const shownBefore = chatSurfaces(agent.messages, failed);
480
+ const failure = await runTurn(copilotkit, agent, "Show my balances.");
481
+ const shownAfter = chatSurfaces(agent.messages, failed);
482
+ if (failure) {
483
+ // runTurn took the prompt back, so a retry sends it once.
484
+ setError(failure.message);
485
+ } else if (
486
+ ![...shownAfter].some(
487
+ ([id, content]) => shownBefore.get(id) !== content,
488
+ )
489
+ ) {
490
+ // This run rendered or updated nothing here. Take its prompt back too.
491
+ takeBack(agent, before, threadId);
492
+ setError("The agent rendered nothing for this screen.");
493
+ }
494
+ } catch (reason) {
495
+ setError(reason instanceof Error ? reason.message : String(reason));
496
+ } finally {
497
+ composing.current = false;
498
+ setBusy(false);
499
+ }
500
+ }, [agent, copilotkit, failed, isReady]);
501
+
502
+ // The agent and its messages live in the core and outlive this screen. Run only
503
+ // when the registered agent has no surface here yet and is not running, so a
504
+ // screen that mounts again shows what it has instead of composing it again.
505
+ // Check again when the agent moves to another thread, once it is not running
506
+ // and no compose is under way (`busy` reruns this when one ends).
507
+ useEffect(() => {
508
+ if (
509
+ !isReady ||
510
+ busy ||
511
+ composing.current ||
512
+ agent.isRunning ||
513
+ checkedThread.current === agent.threadId
514
+ ) {
515
+ return;
516
+ }
517
+ checkedThread.current = agent.threadId;
518
+ setChecked(true);
519
+ setError(undefined);
520
+ if (chatSurfaces(agent.messages, failed).size === 0) {
521
+ void compose();
522
+ }
523
+ }, [isReady, busy, agent, agent.threadId, agent.isRunning, compose, failed]);
524
+
525
+ const surfaces = agent.messages.filter(isChatSurface);
526
+ const built = chatSurfaces(agent.messages, failed);
527
+ const unreachable =
528
+ copilotkit.runtimeConnectionStatus ===
529
+ CopilotKitCoreRuntimeConnectionStatus.Error;
530
+ const waiting = !isReady || !checked || busy || agent.isRunning;
531
+
532
+ return (
533
+ <ScrollView contentContainerStyle={{ padding: 16 }}>
534
+ {surfaces.map((message) => (
535
+ <GenerativeUIActivity
536
+ key={message.id}
537
+ message={message}
538
+ agent={agent}
539
+ />
540
+ ))}
541
+ {unreachable ? (
542
+ <Text accessibilityRole="alert">
543
+ Can't reach the agent. Check the runtime URL.
544
+ </Text>
545
+ ) : waiting ? (
546
+ <ActivityIndicator />
547
+ ) : error || built.size === 0 ? (
548
+ <Pressable accessibilityRole="button" onPress={() => void compose()}>
549
+ <Text>
550
+ Couldn't load your balances{error ? ` (${error})` : ""}. Tap to try
551
+ again.
552
+ </Text>
553
+ </Pressable>
554
+ ) : null}
555
+ </ScrollView>
556
+ );
557
+ }
558
+
559
+ export default function App() {
560
+ return (
561
+ <CopilotKitProvider runtimeUrl="https://your-server/api/copilotkit">
562
+ <GenerativeUIProvider ui={ui}>
563
+ <Home />
564
+ </GenerativeUIProvider>
565
+ </CopilotKitProvider>
566
+ );
567
+ }
568
+ ```
569
+
570
+ `GenerativeUIActivity` renders the surface of one activity message, in your own
571
+ message list or on a screen with no chat. Like the web chat, it shows only
572
+ surfaces aimed at the chat; pass `target` to show another target. It renders
573
+ nothing (and warns in development) without a `GenerativeUIProvider`, under a
574
+ provider without `ui`, or while the agent has no `threadId`. The example shows
575
+ a spinner, an unreachable runtime and a retry with the reason. A failed run's
576
+ prompt is taken back, but the surfaces it rendered stay: the provider and the
577
+ model keep them. The docs add a chat list.
578
+ `GenerativeUISurface` marks a named place in the app; `style` applies while its
579
+ fallback shows too. Tool transport only; there is no standard catalog, no
580
+ `theme` prop (a `theme` passed from JavaScript is dropped with a development
581
+ warning) and no `openUrl` (it fails with "openUrl is not available on this
582
+ platform"), and the prebuilt `CopilotChat` does not draw surfaces yet. See the
583
+ [React Native docs](https://docs.copilotkit.ai/react-native#generative-ui-with-your-own-components).
@@ -1,6 +1,6 @@
1
1
  import React, { ReactNode } from "react";
2
- import { CopilotKitCoreErrorCode, CopilotKitMessageFilter } from "@copilotkit/core";
3
2
  import { DebugConfig } from "@copilotkit/shared";
3
+ import { CopilotKitCoreErrorCode, CopilotKitMessageFilter } from "@copilotkit/core";
4
4
 
5
5
  //#region src/CopilotKitProvider.d.ts
6
6
  interface CopilotKitNativeProviderProps {
@@ -92,4 +92,4 @@ interface CopilotKitNativeProviderProps {
92
92
  declare const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps>;
93
93
  //#endregion
94
94
  export { CopilotKitProvider as n, CopilotKitNativeProviderProps as t };
95
- //# sourceMappingURL=CopilotKitProvider-DBq4AhRP.d.cts.map
95
+ //# sourceMappingURL=CopilotKitProvider-CQ-DpvY1.d.cts.map
@@ -118,4 +118,4 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp, creden
118
118
 
119
119
  //#endregion
120
120
  export { CopilotKitProvider as t };
121
- //# sourceMappingURL=CopilotKitProvider-D8sn7G_C.mjs.map
121
+ //# sourceMappingURL=CopilotKitProvider-CXQGv39c.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CopilotKitProvider-D8sn7G_C.mjs","names":[],"sources":["../src/CopilotKitProvider.tsx"],"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 {\n CopilotKitCoreErrorCode,\n CopilotKitMessageFilter,\n} from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /**\n * Rewrites the message list sent to runtime agents on every run.\n *\n * CopilotKit sends the whole thread each time. When your agent already\n * stores the conversation, most of that payload is waste, and an agent that\n * merges the inbound list with its own store can show the model every turn\n * twice. Return the messages to send:\n *\n * ```tsx\n * <CopilotKitProvider\n * runtimeUrl=\"/api/copilotkit\"\n * messageFilter={(messages) => messages.slice(-1)}\n * />\n * ```\n *\n * The filter changes the request body only. The transcript the UI renders is\n * untouched. Broken tool-call pairs are repaired before the request is sent,\n * so a filter this blunt cannot strand a tool result mid-HITL.\n *\n * Agents reached through your CopilotRuntime honor this. An agent your app\n * passes in directly does not, and neither Intelligence runs nor suggestion\n * runs are ever filtered.\n *\n * Prefer a stable reference (`useCallback`). An inline arrow re-registers the\n * filter on every render, which is harmless but needless.\n */\n messageFilter?: CopilotKitMessageFilter;\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 * `true` logs event and lifecycle summaries. Pass `{ verbose: true }` for\n * full event payloads.\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 messageFilter,\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 messageFilter,\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.setMessageFilter(messageFilter);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n messageFilter,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n {children}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,eACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,OAAO,gBAAgB,aAAa,aAAa,GAAG;CAKtD,MAAM,gBAAgB,cACd,mBAAmB,EAAE,EAC3B,CAAC,KAAK,UAAU,gBAAgB,CAAC,CAClC;CAED,MAAM,mBAAmB,cACjB,cAAc,EAAE,EACtB,CAAC,KAAK,UAAU,WAAW,CAAC,CAC7B;CAED,MAAM,gBAAgB,OAA2C,KAAK;AAEtE,KAAI,cAAc,YAAY,MAAM;EAClC,MAAM,WAAwC,IAAI,oBAAoB;GACpE;GACA,kBACE,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA;GACR,SAAS;GACT;GACA;GACA,YAAY;GACZ;GACD,CAAC;AAGF,MAAI,sBAAsB,OACxB,UAAS,qBAAqB,kBAAkB;AAElD,gBAAc,UAAU;;CAG1B,MAAM,aAAa,cAAc;AAGjC,iBAAgB;AACd,aAAW,cAAc,WAAW;AACpC,aAAW,oBACT,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA,OACP;AACD,aAAW,WAAW,cAAc;AACpC,aAAW,eAAe,YAAY;AACtC,aAAW,iBAAiB,cAAc;AAC1C,aAAW,cAAc,iBAAiB;AAC1C,aAAW,SAAS,MAAM;IACzB;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAKF,iBAAgB;AACd,aAAW,qBAAqB,kBAAkB;IACjD,CAAC,YAAY,kBAAkB,CAAC;CAKnC,MAAM,CAAC,sBAAsB,2BAA2B,+BAEhD,IAAI,KAAK,CAAC;CAElB,MAAM,CAAC,sBAAsB,2BAA2B,SAEtD,OAAU;CAGZ,MAAM,aAAa,OAAO,QAAQ;AAClC,iBAAgB;AACd,aAAW,UAAU;IACpB,CAAC,QAAQ,CAAC;AAKb,iBAAgB;EACd,MAAM,eAAe,WAAW,UAAU;GACxC,uBAAuB,EAAE,iBAAiB;AACxC,6BAAyB,SAAS;AAChC,SAAI,KAAK,IAAI,WAAW,CAAE,QAAO;KACjC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,IAAI,WAAW;AACpB,YAAO;MACP;;GAEJ,qBAAqB,EAAE,iBAAiB;AACtC,6BAAyB,SAAS;AAChC,SAAI,CAAC,KAAK,IAAI,WAAW,CAAE,QAAO;KAClC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,OAAO,WAAW;AACvB,YAAO;MACP;;GAEJ,UAAU,UAAU;AAClB,QAAI,WAAW,QACb,YAAW,QAAQ,MAAM;QAEzB,SAAQ,MACN,uBAAuB,MAAM,KAAK,KAClC,MAAM,OACN,MAAM,WAAW,EAAE,CACpB;;GAGL,wCAAwC;AACtC,4BAAwB,WAAW,cAAc;;GAEpD,CAAC;AACF,eAAa,aAAa,aAAa;IACtC,CAAC,WAAW,CAAC;CAEhB,MAAM,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;GAC7B;IACuB;GACC"}
1
+ {"version":3,"file":"CopilotKitProvider-CXQGv39c.mjs","names":[],"sources":["../src/CopilotKitProvider.tsx"],"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 {\n CopilotKitCoreErrorCode,\n CopilotKitMessageFilter,\n} from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /**\n * Rewrites the message list sent to runtime agents on every run.\n *\n * CopilotKit sends the whole thread each time. When your agent already\n * stores the conversation, most of that payload is waste, and an agent that\n * merges the inbound list with its own store can show the model every turn\n * twice. Return the messages to send:\n *\n * ```tsx\n * <CopilotKitProvider\n * runtimeUrl=\"/api/copilotkit\"\n * messageFilter={(messages) => messages.slice(-1)}\n * />\n * ```\n *\n * The filter changes the request body only. The transcript the UI renders is\n * untouched. Broken tool-call pairs are repaired before the request is sent,\n * so a filter this blunt cannot strand a tool result mid-HITL.\n *\n * Agents reached through your CopilotRuntime honor this. An agent your app\n * passes in directly does not, and neither Intelligence runs nor suggestion\n * runs are ever filtered.\n *\n * Prefer a stable reference (`useCallback`). An inline arrow re-registers the\n * filter on every render, which is harmless but needless.\n */\n messageFilter?: CopilotKitMessageFilter;\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 * `true` logs event and lifecycle summaries. Pass `{ verbose: true }` for\n * full event payloads.\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 messageFilter,\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 messageFilter,\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.setMessageFilter(messageFilter);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n messageFilter,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n {children}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,eACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,OAAO,gBAAgB,aAAa,aAAa,GAAG;CAKtD,MAAM,gBAAgB,cACd,mBAAmB,EAAE,EAC3B,CAAC,KAAK,UAAU,gBAAgB,CAAC,CAClC;CAED,MAAM,mBAAmB,cACjB,cAAc,EAAE,EACtB,CAAC,KAAK,UAAU,WAAW,CAAC,CAC7B;CAED,MAAM,gBAAgB,OAA2C,KAAK;AAEtE,KAAI,cAAc,YAAY,MAAM;EAClC,MAAM,WAAwC,IAAI,oBAAoB;GACpE;GACA,kBACE,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA;GACR,SAAS;GACT;GACA;GACA,YAAY;GACZ;GACD,CAAC;AAGF,MAAI,sBAAsB,OACxB,UAAS,qBAAqB,kBAAkB;AAElD,gBAAc,UAAU;;CAG1B,MAAM,aAAa,cAAc;AAGjC,iBAAgB;AACd,aAAW,cAAc,WAAW;AACpC,aAAW,oBACT,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA,OACP;AACD,aAAW,WAAW,cAAc;AACpC,aAAW,eAAe,YAAY;AACtC,aAAW,iBAAiB,cAAc;AAC1C,aAAW,cAAc,iBAAiB;AAC1C,aAAW,SAAS,MAAM;IACzB;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAKF,iBAAgB;AACd,aAAW,qBAAqB,kBAAkB;IACjD,CAAC,YAAY,kBAAkB,CAAC;CAKnC,MAAM,CAAC,sBAAsB,2BAA2B,+BAEhD,IAAI,KAAK,CAAC;CAElB,MAAM,CAAC,sBAAsB,2BAA2B,SAEtD,OAAU;CAGZ,MAAM,aAAa,OAAO,QAAQ;AAClC,iBAAgB;AACd,aAAW,UAAU;IACpB,CAAC,QAAQ,CAAC;AAKb,iBAAgB;EACd,MAAM,eAAe,WAAW,UAAU;GACxC,uBAAuB,EAAE,iBAAiB;AACxC,6BAAyB,SAAS;AAChC,SAAI,KAAK,IAAI,WAAW,CAAE,QAAO;KACjC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,IAAI,WAAW;AACpB,YAAO;MACP;;GAEJ,qBAAqB,EAAE,iBAAiB;AACtC,6BAAyB,SAAS;AAChC,SAAI,CAAC,KAAK,IAAI,WAAW,CAAE,QAAO;KAClC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,OAAO,WAAW;AACvB,YAAO;MACP;;GAEJ,UAAU,UAAU;AAClB,QAAI,WAAW,QACb,YAAW,QAAQ,MAAM;QAEzB,SAAQ,MACN,uBAAuB,MAAM,KAAK,KAClC,MAAM,OACN,MAAM,WAAW,EAAE,CACpB;;GAGL,wCAAwC;AACtC,4BAAwB,WAAW,cAAc;;GAEpD,CAAC;AACF,eAAa,aAAa,aAAa;IACtC,CAAC,WAAW,CAAC;CAEhB,MAAM,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;GAC7B;IACuB;GACC"}
@@ -92,4 +92,4 @@ interface CopilotKitNativeProviderProps {
92
92
  declare const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps>;
93
93
  //#endregion
94
94
  export { CopilotKitProvider as n, CopilotKitNativeProviderProps as t };
95
- //# sourceMappingURL=CopilotKitProvider-fW21Gb7T.d.mts.map
95
+ //# sourceMappingURL=CopilotKitProvider-Dc1Vbv7K.d.mts.map
@@ -125,4 +125,4 @@ Object.defineProperty(exports, 'CopilotKitProvider', {
125
125
  return CopilotKitProvider;
126
126
  }
127
127
  });
128
- //# sourceMappingURL=CopilotKitProvider-CjoPnabW.cjs.map
128
+ //# sourceMappingURL=CopilotKitProvider-zSfbWwIg.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CopilotKitProvider-CjoPnabW.cjs","names":["CopilotKitCoreReact","CopilotKitContext","LicenseContext"],"sources":["../src/CopilotKitProvider.tsx"],"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 {\n CopilotKitCoreErrorCode,\n CopilotKitMessageFilter,\n} from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /**\n * Rewrites the message list sent to runtime agents on every run.\n *\n * CopilotKit sends the whole thread each time. When your agent already\n * stores the conversation, most of that payload is waste, and an agent that\n * merges the inbound list with its own store can show the model every turn\n * twice. Return the messages to send:\n *\n * ```tsx\n * <CopilotKitProvider\n * runtimeUrl=\"/api/copilotkit\"\n * messageFilter={(messages) => messages.slice(-1)}\n * />\n * ```\n *\n * The filter changes the request body only. The transcript the UI renders is\n * untouched. Broken tool-call pairs are repaired before the request is sent,\n * so a filter this blunt cannot strand a tool result mid-HITL.\n *\n * Agents reached through your CopilotRuntime honor this. An agent your app\n * passes in directly does not, and neither Intelligence runs nor suggestion\n * runs are ever filtered.\n *\n * Prefer a stable reference (`useCallback`). An inline arrow re-registers the\n * filter on every render, which is harmless but needless.\n */\n messageFilter?: CopilotKitMessageFilter;\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 * `true` logs event and lifecycle summaries. Pass `{ verbose: true }` for\n * full event payloads.\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 messageFilter,\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 messageFilter,\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.setMessageFilter(messageFilter);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n messageFilter,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n {children}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,eACA,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;GACA,YAAY;GACZ;GACD,CAAC;AAGF,MAAI,sBAAsB,OACxB,UAAS,qBAAqB,kBAAkB;AAElD,gBAAc,UAAU;;CAG1B,MAAM,aAAa,cAAc;AAGjC,4BAAgB;AACd,aAAW,cAAc,WAAW;AACpC,aAAW,oBACT,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA,OACP;AACD,aAAW,WAAW,cAAc;AACpC,aAAW,eAAe,YAAY;AACtC,aAAW,iBAAiB,cAAc;AAC1C,aAAW,cAAc,iBAAiB;AAC1C,aAAW,SAAS,MAAM;IACzB;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAKF,4BAAgB;AACd,aAAW,qBAAqB,kBAAkB;IACjD,CAAC,YAAY,kBAAkB,CAAC;CAKnC,MAAM,CAAC,sBAAsB,qEAErB,IAAI,KAAK,CAAC;CAElB,MAAM,CAAC,sBAAsB,+CAE3B,OAAU;CAGZ,MAAM,+BAAoB,QAAQ;AAClC,4BAAgB;AACd,aAAW,UAAU;IACpB,CAAC,QAAQ,CAAC;AAKb,4BAAgB;EACd,MAAM,eAAe,WAAW,UAAU;GACxC,uBAAuB,EAAE,iBAAiB;AACxC,6BAAyB,SAAS;AAChC,SAAI,KAAK,IAAI,WAAW,CAAE,QAAO;KACjC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,IAAI,WAAW;AACpB,YAAO;MACP;;GAEJ,qBAAqB,EAAE,iBAAiB;AACtC,6BAAyB,SAAS;AAChC,SAAI,CAAC,KAAK,IAAI,WAAW,CAAE,QAAO;KAClC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,OAAO,WAAW;AACvB,YAAO;MACP;;GAEJ,UAAU,UAAU;AAClB,QAAI,WAAW,QACb,YAAW,QAAQ,MAAM;QAEzB,SAAQ,MACN,uBAAuB,MAAM,KAAK,KAClC,MAAM,OACN,MAAM,WAAW,EAAE,CACpB;;GAGL,wCAAwC;AACtC,4BAAwB,WAAW,cAAc;;GAEpD,CAAC;AACF,eAAa,aAAa,aAAa;IACtC,CAAC,WAAW,CAAC;CAEhB,MAAM,yCACG;EACL;EACA;EACD,GACD,CAAC,YAAY,qBAAqB,CACnC;CAGD,MAAM,iGAC4B,qBAAqB,EACrD,CAAC,qBAAqB,CACvB;AAED,QACE,2CAACC,oDAAkB;EAAS,OAAO;YACjC,2CAACC,iDAAe;GAAS,OAAO;GAC7B;IACuB;GACC"}
1
+ {"version":3,"file":"CopilotKitProvider-zSfbWwIg.cjs","names":["CopilotKitCoreReact","CopilotKitContext","LicenseContext"],"sources":["../src/CopilotKitProvider.tsx"],"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 {\n CopilotKitCoreErrorCode,\n CopilotKitMessageFilter,\n} from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /**\n * Rewrites the message list sent to runtime agents on every run.\n *\n * CopilotKit sends the whole thread each time. When your agent already\n * stores the conversation, most of that payload is waste, and an agent that\n * merges the inbound list with its own store can show the model every turn\n * twice. Return the messages to send:\n *\n * ```tsx\n * <CopilotKitProvider\n * runtimeUrl=\"/api/copilotkit\"\n * messageFilter={(messages) => messages.slice(-1)}\n * />\n * ```\n *\n * The filter changes the request body only. The transcript the UI renders is\n * untouched. Broken tool-call pairs are repaired before the request is sent,\n * so a filter this blunt cannot strand a tool result mid-HITL.\n *\n * Agents reached through your CopilotRuntime honor this. An agent your app\n * passes in directly does not, and neither Intelligence runs nor suggestion\n * runs are ever filtered.\n *\n * Prefer a stable reference (`useCallback`). An inline arrow re-registers the\n * filter on every render, which is harmless but needless.\n */\n messageFilter?: CopilotKitMessageFilter;\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 * `true` logs event and lifecycle summaries. Pass `{ verbose: true }` for\n * full event payloads.\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 messageFilter,\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 messageFilter,\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.setMessageFilter(messageFilter);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n messageFilter,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n {children}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,eACA,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;GACA,YAAY;GACZ;GACD,CAAC;AAGF,MAAI,sBAAsB,OACxB,UAAS,qBAAqB,kBAAkB;AAElD,gBAAc,UAAU;;CAG1B,MAAM,aAAa,cAAc;AAGjC,4BAAgB;AACd,aAAW,cAAc,WAAW;AACpC,aAAW,oBACT,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA,OACP;AACD,aAAW,WAAW,cAAc;AACpC,aAAW,eAAe,YAAY;AACtC,aAAW,iBAAiB,cAAc;AAC1C,aAAW,cAAc,iBAAiB;AAC1C,aAAW,SAAS,MAAM;IACzB;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAKF,4BAAgB;AACd,aAAW,qBAAqB,kBAAkB;IACjD,CAAC,YAAY,kBAAkB,CAAC;CAKnC,MAAM,CAAC,sBAAsB,qEAErB,IAAI,KAAK,CAAC;CAElB,MAAM,CAAC,sBAAsB,+CAE3B,OAAU;CAGZ,MAAM,+BAAoB,QAAQ;AAClC,4BAAgB;AACd,aAAW,UAAU;IACpB,CAAC,QAAQ,CAAC;AAKb,4BAAgB;EACd,MAAM,eAAe,WAAW,UAAU;GACxC,uBAAuB,EAAE,iBAAiB;AACxC,6BAAyB,SAAS;AAChC,SAAI,KAAK,IAAI,WAAW,CAAE,QAAO;KACjC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,IAAI,WAAW;AACpB,YAAO;MACP;;GAEJ,qBAAqB,EAAE,iBAAiB;AACtC,6BAAyB,SAAS;AAChC,SAAI,CAAC,KAAK,IAAI,WAAW,CAAE,QAAO;KAClC,MAAM,OAAO,IAAI,IAAI,KAAK;AAC1B,UAAK,OAAO,WAAW;AACvB,YAAO;MACP;;GAEJ,UAAU,UAAU;AAClB,QAAI,WAAW,QACb,YAAW,QAAQ,MAAM;QAEzB,SAAQ,MACN,uBAAuB,MAAM,KAAK,KAClC,MAAM,OACN,MAAM,WAAW,EAAE,CACpB;;GAGL,wCAAwC;AACtC,4BAAwB,WAAW,cAAc;;GAEpD,CAAC;AACF,eAAa,aAAa,aAAa;IACtC,CAAC,WAAW,CAAC;CAEhB,MAAM,yCACG;EACL;EACA;EACD,GACD,CAAC,YAAY,qBAAqB,CACnC;CAGD,MAAM,iGAC4B,qBAAqB,EACrD,CAAC,qBAAqB,CACvB;AAED,QACE,2CAACC,oDAAkB;EAAS,OAAO;YACjC,2CAACC,iDAAe;GAAS,OAAO;GAC7B;IACuB;GACC"}
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_chunk = require('../chunk-C0xms8kb.cjs');
3
+ require('../polyfills.cjs');
3
4
  let react = require("react");
4
5
  react = require_chunk.__toESM(react);
5
6
  let _copilotkit_react_core_v2_context = require("@copilotkit/react-core/v2/context");